mysql.go 1.7 KB

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