place_thing.go 2.2 KB

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