|
|
package postgres
import ( "context" "database/sql" "github.com/Masterminds/squirrel" "github.com/gissleh/stufflog/internal/slerrors" "github.com/gissleh/stufflog/models" "github.com/jmoiron/sqlx" )
type logRepository struct { db *sqlx.DB }
func (r *logRepository) Find(ctx context.Context, id string) (*models.Log, error) { res := models.Log{} err := r.db.GetContext(ctx, &res, "SELECT * FROM log WHERE log_id=$1", id) if err != nil { if err == sql.ErrNoRows { return nil, slerrors.NotFound("Log") }
return nil, err }
return &res, nil }
func (r *logRepository) List(ctx context.Context, filter models.LogFilter) ([]*models.Log, error) { sq := squirrel.Select("log.*").From("log").PlaceholderFormat(squirrel.Dollar) sq = sq.Where(squirrel.Eq{"user_id": filter.UserID}) if len(filter.TaskIDs) > 0 { sq = sq.Where(squirrel.Eq{"task_id": filter.TaskIDs}) } if len(filter.ItemIDs) > 0 { sq = sq.Where(squirrel.Eq{"item_id": filter.ItemIDs}) } if filter.MinTime != nil { sq = sq.Where(squirrel.GtOrEq{ "logged_time": *filter.MinTime, }) } if filter.MaxTime != nil { sq = sq.Where(squirrel.LtOrEq{ "logged_time": *filter.MaxTime, }) }
sq = sq.OrderBy("logged_time")
query, args, err := sq.ToSql() if err != nil { return nil, err }
res := make([]*models.Log, 0, 8) err = r.db.SelectContext(ctx, &res, query, args...) if err != nil { if err == sql.ErrNoRows { return res, nil } return nil, err }
return res, nil }
func (r *logRepository) Insert(ctx context.Context, log models.Log) error { _, err := r.db.NamedExecContext(ctx, ` INSERT INTO log ( log_id, user_id, task_id, item_id, logged_time, description ) VALUES ( :log_id, :user_id, :task_id, :item_id, :logged_time, :description ) `, &log) if err != nil { return err }
return nil }
func (r *logRepository) Update(ctx context.Context, log models.Log) error { _, err := r.db.NamedExecContext(ctx, ` UPDATE log SET logged_time=:logged_time, description=:description WHERE log_id=:log_id `, &log) if err != nil { return err }
return nil }
func (r *logRepository) Delete(ctx context.Context, log models.Log) error { _, err := r.db.ExecContext(ctx, `DELETE FROM log WHERE log_id=$1`, log.ID) if err != nil { if err == sql.ErrNoRows { return slerrors.NotFound("Log") } return err }
return nil }
|