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

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 groupRepository struct {
  11. db *sqlx.DB
  12. }
  13. func (r *groupRepository) Find(ctx context.Context, id string) (*models.Group, error) {
  14. res := models.Group{}
  15. err := r.db.GetContext(ctx, &res, "SELECT * FROM \"group\" WHERE group_id=$1", id)
  16. if err != nil {
  17. if err == sql.ErrNoRows {
  18. return nil, slerrors.NotFound("Group")
  19. }
  20. return nil, err
  21. }
  22. return &res, nil
  23. }
  24. func (r *groupRepository) List(ctx context.Context, filter models.GroupFilter) ([]*models.Group, error) {
  25. sq := squirrel.Select("*").From("\"group\"").PlaceholderFormat(squirrel.Dollar)
  26. sq = sq.Where(squirrel.Eq{"user_id": filter.UserID})
  27. if len(filter.IDs) > 0 {
  28. sq = sq.Where(squirrel.Eq{"group_id": filter.IDs})
  29. }
  30. sq = sq.OrderBy("name")
  31. query, args, err := sq.ToSql()
  32. if err != nil {
  33. return nil, err
  34. }
  35. res := make([]*models.Group, 0, 8)
  36. err = r.db.SelectContext(ctx, &res, query, args...)
  37. if err != nil {
  38. if err == sql.ErrNoRows {
  39. return []*models.Group{}, nil
  40. }
  41. return nil, err
  42. }
  43. return res, nil
  44. }
  45. func (r *groupRepository) Insert(ctx context.Context, group models.Group) error {
  46. _, err := r.db.NamedExecContext(ctx, `
  47. INSERT INTO "group" (
  48. group_id, user_id, name, icon, description
  49. ) VALUES (
  50. :group_id, :user_id, :name, :icon, :description
  51. )
  52. `, &group)
  53. if err != nil {
  54. return err
  55. }
  56. return nil
  57. }
  58. func (r *groupRepository) Update(ctx context.Context, group models.Group) error {
  59. _, err := r.db.NamedExecContext(ctx, `
  60. UPDATE "group" SET
  61. name=:name,
  62. icon=:icon,
  63. description=:description
  64. WHERE group_id=:group_id
  65. `, &group)
  66. if err != nil {
  67. return err
  68. }
  69. return nil
  70. }
  71. func (r *groupRepository) Delete(ctx context.Context, group models.Group) error {
  72. _, err := r.db.ExecContext(ctx, `DELETE FROM "group" WHERE group_id=$1`, group.ID)
  73. if err != nil {
  74. if err == sql.ErrNoRows {
  75. return slerrors.NotFound("Group")
  76. }
  77. return err
  78. }
  79. return nil
  80. }