73 lines
1.5 KiB
Go
73 lines
1.5 KiB
Go
package repository
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"errors"
|
|
"tailly_back_v2/internal/domain"
|
|
)
|
|
|
|
var (
|
|
ErrUserNotFound = errors.New("user not found")
|
|
)
|
|
|
|
type UserRepository interface {
|
|
Create(ctx context.Context, user *domain.User) error
|
|
GetByID(ctx context.Context, id int) (*domain.User, error)
|
|
GetByEmail(ctx context.Context, email string) (*domain.User, error)
|
|
Update(ctx context.Context, user *domain.User) error
|
|
Delete(ctx context.Context, id int) error
|
|
}
|
|
|
|
type userRepository struct {
|
|
db *sql.DB
|
|
}
|
|
|
|
func NewUserRepository(db *sql.DB) UserRepository {
|
|
return &userRepository{db: db}
|
|
}
|
|
|
|
func (r *userRepository) Create(ctx context.Context, user *domain.User) error {
|
|
query := `
|
|
INSERT INTO users (username, email, password, created_at, updated_at)
|
|
VALUES ($1, $2, $3, $4, $5)
|
|
RETURNING id
|
|
`
|
|
|
|
err := r.db.QueryRowContext(ctx, query,
|
|
user.Username,
|
|
user.Email,
|
|
user.Password,
|
|
user.CreatedAt,
|
|
user.UpdatedAt,
|
|
).Scan(&user.ID)
|
|
|
|
return err
|
|
}
|
|
|
|
func (r *userRepository) GetByID(ctx context.Context, id int) (*domain.User, error) {
|
|
query := `
|
|
SELECT id, username, email, password, created_at, updated_at
|
|
FROM users
|
|
WHERE id = $1
|
|
`
|
|
|
|
user := &domain.User{}
|
|
err := r.db.QueryRowContext(ctx, query, id).Scan(
|
|
&user.ID,
|
|
&user.Username,
|
|
&user.Email,
|
|
&user.Password,
|
|
&user.CreatedAt,
|
|
&user.UpdatedAt,
|
|
)
|
|
|
|
if err == sql.ErrNoRows {
|
|
return nil, ErrUserNotFound
|
|
}
|
|
|
|
return user, err
|
|
}
|
|
|
|
// Остальные методы аналогично...
|