user.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package repositories
  2. import (
  3. "context"
  4. "fmt"
  5. sq "github.com/Masterminds/squirrel"
  6. "git.dmitriygnatenko.ru/dima/homethings/internal/models"
  7. )
  8. const userTableName = "\"user\""
  9. var userTableFields = []string{"id", "username", "password", "created_at", "updated_at"}
  10. type UserRepository struct {
  11. db DB
  12. }
  13. func InitUserRepository(db DB) *UserRepository {
  14. return &UserRepository{db: db}
  15. }
  16. func (r UserRepository) Get(ctx context.Context, username string) (*models.User, error) {
  17. q, v, err := sq.Select(userTableFields...).
  18. From(userTableName).
  19. PlaceholderFormat(sq.Dollar).
  20. Where(sq.Eq{"username": username}).
  21. ToSql()
  22. if err != nil {
  23. return nil, fmt.Errorf("build query: %w", err)
  24. }
  25. var res models.User
  26. err = r.db.GetContext(ctx, &res, q, v...)
  27. if err != nil {
  28. return nil, fmt.Errorf("get: %w", err)
  29. }
  30. return &res, nil
  31. }
  32. func (r UserRepository) Add(ctx context.Context, username string, password string) (uint64, error) {
  33. q, v, err := sq.Insert(userTableName).
  34. PlaceholderFormat(sq.Dollar).
  35. Columns("username", "password").
  36. Values(username, password).
  37. Suffix("RETURNING id").
  38. ToSql()
  39. if err != nil {
  40. return 0, fmt.Errorf("build query: %w", err)
  41. }
  42. var id uint64
  43. err = r.db.QueryRowContext(ctx, q, v...).Scan(&id)
  44. if err != nil {
  45. return 0, fmt.Errorf("exec: %w", err)
  46. }
  47. return id, nil
  48. }
  49. func (r UserRepository) Update(ctx context.Context, req models.UpdateUserRequest) error {
  50. qb := sq.Update(userTableName).
  51. PlaceholderFormat(sq.Dollar).
  52. Set("updated_at", "NOW()").
  53. Where(sq.Eq{"id": req.ID})
  54. if req.Username.Valid {
  55. qb = qb.Set("username", req.Username.String)
  56. }
  57. if req.Password.Valid {
  58. qb = qb.Set("password", req.Password.String)
  59. }
  60. q, v, err := qb.ToSql()
  61. if err != nil {
  62. return fmt.Errorf("build query: %w", err)
  63. }
  64. _, err = r.db.ExecContext(ctx, q, v...)
  65. if err != nil {
  66. return fmt.Errorf("exec: %w", err)
  67. }
  68. return nil
  69. }