place_image.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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 placeImageTableName = "place_image"
  9. type PlaceImageRepository struct {
  10. db DB
  11. }
  12. func InitPlaceImageRepository(db DB) *PlaceImageRepository {
  13. return &PlaceImageRepository{db: db}
  14. }
  15. func (r PlaceImageRepository) Add(ctx context.Context, req models.AddPlaceImageRequest) error {
  16. q, v, err := sq.Insert(placeImageTableName).
  17. PlaceholderFormat(sq.Dollar).
  18. Columns("place_id", "image").
  19. Values(req.PlaceID, req.Image).
  20. ToSql()
  21. if err != nil {
  22. return fmt.Errorf("build query: %w", err)
  23. }
  24. _, err = r.db.ExecContext(ctx, q, v...)
  25. if err != nil {
  26. return fmt.Errorf("exec: %w", err)
  27. }
  28. return nil
  29. }
  30. func (r PlaceImageRepository) Get(ctx context.Context, id uint64) (*models.Image, error) {
  31. q, v, err := sq.Select("id", "image", "place_id", "created_at").
  32. From(placeImageTableName).
  33. PlaceholderFormat(sq.Dollar).
  34. Where(sq.Eq{"id": id}).
  35. ToSql()
  36. if err != nil {
  37. return nil, fmt.Errorf("build query: %w", err)
  38. }
  39. var res models.Image
  40. err = r.db.GetContext(ctx, &res, q, v...)
  41. if err != nil {
  42. return nil, fmt.Errorf("get: %w", err)
  43. }
  44. return &res, nil
  45. }
  46. func (r PlaceImageRepository) GetByPlaceID(ctx context.Context, id uint64) ([]models.Image, error) {
  47. var res []models.Image
  48. q := "WITH RECURSIVE cte (id, parent_id) AS (" +
  49. "SELECT id, parent_id " +
  50. "FROM " + placeTableName + " " +
  51. "WHERE id = $1 " +
  52. "UNION ALL " +
  53. "SELECT p.id, p.parent_id " +
  54. "FROM " + placeTableName + " p " +
  55. "INNER JOIN cte ON p.parent_id = cte.id " +
  56. ")" +
  57. "SELECT pi.id, pi.image, pi.place_id, pi.created_at " +
  58. "FROM cte, " + placeImageTableName + " pi " +
  59. "WHERE pi.place_id = cte.id " +
  60. "ORDER BY pi.created_at DESC"
  61. err := r.db.SelectContext(ctx, &res, q, id)
  62. if err != nil {
  63. return nil, fmt.Errorf("select: %w", err)
  64. }
  65. return res, nil
  66. }
  67. func (r PlaceImageRepository) Delete(ctx context.Context, id uint64) error {
  68. q, v, err := sq.Delete(placeImageTableName).
  69. PlaceholderFormat(sq.Dollar).
  70. Where(sq.Eq{"id": id}).
  71. ToSql()
  72. if err != nil {
  73. return fmt.Errorf("build query: %w", err)
  74. }
  75. _, err = r.db.ExecContext(ctx, q, v...)
  76. if err != nil {
  77. return fmt.Errorf("exec: %w", err)
  78. }
  79. return nil
  80. }