user.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package repositories
  2. import (
  3. "context"
  4. "database/sql"
  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 *sql.DB
  13. }
  14. func InitUserRepository(db *sql.DB) *UserRepository {
  15. return &UserRepository{db: db}
  16. }
  17. func (u 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 = u.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 (u 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 = u.db.QueryRowContext(ctx, query, args...).Scan(&id); err != nil {
  46. return 0, err
  47. }
  48. return id, nil
  49. }
  50. func (u UserRepository) UpdatePassword(ctx context.Context, id int, newPassword string) error {
  51. query, args, err := sq.Update(userTableName).
  52. PlaceholderFormat(sq.Dollar).
  53. Set("password", newPassword).
  54. Set("updated_at", "NOW()").
  55. Where(sq.Eq{"id": id}).
  56. ToSql()
  57. if err != nil {
  58. return err
  59. }
  60. _, err = u.db.ExecContext(ctx, query, args...)
  61. return err
  62. }