user.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. res, err := r.db.ExecContext(ctx, q, v...)
  43. if err != nil {
  44. return 0, fmt.Errorf("exec: %w", err)
  45. }
  46. id, err := res.LastInsertId()
  47. if err != nil {
  48. return 0, fmt.Errorf("last insert ID: %w", err)
  49. }
  50. return uint64(id), nil
  51. }
  52. func (r UserRepository) Update(ctx context.Context, req models.UpdateUserRequest) error {
  53. qb := sq.Update(userTableName).
  54. PlaceholderFormat(sq.Dollar).
  55. Set("updated_at", "NOW()").
  56. Where(sq.Eq{"id": req.ID})
  57. if req.Username.Valid {
  58. qb = qb.Set("username", req.Username.String)
  59. }
  60. if req.Password.Valid {
  61. qb = qb.Set("password", req.Password.String)
  62. }
  63. q, v, err := qb.ToSql()
  64. if err != nil {
  65. return fmt.Errorf("build query: %w", err)
  66. }
  67. _, err = r.db.ExecContext(ctx, q, v...)
  68. if err != nil {
  69. return fmt.Errorf("exec: %w", err)
  70. }
  71. return nil
  72. }