place_thing.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. package repositories
  2. import (
  3. "context"
  4. "fmt"
  5. sq "github.com/Masterminds/squirrel"
  6. "git.dmitriygnatenko.ru/dima/homethings/internal/models"
  7. )
  8. const placeThingTableName = "place_thing"
  9. type PlaceThingRepository struct {
  10. db DB
  11. }
  12. func InitPlaceThingRepository(db DB) *PlaceThingRepository {
  13. return &PlaceThingRepository{db: db}
  14. }
  15. func (r PlaceThingRepository) GetByThingID(ctx context.Context, id uint64) (*models.PlaceThing, error) {
  16. q, v, err := sq.Select("place_id", "thing_id", "created_at").
  17. From(placeThingTableName).
  18. PlaceholderFormat(sq.Dollar).
  19. Where(sq.Eq{"thing_id": id}).
  20. ToSql()
  21. if err != nil {
  22. return nil, fmt.Errorf("build query: %w", err)
  23. }
  24. var res models.PlaceThing
  25. err = r.db.GetContext(ctx, &res, q, v...)
  26. if err != nil {
  27. return nil, fmt.Errorf("get: %w", err)
  28. }
  29. return &res, nil
  30. }
  31. func (r PlaceThingRepository) Add(ctx context.Context, req models.AddPlaceThingRequest) error {
  32. q, v, err := sq.Insert(placeThingTableName).
  33. PlaceholderFormat(sq.Dollar).
  34. Columns("place_id", "thing_id").
  35. Values(req.PlaceID, req.ThingID).
  36. ToSql()
  37. if err != nil {
  38. return fmt.Errorf("build query: %w", err)
  39. }
  40. _, err = r.db.ExecContext(ctx, q, v...)
  41. if err != nil {
  42. return fmt.Errorf("exec: %w", err)
  43. }
  44. return nil
  45. }
  46. func (r PlaceThingRepository) UpdatePlace(ctx context.Context, req models.UpdatePlaceThingRequest) error {
  47. q, v, err := sq.Update(placeThingTableName).
  48. PlaceholderFormat(sq.Dollar).
  49. Set("place_id", req.PlaceID).
  50. Set("updated_at", "NOW()").
  51. Where(sq.Eq{"thing_id": req.ThingID}).
  52. ToSql()
  53. if err != nil {
  54. return fmt.Errorf("build query: %w", err)
  55. }
  56. _, err = r.db.ExecContext(ctx, q, v...)
  57. if err != nil {
  58. return fmt.Errorf("exec: %w", err)
  59. }
  60. return nil
  61. }
  62. func (r PlaceThingRepository) DeleteThing(ctx context.Context, id uint64) error {
  63. q, v, err := sq.Delete(placeThingTableName).
  64. PlaceholderFormat(sq.Dollar).
  65. Where(sq.Eq{"thing_id": id}).
  66. ToSql()
  67. if err != nil {
  68. return fmt.Errorf("build query: %w", err)
  69. }
  70. _, err = r.db.ExecContext(ctx, q, v...)
  71. if err != nil {
  72. return fmt.Errorf("exec: %w", err)
  73. }
  74. return nil
  75. }