package training import ( "context" "github.com/jackc/pgx/v5/pgxpool" "log" ) type PostgresRepository struct { pg *pgxpool.Pool logger *log.Logger } func NewPostgresRepository(logger *log.Logger, pg *pgxpool.Pool) *PostgresRepository { return &PostgresRepository{ pg: pg, logger: logger, } } func (r *PostgresRepository) Create(ctx context.Context, training *Training) error { tx, txErr := r.pg.Begin(ctx) if txErr != nil { return txErr } queryErr := tx.QueryRow(ctx, ` INSERT INTO training.trainings (name, days, published) VALUES ($1, $2, $3, $4, $5) RETURNING id `, training.name, training.days, training.published).Scan(&training.id) if queryErr != nil { return queryErr } // TODO: insert pricing using the transaction (tx) return nil } func (r *PostgresRepository) Update(ctx context.Context, training *Training) error { _, err := r.pg.Exec(ctx, ` UPDATE training.trainings SET title = $2 WHERE id = $1 `, training.ID, training.name) if err != nil { r.logger.Printf("error: %v\n", err) return err } return nil } func (r *PostgresRepository) FindByID(ctx context.Context, id ID) (*Training, error) { var t Training err := r.pg.QueryRow(ctx, ` SELECT id, title, published, retired FROM training.trainings WHERE id = $1 `, id).Scan(&t.id, &t.name, &t.published, &t.retired) if err != nil { r.logger.Printf("error: %v\n", err) return nil, err } return &t, nil } func (r *PostgresRepository) FindAll(ctx context.Context) ([]Training, error) { rows, err := r.pg.Query(ctx, ` SELECT id, title, published, retired FROM training.trainings `) if err != nil { r.logger.Printf("error: %v\n", err) return nil, err } defer rows.Close() var trainings []Training for rows.Next() { var t Training err := rows.Scan(&t.id, &t.name, &t.published, &t.retired) if err != nil { r.logger.Printf("error: %v\n", err) return nil, err } trainings = append(trainings, t) } return trainings, nil } func (r *PostgresRepository) Publish(ctx context.Context, id ID) error { _, err := r.pg.Exec(ctx, ` UPDATE training.trainings SET published = true WHERE id = $1 `, id) if err != nil { r.logger.Printf("error: %v\n", err) return err } return nil } func (r *PostgresRepository) Unpublish(ctx context.Context, id ID) error { _, err := r.pg.Exec(ctx, ` UPDATE training.trainings SET published = false WHERE id = $1 `, id) if err != nil { r.logger.Printf("error: %v\n", err) return err } return nil } func (r *PostgresRepository) Retire(ctx context.Context, id ID) error { _, err := r.pg.Exec(ctx, ` UPDATE training.trainings SET retired = true WHERE id = $1 `, id) if err != nil { r.logger.Printf("error: %v\n", err) return err } return nil }