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.
 
 
 
 
 
 

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