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

4 years ago
  1. package postgres
  2. import (
  3. "context"
  4. "database/sql"
  5. "github.com/Masterminds/squirrel"
  6. "github.com/gissleh/stufflog/internal/slerrors"
  7. "github.com/gissleh/stufflog/models"
  8. "github.com/jmoiron/sqlx"
  9. )
  10. type itemRepository struct {
  11. db *sqlx.DB
  12. }
  13. func (r *itemRepository) Find(ctx context.Context, id string) (*models.Item, error) {
  14. res := models.Item{}
  15. 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)
  16. if err != nil {
  17. if err == sql.ErrNoRows {
  18. return nil, slerrors.NotFound("Item")
  19. }
  20. return nil, err
  21. }
  22. return &res, nil
  23. }
  24. func (r *itemRepository) List(ctx context.Context, filter models.ItemFilter) ([]*models.Item, error) {
  25. sq := squirrel.Select("item.*", "g.icon").From("item").PlaceholderFormat(squirrel.Dollar)
  26. sq = sq.Where(squirrel.Eq{"item.user_id": filter.UserID})
  27. if len(filter.IDs) > 0 {
  28. sq = sq.Where(squirrel.Eq{"item.item_id": filter.IDs})
  29. }
  30. if len(filter.GroupIDs) > 0 {
  31. sq = sq.Where(squirrel.Eq{"item.group_id": filter.GroupIDs})
  32. }
  33. sq = sq.InnerJoin("\"group\" AS g ON item.group_id = g.group_id")
  34. sq = sq.OrderBy("item.group_weight", "item.name")
  35. query, args, err := sq.ToSql()
  36. if err != nil {
  37. return nil, err
  38. }
  39. res := make([]*models.Item, 0, 8)
  40. err = r.db.SelectContext(ctx, &res, query, args...)
  41. if err != nil {
  42. if err == sql.ErrNoRows {
  43. return res, nil
  44. }
  45. return nil, err
  46. }
  47. return res, nil
  48. }
  49. func (r *itemRepository) Insert(ctx context.Context, item models.Item) error {
  50. _, err := r.db.NamedExecContext(ctx, `
  51. INSERT INTO item (
  52. item_id, user_id, group_id, group_weight, name, description
  53. ) VALUES (
  54. :item_id, :user_id, :group_id, :group_weight, :name, :description
  55. )
  56. `, &item)
  57. if err != nil {
  58. return err
  59. }
  60. return nil
  61. }
  62. func (r *itemRepository) Update(ctx context.Context, item models.Item) error {
  63. _, err := r.db.NamedExecContext(ctx, `
  64. UPDATE item SET
  65. group_weight = :group_weight,
  66. name = :name,
  67. description = :description
  68. WHERE item_id=:item_id
  69. `, &item)
  70. if err != nil {
  71. return err
  72. }
  73. return nil
  74. }
  75. func (r *itemRepository) Delete(ctx context.Context, item models.Item) error {
  76. _, err := r.db.ExecContext(ctx, `DELETE FROM item WHERE item_id=$1`, item.ID)
  77. if err != nil {
  78. if err == sql.ErrNoRows {
  79. return slerrors.NotFound("Item")
  80. }
  81. return err
  82. }
  83. return nil
  84. }