Files
core/internal/repository/registry/locations.go

86 lines
2.1 KiB
Go

package registry
import (
"context"
"database/sql"
"reanimator/internal/domain"
"reanimator/internal/idgen"
)
type LocationRepository struct {
db *sql.DB
idgen *idgen.Generator
}
func NewLocationRepository(db *sql.DB) *LocationRepository {
return &LocationRepository{
db: db,
idgen: idgen.NewGenerator(db),
}
}
func (r *LocationRepository) Create(ctx context.Context, customerID string, name string, kind *string) (domain.Location, error) {
// Generate string ID
id, err := r.idgen.Generate(ctx, idgen.Location)
if err != nil {
return domain.Location{}, err
}
_, err = r.db.ExecContext(ctx,
`INSERT INTO locations (id, customer_id, name, kind) VALUES (?, ?, ?, ?)`,
id, customerID, name, kind,
)
if err != nil {
return domain.Location{}, classifyError(err)
}
return r.Get(ctx, id)
}
func (r *LocationRepository) Get(ctx context.Context, id string) (domain.Location, error) {
var location domain.Location
var kind sql.NullString
row := r.db.QueryRowContext(ctx,
`SELECT id, customer_id, name, kind, created_at, updated_at FROM locations WHERE id = ?`,
id,
)
if err := row.Scan(&location.ID, &location.CustomerID, &location.Name, &kind, &location.CreatedAt, &location.UpdatedAt); err != nil {
if err == sql.ErrNoRows {
return domain.Location{}, ErrNotFound
}
return domain.Location{}, err
}
location.Kind = nullStringToPtr(kind)
return location, nil
}
func (r *LocationRepository) List(ctx context.Context) ([]domain.Location, error) {
rows, err := r.db.QueryContext(ctx,
`SELECT id, customer_id, name, kind, created_at, updated_at FROM locations ORDER BY created_at DESC`,
)
if err != nil {
return nil, err
}
defer rows.Close()
locations := make([]domain.Location, 0)
for rows.Next() {
var location domain.Location
var kind sql.NullString
if err := rows.Scan(&location.ID, &location.CustomerID, &location.Name, &kind, &location.CreatedAt, &location.UpdatedAt); err != nil {
return nil, err
}
location.Kind = nullStringToPtr(kind)
locations = append(locations, location)
}
if err := rows.Err(); err != nil {
return nil, err
}
return locations, nil
}