user.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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/homethings/internal/interfaces.UserRepository -o ./mocks/ -s "_minimock.go"
  5. import (
  6. "context"
  7. "database/sql"
  8. "git.dmitriygnatenko.ru/dima/homethings/internal/interfaces"
  9. "git.dmitriygnatenko.ru/dima/homethings/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 (r 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 = r.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 (r 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 = r.db.QueryRowContext(ctx, query, args...).Scan(&id); err != nil {
  50. return 0, err
  51. }
  52. return id, nil
  53. }
  54. func (r userRepository) Update(ctx context.Context, req models.UpdateUserRequest) error {
  55. qb := sq.Update(userTableName).
  56. PlaceholderFormat(sq.Dollar).
  57. Set("updated_at", "NOW()").
  58. Where(sq.Eq{"id": req.ID})
  59. if req.Username.Valid {
  60. qb = qb.Set("username", req.Username.String)
  61. }
  62. if req.Password.Valid {
  63. qb = qb.Set("password", req.Password.String)
  64. }
  65. query, args, err := qb.ToSql()
  66. if err != nil {
  67. return err
  68. }
  69. _, err = r.db.ExecContext(ctx, query, args...)
  70. return err
  71. }