user.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. package repository
  2. import (
  3. "context"
  4. sq "github.com/Masterminds/squirrel"
  5. "git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/helper/errors"
  6. "git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/model"
  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(
  18. ctx context.Context,
  19. username string,
  20. ) (*model.User, error) {
  21. var res model.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. ToSql()
  46. if err != nil {
  47. return 0, errors.Wrap(err, "build query")
  48. }
  49. res, err := u.db.ExecContext(ctx, q, v...)
  50. if err != nil {
  51. return 0, errors.Wrap(err, "exec")
  52. }
  53. id, err := res.LastInsertId()
  54. if err != nil {
  55. return 0, errors.Wrap(err, "can't get last insert id")
  56. }
  57. return uint64(id), nil
  58. }
  59. func (u UserRepository) UpdatePassword(
  60. ctx context.Context,
  61. id uint64,
  62. newPassword string,
  63. ) error {
  64. q, v, err := sq.Update(userTableName).
  65. PlaceholderFormat(placeholder).
  66. Set("password", newPassword).
  67. Where(sq.Eq{"id": id}).
  68. ToSql()
  69. if err != nil {
  70. return errors.Wrap(err, "build query")
  71. }
  72. _, err = u.db.ExecContext(ctx, q, v...)
  73. if err != nil {
  74. return errors.Wrap(err, "exec")
  75. }
  76. return nil
  77. }