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.
 
 
 
 
 
 

114 lines
2.7 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 projectRepository struct {
db *sqlx.DB
}
func (r *projectRepository) Find(ctx context.Context, id string) (*models.Project, error) {
res := models.Project{}
err := r.db.GetContext(ctx, &res, "SELECT * FROM project WHERE project_id=$1", id)
if err != nil {
if err == sql.ErrNoRows {
return nil, slerrors.NotFound("Log")
}
return nil, err
}
return &res, nil
}
func (r *projectRepository) List(ctx context.Context, filter models.ProjectFilter) ([]*models.Project, error) {
sq := squirrel.Select("*").From("project").PlaceholderFormat(squirrel.Dollar)
sq = sq.Where(squirrel.Eq{"user_id": filter.UserID})
if filter.IDs != nil {
sq = sq.Where(squirrel.Eq{"project_id": filter.IDs})
}
if filter.Active != nil {
sq = sq.Where(squirrel.Eq{"active": *filter.Active})
}
if filter.Expiring {
sq = sq.Where("end_time IS NOT NULL")
}
if filter.Favorite != nil {
sq = sq.Where(squirrel.Eq{"favorite": *filter.Favorite})
}
sq = sq.OrderBy("active", "created_time DESC")
query, args, err := sq.ToSql()
if err != nil {
return nil, err
}
res := make([]*models.Project, 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 *projectRepository) Insert(ctx context.Context, project models.Project) error {
_, err := r.db.NamedExecContext(ctx, `
INSERT INTO project(
project_id, user_id, name, description, icon, active, created_time, end_time, status_tag, favorite
) VALUES (
:project_id, :user_id, :name, :description, :icon, :active, :created_time, :end_time, :status_tag, :favorite
)
`, &project)
if err != nil {
return err
}
return nil
}
func (r *projectRepository) Update(ctx context.Context, project models.Project) error {
_, err := r.db.NamedExecContext(ctx, `
UPDATE project SET
name = :name,
description = :description,
icon = :icon,
active = :active,
end_time = :end_time,
status_tag = :status_tag,
favorite = :favorite
WHERE project_id=:project_id
`, &project)
if err != nil {
return err
}
return nil
}
func (r *projectRepository) Delete(ctx context.Context, project models.Project) error {
_, err := r.db.ExecContext(ctx, `DELETE FROM project WHERE project_id=$1`, project.ID)
if err != nil {
if err == sql.ErrNoRows {
return slerrors.NotFound("Project")
}
return err
}
_, err = r.db.ExecContext(ctx, `DELETE FROM task_link WHERE project_id=$1`, project.ID)
if err != nil && err != sql.ErrNoRows {
return err
}
return nil
}