package repositories import ( "context" sq "github.com/Masterminds/squirrel" "git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/helpers/errors" "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( // TESTED 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(placeholder). Where(sq.Eq{"username": username}). ToSql() if err != nil { return nil, errors.Wrap(err, "build query") } err = u.db.GetContext(ctx, &res, q, v...) if err != nil { return nil, errors.Wrap(err, "get") } return &res, nil } func (u UserRepository) Add( ctx context.Context, username string, password string, ) (uint64, error) { q, v, err := sq.Insert(userTableName). PlaceholderFormat(placeholder). Columns("username", "password"). Values(username, password). Suffix("RETURNING id"). ToSql() if err != nil { return 0, errors.Wrap(err, "build query") } res, err := u.db.ExecContext(ctx, q, v...) if err != nil { return 0, errors.Wrap(err, "exec") } id, err := res.LastInsertId() if err != nil { return 0, errors.Wrap(err, "can't get last insert id") } return uint64(id), nil } func (u UserRepository) UpdatePassword( ctx context.Context, id uint64, newPassword string, ) error { q, v, err := sq.Update(userTableName). PlaceholderFormat(placeholder). Set("password", newPassword). Set("updated_at", "NOW()"). Where(sq.Eq{"id": id}). ToSql() if err != nil { return errors.Wrap(err, "build query") } _, err = u.db.ExecContext(ctx, q, v...) if err != nil { return errors.Wrap(err, "exec") } return nil }