package repository import ( "context" "errors" "git.sch9.ru/new_gate/models" "git.sch9.ru/new_gate/ms-tester/pkg/utils" "github.com/jackc/pgerrcode" "github.com/jackc/pgx/v5/pgconn" "github.com/jmoiron/sqlx" "go.uber.org/zap" ) type ProblemRepository struct { db *sqlx.DB logger *zap.Logger } func NewProblemRepository(db *sqlx.DB, logger *zap.Logger) *ProblemRepository { return &ProblemRepository{ db: db, logger: logger, } } const createProblemQuery = "INSERT INTO problems (title) VALUES (?) RETURNING id" func (r *ProblemRepository) CreateProblem(ctx context.Context, title string) (int32, error) { query := r.db.Rebind(createProblemQuery) rows, err := r.db.QueryxContext(ctx, query, title) if err != nil { return 0, handlePgErr(err) } defer rows.Close() var id int32 rows.Next() err = rows.Scan(&id) if err != nil { return 0, handlePgErr(err) } return id, nil } const readProblemQuery = "SELECT * from problems WHERE id=? LIMIT 1" func (r *ProblemRepository) ReadProblemById(ctx context.Context, id int32) (*models.Problem, error) { var problem models.Problem query := r.db.Rebind(readProblemQuery) err := r.db.GetContext(ctx, &problem, query, id) if err != nil { return nil, handlePgErr(err) } return &problem, nil } const deleteProblemQuery = "DELETE FROM problems WHERE id=?" func (r *ProblemRepository) DeleteProblem(ctx context.Context, id int32) error { query := r.db.Rebind(deleteProblemQuery) _, err := r.db.ExecContext(ctx, query, id) if err != nil { return handlePgErr(err) } return nil } func handlePgErr(err error) error { var pgErr *pgconn.PgError if !errors.As(err, &pgErr) { return utils.StorageError(err, utils.ErrUnknown, "unexpected error from postgres") } if pgerrcode.IsIntegrityConstraintViolation(pgErr.Code) { // TODO: probably should specify which constraint return utils.StorageError(err, utils.ErrConflict, pgErr.Message) } if pgerrcode.IsNoData(pgErr.Code) { return utils.StorageError(err, utils.ErrNotFound, pgErr.Message) } return utils.StorageError(err, utils.ErrUnimplemented, "unimplemented error") }