user.go 1.8 KB

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