86 lines
1.9 KiB
Go
86 lines
1.9 KiB
Go
package postgres
|
|
|
|
import (
|
|
"context"
|
|
"log/slog"
|
|
|
|
"gitea.michaelthomson.dev/mthomson/habits/internal/todo/repository"
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
)
|
|
|
|
type PostgresTodoRepository struct {
|
|
logger *slog.Logger
|
|
db *pgxpool.Pool
|
|
}
|
|
|
|
func NewPostgresTodoRepository(logger *slog.Logger, db *pgxpool.Pool) *PostgresTodoRepository {
|
|
return &PostgresTodoRepository{
|
|
logger: logger,
|
|
db: db,
|
|
}
|
|
}
|
|
|
|
func (r *PostgresTodoRepository) GetById(ctx context.Context, id int64) (repository.TodoRow, error) {
|
|
todo := repository.TodoRow{}
|
|
|
|
err := r.db.QueryRow(ctx, "SELECT * FROM todo WHERE id = $1;", id).Scan(&todo.Id, &todo.Name, &todo.Done)
|
|
|
|
if err != nil {
|
|
if err == pgx.ErrNoRows {
|
|
return todo, repository.ErrNotFound
|
|
}
|
|
|
|
r.logger.ErrorContext(ctx, err.Error())
|
|
return todo, err
|
|
}
|
|
|
|
return todo, nil
|
|
}
|
|
|
|
func (r *PostgresTodoRepository) Create(ctx context.Context, todo repository.TodoRow) (repository.TodoRow, error) {
|
|
result := r.db.QueryRow(ctx, "INSERT INTO todo (name, done) VALUES ($1, $2) RETURNING id;", todo.Name, todo.Done)
|
|
err := result.Scan(&todo.Id)
|
|
|
|
if err != nil {
|
|
r.logger.ErrorContext(ctx, err.Error())
|
|
return repository.TodoRow{}, err
|
|
}
|
|
|
|
return todo, nil
|
|
}
|
|
|
|
func (r *PostgresTodoRepository) Update(ctx context.Context, todo repository.TodoRow) error {
|
|
result, err := r.db.Exec(ctx, "UPDATE todo SET name = $1, done = $2 WHERE id = $3;", todo.Name, todo.Done, todo.Id)
|
|
|
|
if err != nil {
|
|
r.logger.ErrorContext(ctx, err.Error())
|
|
return err
|
|
}
|
|
|
|
rowsAffected := result.RowsAffected()
|
|
|
|
if rowsAffected == 0 {
|
|
return repository.ErrNotFound
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (r *PostgresTodoRepository) Delete(ctx context.Context, id int64) error {
|
|
result, err := r.db.Exec(ctx, "DELETE FROM todo WHERE id = $1;", id)
|
|
|
|
if err != nil {
|
|
r.logger.ErrorContext(ctx, err.Error())
|
|
return err
|
|
}
|
|
|
|
rowsAffected := result.RowsAffected()
|
|
|
|
if rowsAffected == 0 {
|
|
return repository.ErrNotFound
|
|
}
|
|
|
|
return nil
|
|
}
|