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 goalRepository struct { db *sqlx.DB } func (r *goalRepository) Find(ctx context.Context, id string) (*models.Goal, error) { res := models.Goal{} err := r.db.GetContext(ctx, &res, "SELECT * FROM goal WHERE goal_id=$1", id) if err != nil { if err == sql.ErrNoRows { return nil, slerrors.NotFound("Goal") } return nil, err } return &res, nil } func (r *goalRepository) List(ctx context.Context, filter models.GoalFilter) ([]*models.Goal, error) { sq := squirrel.Select("*").From("goal").PlaceholderFormat(squirrel.Dollar) sq = sq.Where(squirrel.Eq{"user_id": filter.UserID}) if len(filter.IDs) > 0 { sq = sq.Where(squirrel.Eq{"goal_id": filter.IDs}) } if filter.MinTime != nil { sq = sq.Where(squirrel.GtOrEq{ "end_time": *filter.MinTime, }) } if filter.MaxTime != nil { sq = sq.Where(squirrel.LtOrEq{ "start_time": *filter.MaxTime, }) } if filter.IncludesTime != nil { sq = sq.Where(squirrel.LtOrEq{ "start_time": *filter.IncludesTime, }).Where(squirrel.GtOrEq{ "end_time": *filter.IncludesTime, }) } sq = sq.OrderBy("start_time DESC", "end_time ASC", "name") query, args, err := sq.ToSql() if err != nil { return nil, err } res := make([]*models.Goal, 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 *goalRepository) Insert(ctx context.Context, goal models.Goal) error { _, err := r.db.NamedExecContext(ctx, ` INSERT INTO goal ( goal_id, user_id, group_id, amount, start_time, end_time, name, description ) VALUES ( :goal_id, :user_id, :group_id, :amount, :start_time, :end_time, :name, :description ) `, &goal) if err != nil { return err } return nil } func (r *goalRepository) Update(ctx context.Context, goal models.Goal) error { _, err := r.db.NamedExecContext(ctx, ` UPDATE goal SET amount=:amount, start_time=:start_time, end_time=:end_time, name=:name, description=:description WHERE goal_id=:goal_id `, &goal) if err != nil { return err } return nil } func (r *goalRepository) Delete(ctx context.Context, goal models.Goal) error { _, err := r.db.ExecContext(ctx, `DELETE FROM goal WHERE goal_id=$1`, goal.ID) if err != nil { if err == sql.ErrNoRows { return slerrors.NotFound("Goal") } return err } return nil }