mysql.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package infrastructure
  2. import (
  3. "database/sql"
  4. "code.osinet.fr/fgm/kurz/domain"
  5. _ "github.com/go-sql-driver/mysql"
  6. )
  7. type MySQLShortURLRepository struct {
  8. DB *sql.DB
  9. }
  10. type MySQLTargetURLRepository struct {
  11. DB *sql.DB
  12. }
  13. func (sr MySQLShortURLRepository) GetTarget(su domain.ShortURL) (domain.TargetURL, error) {
  14. var tu domain.TargetURL
  15. row := sr.DB.QueryRow(`
  16. SELECT map.url
  17. FROM map
  18. WHERE map.hash = ?
  19. `, su.URL)
  20. err := row.Scan(&tu.URL)
  21. switch err {
  22. case sql.ErrNoRows:
  23. err = domain.MakeError(domain.ShortNotFound, string(su.URL))
  24. case nil:
  25. break
  26. default:
  27. err = domain.MakeError(domain.StorageReadError, "")
  28. }
  29. return tu, err
  30. }
  31. func (tr MySQLTargetURLRepository) GetShort(tu domain.TargetURL) (su domain.ShortURL, isNew bool, err error) {
  32. // TODO future versions may have multiple shorts for a target, and choose a
  33. // specific short based on the domain and Kurz user. For now just ensure we
  34. // don't get more than one.
  35. row := tr.DB.QueryRow(`
  36. SELECT map.hash
  37. FROM map
  38. LIMIT 1
  39. `)
  40. err = row.Scan(&su.URL)
  41. switch err {
  42. case sql.ErrNoRows:
  43. // If it doesn't exist, attempt to create it.
  44. su, err = domain.NewUnspecifiedShortURL(tu)
  45. if err != nil {
  46. // Creation failed.
  47. return su, false, err
  48. }
  49. _, err = tr.DB.Exec(`
  50. INSERT INTO map(hash, url, date1, date2, date3, refcount)
  51. VALUES (?, ?, CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP(), 0)
  52. `, su.URL, tu.URL)
  53. if err != nil {
  54. err = domain.MakeError(domain.StorageWriteError, "storing new mapping")
  55. }
  56. isNew = true
  57. case nil:
  58. break
  59. default:
  60. err = domain.MakeError(domain.StorageReadError, "looking for mapping")
  61. }
  62. return
  63. }