user.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package repositories
  2. import (
  3. "context"
  4. "fmt"
  5. sq "github.com/Masterminds/squirrel"
  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(ctx context.Context, username string) (*models.User, error) {
  18. var res models.User
  19. q, v, err := sq.Select("id", "username", "password", "created_at", "updated_at").
  20. From(userTableName).
  21. PlaceholderFormat(sq.Dollar).
  22. Where(sq.Eq{"username": username}).
  23. ToSql()
  24. if err != nil {
  25. return nil, fmt.Errorf("build query: %w", err)
  26. }
  27. err = u.db.GetContext(ctx, &res, q, v...)
  28. if err != nil {
  29. return nil, fmt.Errorf("get: %w", err)
  30. }
  31. return &res, nil
  32. }
  33. func (u UserRepository) Add(ctx context.Context, username string, password string) (uint64, error) {
  34. q, v, err := sq.Insert(userTableName).
  35. PlaceholderFormat(sq.Dollar).
  36. Columns("username", "password").
  37. Values(username, password).
  38. Suffix("RETURNING id").
  39. ToSql()
  40. if err != nil {
  41. return 0, fmt.Errorf("build query: %w", err)
  42. }
  43. var id uint64
  44. if err = u.db.QueryRowContext(ctx, q, v...).Scan(&id); err != nil {
  45. return 0, fmt.Errorf("query row: %w", err)
  46. }
  47. return id, nil
  48. }
  49. func (u UserRepository) UpdatePassword(ctx context.Context, id uint64, newPassword string) error {
  50. q, v, err := sq.Update(userTableName).
  51. PlaceholderFormat(sq.Dollar).
  52. Set("password", newPassword).
  53. Set("updated_at", "NOW()").
  54. Where(sq.Eq{"id": id}).
  55. ToSql()
  56. if err != nil {
  57. return fmt.Errorf("build query: %w", err)
  58. }
  59. _, err = u.db.ExecContext(ctx, q, v...)
  60. if err != nil {
  61. return fmt.Errorf("exec: %w", err)
  62. }
  63. return nil
  64. }