12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182 |
- package repositories
- import (
- "context"
- "database/sql"
- sq "github.com/Masterminds/squirrel"
- "git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/models"
- )
- const (
- userTableName = "\"user\""
- )
- type UserRepository struct {
- db *sql.DB
- }
- func InitUserRepository(db *sql.DB) *UserRepository {
- return &UserRepository{db: db}
- }
- func (u UserRepository) Get(ctx context.Context, username string) (*models.User, error) {
- query, args, 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, err
- }
- var res models.User
- err = u.db.QueryRowContext(ctx, query, args...).
- Scan(&res.ID, &res.Username, &res.Password, &res.CreatedAt, &res.UpdatedAt)
- if err != nil {
- return nil, err
- }
- return &res, nil
- }
- func (u UserRepository) Add(ctx context.Context, username string, password string) (int, error) {
- query, args, err := sq.Insert(userTableName).
- PlaceholderFormat(sq.Dollar).
- Columns("username", "password").
- Values(username, password).
- Suffix("RETURNING id").
- ToSql()
- if err != nil {
- return 0, err
- }
- var id int
- if err = u.db.QueryRowContext(ctx, query, args...).Scan(&id); err != nil {
- return 0, err
- }
- return id, nil
- }
- func (u UserRepository) UpdatePassword(ctx context.Context, id int, newPassword string) error {
- query, args, err := sq.Update(userTableName).
- PlaceholderFormat(sq.Dollar).
- Set("password", newPassword).
- Set("updated_at", "NOW()").
- Where(sq.Eq{"id": id}).
- ToSql()
- if err != nil {
- return err
- }
- _, err = u.db.ExecContext(ctx, query, args...)
- return err
- }
|