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.
 
 
 
 
 
 

100 lines
2.3 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 itemRepository struct {
db *sqlx.DB
}
func (r *itemRepository) Find(ctx context.Context, id string) (*models.Item, error) {
res := models.Item{}
err := r.db.GetContext(ctx, &res, "SELECT item.*, g.icon FROM item INNER JOIN \"group\" AS g ON item.group_id = g.group_id WHERE item_id=$1", id)
if err != nil {
if err == sql.ErrNoRows {
return nil, slerrors.NotFound("Item")
}
return nil, err
}
return &res, nil
}
func (r *itemRepository) List(ctx context.Context, filter models.ItemFilter) ([]*models.Item, error) {
sq := squirrel.Select("item.*", "g.icon").From("item").PlaceholderFormat(squirrel.Dollar)
sq = sq.Where(squirrel.Eq{"item.user_id": filter.UserID})
if len(filter.IDs) > 0 {
sq = sq.Where(squirrel.Eq{"item.item_id": filter.IDs})
}
if len(filter.GroupIDs) > 0 {
sq = sq.Where(squirrel.Eq{"item.group_id": filter.GroupIDs})
}
sq = sq.InnerJoin("\"group\" AS g ON item.group_id = g.group_id")
sq = sq.OrderBy("item.group_weight", "item.name")
query, args, err := sq.ToSql()
if err != nil {
return nil, err
}
res := make([]*models.Item, 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 *itemRepository) Insert(ctx context.Context, item models.Item) error {
_, err := r.db.NamedExecContext(ctx, `
INSERT INTO item (
item_id, user_id, group_id, group_weight, name, description
) VALUES (
:item_id, :user_id, :group_id, :group_weight, :name, :description
)
`, &item)
if err != nil {
return err
}
return nil
}
func (r *itemRepository) Update(ctx context.Context, item models.Item) error {
_, err := r.db.NamedExecContext(ctx, `
UPDATE item SET
group_weight = :group_weight,
name = :name,
description = :description
WHERE item_id=:item_id
`, &item)
if err != nil {
return err
}
return nil
}
func (r *itemRepository) Delete(ctx context.Context, item models.Item) error {
_, err := r.db.ExecContext(ctx, `DELETE FROM item WHERE item_id=$1`, item.ID)
if err != nil {
if err == sql.ErrNoRows {
return slerrors.NotFound("Item")
}
return err
}
return nil
}