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