1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- package repositories
- import (
- "context"
- "fmt"
- sq "github.com/Masterminds/squirrel"
- "git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/models"
- )
- const (
- userTableName = "\"user\""
- )
- type UserRepository struct {
- db DB
- }
- func InitUserRepository(db DB) *UserRepository {
- return &UserRepository{db: db}
- }
- func (u UserRepository) Get(ctx context.Context, username string) (*models.User, error) {
- var res models.User
- q, v, err := sq.Select("id", "username", "password", "created_at", "updated_at").
- From(userTableName).
- PlaceholderFormat(sq.Dollar).
- Where(sq.Eq{"username": username}).
- ToSql()
- if err != nil {
- return nil, fmt.Errorf("build query: %w", err)
- }
- err = u.db.GetContext(ctx, &res, q, v...)
- if err != nil {
- return nil, fmt.Errorf("get: %w", err)
- }
- return &res, nil
- }
- func (u UserRepository) Add(ctx context.Context, username string, password string) (uint64, error) {
- q, v, err := sq.Insert(userTableName).
- PlaceholderFormat(sq.Dollar).
- Columns("username", "password").
- Values(username, password).
- Suffix("RETURNING id").
- ToSql()
- if err != nil {
- return 0, fmt.Errorf("build query: %w", err)
- }
- var id uint64
- if err = u.db.QueryRowContext(ctx, q, v...).Scan(&id); err != nil {
- return 0, fmt.Errorf("query row: %w", err)
- }
- return id, nil
- }
- func (u UserRepository) UpdatePassword(ctx context.Context, id uint64, newPassword string) error {
- q, v, err := sq.Update(userTableName).
- PlaceholderFormat(sq.Dollar).
- Set("password", newPassword).
- Set("updated_at", "NOW()").
- Where(sq.Eq{"id": id}).
- ToSql()
- if err != nil {
- return fmt.Errorf("build query: %w", err)
- }
- _, err = u.db.ExecContext(ctx, q, v...)
- if err != nil {
- return fmt.Errorf("exec: %w", err)
- }
- return nil
- }
|