75 lines
1.7 KiB
Go
75 lines
1.7 KiB
Go
package registry
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
|
|
"reanimator/internal/domain"
|
|
)
|
|
|
|
type CustomerRepository struct {
|
|
db *sql.DB
|
|
}
|
|
|
|
func NewCustomerRepository(db *sql.DB) *CustomerRepository {
|
|
return &CustomerRepository{db: db}
|
|
}
|
|
|
|
func (r *CustomerRepository) Create(ctx context.Context, name string) (domain.Customer, error) {
|
|
result, err := r.db.ExecContext(ctx,
|
|
`INSERT INTO customers (name) VALUES (?)`,
|
|
name,
|
|
)
|
|
if err != nil {
|
|
return domain.Customer{}, classifyError(err)
|
|
}
|
|
|
|
id, err := result.LastInsertId()
|
|
if err != nil {
|
|
return domain.Customer{}, err
|
|
}
|
|
|
|
return r.Get(ctx, id)
|
|
}
|
|
|
|
func (r *CustomerRepository) Get(ctx context.Context, id int64) (domain.Customer, error) {
|
|
var customer domain.Customer
|
|
|
|
row := r.db.QueryRowContext(ctx,
|
|
`SELECT id, name, created_at, updated_at FROM customers WHERE id = ?`,
|
|
id,
|
|
)
|
|
if err := row.Scan(&customer.ID, &customer.Name, &customer.CreatedAt, &customer.UpdatedAt); err != nil {
|
|
if err == sql.ErrNoRows {
|
|
return domain.Customer{}, ErrNotFound
|
|
}
|
|
return domain.Customer{}, err
|
|
}
|
|
|
|
return customer, nil
|
|
}
|
|
|
|
func (r *CustomerRepository) List(ctx context.Context) ([]domain.Customer, error) {
|
|
rows, err := r.db.QueryContext(ctx,
|
|
`SELECT id, name, created_at, updated_at FROM customers ORDER BY id`,
|
|
)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
|
|
customers := make([]domain.Customer, 0)
|
|
for rows.Next() {
|
|
var customer domain.Customer
|
|
if err := rows.Scan(&customer.ID, &customer.Name, &customer.CreatedAt, &customer.UpdatedAt); err != nil {
|
|
return nil, err
|
|
}
|
|
customers = append(customers, customer)
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return customers, nil
|
|
}
|