|
|
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") }
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 ) VALUES ( :project_id, :user_id, :name, :description, :icon, :active, :created_time, :end_time ) `, &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 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 }
return nil }
|