user.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. package repositories
  2. import (
  3. "context"
  4. sq "github.com/Masterminds/squirrel"
  5. "git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/helpers/errors"
  6. "git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/models"
  7. )
  8. const (
  9. userTableName = "user"
  10. )
  11. type UserRepository struct {
  12. db DB
  13. }
  14. func InitUserRepository(db DB) *UserRepository {
  15. return &UserRepository{db: db}
  16. }
  17. func (u UserRepository) Get( // TESTED
  18. ctx context.Context,
  19. username string,
  20. ) (*models.User, error) {
  21. var res models.User
  22. q, v, err := sq.Select("id", "username", "password", "created_at", "updated_at").
  23. From(userTableName).
  24. PlaceholderFormat(placeholder).
  25. Where(sq.Eq{"username": username}).
  26. ToSql()
  27. if err != nil {
  28. return nil, errors.Wrap(err, "build query")
  29. }
  30. err = u.db.GetContext(ctx, &res, q, v...)
  31. if err != nil {
  32. return nil, errors.Wrap(err, "get")
  33. }
  34. return &res, nil
  35. }
  36. func (u UserRepository) Add(
  37. ctx context.Context,
  38. username string,
  39. password string,
  40. ) (uint64, error) {
  41. q, v, err := sq.Insert(userTableName).
  42. PlaceholderFormat(placeholder).
  43. Columns("username", "password").
  44. Values(username, password).
  45. Suffix("RETURNING id").
  46. ToSql()
  47. if err != nil {
  48. return 0, errors.Wrap(err, "build query")
  49. }
  50. res, err := u.db.ExecContext(ctx, q, v...)
  51. if err != nil {
  52. return 0, errors.Wrap(err, "exec")
  53. }
  54. id, err := res.LastInsertId()
  55. if err != nil {
  56. return 0, errors.Wrap(err, "can't get last insert id")
  57. }
  58. return uint64(id), nil
  59. }
  60. func (u UserRepository) UpdatePassword(
  61. ctx context.Context,
  62. id uint64,
  63. newPassword string,
  64. ) error {
  65. q, v, err := sq.Update(userTableName).
  66. PlaceholderFormat(placeholder).
  67. Set("password", newPassword).
  68. Set("updated_at", "NOW()").
  69. Where(sq.Eq{"id": id}).
  70. ToSql()
  71. if err != nil {
  72. return errors.Wrap(err, "build query")
  73. }
  74. _, err = u.db.ExecContext(ctx, q, v...)
  75. if err != nil {
  76. return errors.Wrap(err, "exec")
  77. }
  78. return nil
  79. }