type UserRepository struct {
db *sql.DB
}
func NewUserRepository(db *sql.DB) *UserRepository {
return &UserRepository{db: db}
}
func (r *UserRepository) GetByID(ctx context.Context, id int) (*User, error) {
var u User
err := r.db.QueryRowContext(
ctx,
"SELECT id, name, email FROM users WHERE id = $1",
id,
).Scan(&u.ID, &u.Name, &u.Email)
if err == sql.ErrNoRows {
return nil, fmt.Errorf("user not found")
}
return &u, err
}
func (r *UserRepository) Create(ctx context.Context, u *User) error {
return r.db.QueryRowContext(
ctx,
"INSERT INTO users (name, email) VALUES ($1, $2) RETURNING id",
u.Name, u.Email,
).Scan(&u.ID)
}
func (r *UserRepository) Update(ctx context.Context, u *User) error {
_, err := r.db.ExecContext(
ctx,
"UPDATE users SET name = $1, email = $2 WHERE id = $3",
u.Name, u.Email, u.ID,
)
return err
}
func (r *UserRepository) Delete(ctx context.Context, id int) error {
_, err := r.db.ExecContext(ctx, "DELETE FROM users WHERE id = $1", id)
return err
}