stufflog graphql server
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.4 KiB

package mysqldriver
import (
"context"
"database/sql"
"errors"
"git.aiterp.net/stufflog/server/internal/generate"
"git.aiterp.net/stufflog/server/internal/xlerrors"
"git.aiterp.net/stufflog/server/models"
sq "github.com/Masterminds/squirrel"
"github.com/jmoiron/sqlx"
)
type activityRepository struct {
db *sqlx.DB
}
func (r *activityRepository) Find(ctx context.Context, id string) (*models.Activity, error) {
activity := models.Activity{}
err := r.db.GetContext(ctx, &activity, "SELECT * FROM activity WHERE activity_id=?", id)
if err != nil {
if err == sql.ErrNoRows {
return nil, xlerrors.NotFound("Activity")
}
return nil, err
}
return &activity, nil
}
func (r *activityRepository) List(ctx context.Context, filter models.ActivityFilter) ([]*models.Activity, error) {
q := sq.Select("*").From("activity")
if len(filter.ActivityIDs) > 0 {
q = q.Where(sq.Eq{"activity_id": filter.ActivityIDs})
}
if len(filter.ProjectIDs) > 0 {
q = q.Where(sq.Eq{"project_id": filter.ProjectIDs})
}
query, args, err := q.ToSql()
if err != nil {
return nil, err
}
results := make([]*models.Activity, 0, 16)
err = r.db.SelectContext(ctx, &results, query, args...)
if err != nil {
if err == sql.ErrNoRows {
return []*models.Activity{}, nil
}
return nil, err
}
return results, nil
}
func (r *activityRepository) Insert(ctx context.Context, activity models.Activity) (*models.Activity, error) {
if activity.ProjectID == "" {
return nil, errors.New("missing project id")
}
activity.ID = generate.ActivityID()
_, err := r.db.NamedExecContext(ctx, `
INSERT INTO activity (
activity_id, project_id, name, countable,
unit_is_time, unit_name, unit_value, base_value
) VALUES (
:activity_id, :project_id, :name, :countable,
:unit_is_time, :unit_name, :unit_value, :base_value
)
`, activity)
if err != nil {
return nil, err
}
return &activity, nil
}
func (r *activityRepository) Save(ctx context.Context, activity models.Activity) error {
_, err := r.db.NamedExecContext(ctx, `
UPDATE activity SET
name=:name,
countable=:countable,
unit_is_time=:unit_is_time,
unit_name=:unit_name,
unit_value=:unit_value,
base_value=:base_value
WHERE activity_id=:activity_id
`, activity)
return err
}
func (r *activityRepository) Delete(ctx context.Context, activity models.Activity) error {
_, err := r.db.ExecContext(ctx, "DELETE FROM activity WHERE activity_id=? LIMIT 1;", activity.ID)
return err
}