feat: add postgres-backed repositories
This commit is contained in:
parent
a2d47a4b3e
commit
c340623721
4 changed files with 324 additions and 0 deletions
61
internal/postgres/training_repository.go
Normal file
61
internal/postgres/training_repository.go
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
package postgres
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
|
||||
"gitlab.mareshq.com/hq/backoffice/backoffice-api/pkg/training"
|
||||
)
|
||||
|
||||
type TrainingRepository struct {
|
||||
db *sql.DB
|
||||
}
|
||||
|
||||
func NewTrainingRepository(db *sql.DB) *TrainingRepository {
|
||||
return &TrainingRepository{db: db}
|
||||
}
|
||||
|
||||
func (r *TrainingRepository) Save(t *training.Training) error {
|
||||
_, err := r.db.Exec("INSERT INTO training (id, name, days, description, price) VALUES ($1, $2, $3)", t.ID, t.Name, t.Days, t.Description, t.Price)
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *TrainingRepository) Get(id training.ID) (*training.Training, error) {
|
||||
var t training.Training
|
||||
err := r.db.QueryRow("SELECT * FROM training WHERE id = $1", id).Scan(&t.ID, &t.Name, &t.Days, &t.Description, &t.Price)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &t, nil
|
||||
}
|
||||
|
||||
func (r *TrainingRepository) Update(t *training.Training) error {
|
||||
_, err := r.db.Exec("UPDATE training SET name = $1, days = $2, description = $3, price = $4 WHERE id = $5", t.Name, t.Days, t.Description, t.Price, t.ID)
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *TrainingRepository) Delete(id training.ID) error {
|
||||
_, err := r.db.Exec("DELETE FROM training WHERE id = $1", id)
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *TrainingRepository) FindAll() ([]training.Training, error) {
|
||||
rows, err := r.db.Query("SELECT * FROM training")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var trainings []training.Training
|
||||
for rows.Next() {
|
||||
var t training.Training
|
||||
err := rows.Scan(&t.ID, &t.Name, &t.Days, &t.Description, &t.Price)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
trainings = append(trainings, t)
|
||||
}
|
||||
|
||||
return trainings, nil
|
||||
}
|
||||
Reference in a new issue