user.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package repositories
  2. //go:generate mkdir -p mocks
  3. //go:generate rm -rf ./mocks/*_minimock.go
  4. //go:generate minimock -i git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/interfaces.UserRepository -o ./mocks/ -s "_minimock.go"
  5. import (
  6. "context"
  7. "database/sql"
  8. "git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/interfaces"
  9. "git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/models"
  10. sq "github.com/Masterminds/squirrel"
  11. )
  12. const (
  13. userTableName = "\"user\""
  14. )
  15. type userRepository struct {
  16. db *sql.DB
  17. }
  18. func InitUserRepository(db *sql.DB) interfaces.UserRepository {
  19. return userRepository{db: db}
  20. }
  21. func (u userRepository) Get(ctx context.Context, username string) (*models.User, error) {
  22. query, args, err := sq.Select("id", "username", "password", "created_at", "updated_at").
  23. From(userTableName).
  24. PlaceholderFormat(sq.Dollar).
  25. Where(sq.Eq{"username": username}).
  26. ToSql()
  27. if err != nil {
  28. return nil, err
  29. }
  30. var res models.User
  31. err = u.db.QueryRowContext(ctx, query, args...).
  32. Scan(&res.ID, &res.Username, &res.Password, &res.CreatedAt, &res.UpdatedAt)
  33. if err != nil {
  34. return nil, err
  35. }
  36. return &res, nil
  37. }
  38. func (u userRepository) Add(ctx context.Context, username string, password string) (int, error) {
  39. query, args, err := sq.Insert(userTableName).
  40. PlaceholderFormat(sq.Dollar).
  41. Columns("username", "password").
  42. Values(username, password).
  43. Suffix("RETURNING id").
  44. ToSql()
  45. if err != nil {
  46. return 0, err
  47. }
  48. var id int
  49. if err = u.db.QueryRowContext(ctx, query, args...).Scan(&id); err != nil {
  50. return 0, err
  51. }
  52. return id, nil
  53. }
  54. func (u userRepository) UpdatePassword(ctx context.Context, id int, newPassword string) error {
  55. query, args, err := sq.Update(userTableName).
  56. PlaceholderFormat(sq.Dollar).
  57. Set("password", newPassword).
  58. Set("updated_at", "NOW()").
  59. Where(sq.Eq{"id": id}).
  60. ToSql()
  61. if err != nil {
  62. return err
  63. }
  64. _, err = u.db.ExecContext(ctx, query, args...)
  65. return err
  66. }