1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798 |
- package repositories
- import (
- "context"
- "fmt"
- sq "github.com/Masterminds/squirrel"
- "git.dmitriygnatenko.ru/dima/homethings/internal/models"
- )
- const placeThingTableName = "place_thing"
- type PlaceThingRepository struct {
- db DB
- }
- func InitPlaceThingRepository(db DB) *PlaceThingRepository {
- return &PlaceThingRepository{db: db}
- }
- func (r PlaceThingRepository) GetByThingID(ctx context.Context, id uint64) (*models.PlaceThing, error) {
- q, v, err := sq.Select("place_id", "thing_id", "created_at").
- From(placeThingTableName).
- PlaceholderFormat(sq.Dollar).
- Where(sq.Eq{"thing_id": id}).
- ToSql()
- if err != nil {
- return nil, fmt.Errorf("build query: %w", err)
- }
- var res models.PlaceThing
- err = r.db.GetContext(ctx, &res, q, v...)
- if err != nil {
- return nil, fmt.Errorf("get: %w", err)
- }
- return &res, nil
- }
- func (r PlaceThingRepository) Add(ctx context.Context, req models.AddPlaceThingRequest) error {
- q, v, err := sq.Insert(placeThingTableName).
- PlaceholderFormat(sq.Dollar).
- Columns("place_id", "thing_id").
- Values(req.PlaceID, req.ThingID).
- ToSql()
- if err != nil {
- return fmt.Errorf("build query: %w", err)
- }
- _, err = r.db.ExecContext(ctx, q, v...)
- if err != nil {
- return fmt.Errorf("exec: %w", err)
- }
- return nil
- }
- func (r PlaceThingRepository) UpdatePlace(ctx context.Context, req models.UpdatePlaceThingRequest) error {
- q, v, err := sq.Update(placeThingTableName).
- PlaceholderFormat(sq.Dollar).
- Set("place_id", req.PlaceID).
- Set("updated_at", "NOW()").
- Where(sq.Eq{"thing_id": req.ThingID}).
- ToSql()
- if err != nil {
- return fmt.Errorf("build query: %w", err)
- }
- _, err = r.db.ExecContext(ctx, q, v...)
- if err != nil {
- return fmt.Errorf("exec: %w", err)
- }
- return nil
- }
- func (r PlaceThingRepository) DeleteThing(ctx context.Context, id uint64) error {
- q, v, err := sq.Delete(placeThingTableName).
- PlaceholderFormat(sq.Dollar).
- Where(sq.Eq{"thing_id": id}).
- ToSql()
- if err != nil {
- return fmt.Errorf("build query: %w", err)
- }
- _, err = r.db.ExecContext(ctx, q, v...)
- if err != nil {
- return fmt.Errorf("exec: %w", err)
- }
- return nil
- }
|