You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

116 lines
2.8 KiB

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 taskRepository struct {
db *sqlx.DB
}
func (r *taskRepository) Find(ctx context.Context, id string) (*models.Task, error) {
res := models.Task{}
err := r.db.GetContext(ctx, &res, "SELECT task.*, p.icon FROM task INNER JOIN project AS p ON task.project_id = p.project_id WHERE task_id=$1", id)
if err != nil {
if err == sql.ErrNoRows {
return nil, slerrors.NotFound("Task")
}
return nil, err
}
return &res, nil
}
func (r *taskRepository) List(ctx context.Context, filter models.TaskFilter) ([]*models.Task, error) {
sq := squirrel.Select("task.*", "p.icon").From("task").PlaceholderFormat(squirrel.Dollar)
sq = sq.Where(squirrel.Eq{"task.user_id": filter.UserID})
if filter.Active != nil {
sq = sq.Where(squirrel.Eq{"task.active": *filter.Active})
}
if filter.Expiring != nil {
if *filter.Expiring {
sq = sq.Where("task.end_time IS NOT NULL")
} else {
sq = sq.Where("task.end_time IS NULL")
}
}
if filter.IDs != nil {
sq = sq.Where(squirrel.Eq{"task.task_id": filter.IDs})
}
if filter.ItemIDs != nil {
sq = sq.Where(squirrel.Eq{"task.item_id": filter.ItemIDs})
}
if filter.ProjectIDs != nil {
sq = sq.Where(squirrel.Eq{"task.project_id": filter.ProjectIDs})
}
sq = sq.InnerJoin("project AS p ON task.project_id = p.project_id")
sq = sq.OrderBy("created_time")
query, args, err := sq.ToSql()
if err != nil {
return nil, err
}
res := make([]*models.Task, 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 *taskRepository) Insert(ctx context.Context, task models.Task) error {
_, err := r.db.NamedExecContext(ctx, `
INSERT INTO task (
task_id, user_id, item_id, project_id, item_amount, name, description, active, created_time, end_time
) VALUES (
:task_id, :user_id, :item_id, :project_id, :item_amount, :name, :description, :active, :created_time, :end_time
)
`, &task)
if err != nil {
return err
}
return nil
}
func (r *taskRepository) Update(ctx context.Context, task models.Task) error {
_, err := r.db.NamedExecContext(ctx, `
UPDATE task SET
item_id = :item_id,
item_amount = :item_amount,
name = :name,
description = :description,
active = :active,
end_time = :end_time
WHERE task_id=:task_id
`, &task)
if err != nil {
return err
}
return nil
}
func (r *taskRepository) Delete(ctx context.Context, task models.Task) error {
_, err := r.db.ExecContext(ctx, `DELETE FROM task WHERE task_id=$1`, task.ID)
if err != nil {
if err == sql.ErrNoRows {
return slerrors.NotFound("Task")
}
return err
}
return nil
}