package db import ( "context" "encoding/json" "errors" "fmt" "strings" "online-back/internal/admin/location" "online-back/pkg/client/postgresql" "online-back/pkg/logging" "github.com/jackc/pgx/v4" ) type repository struct { client postgresql.Client logger *logging.Logger } func NewRepository(client postgresql.Client, logger *logging.Logger) location.Repository { return &repository{client: client, logger: logger} } func (r *repository) List(ctx context.Context, filter location.ListFilter) (location.ListLocationDTO, error) { fromClause, whereClause, args := buildListQuery(filter) var count int64 countQuery := `SELECT COUNT(*) ` + fromClause + whereClause if err := r.client.QueryRow(ctx, countQuery, args...).Scan(&count); err != nil { return location.ListLocationDTO{}, err } offset := (filter.Page - 1) * filter.Limit limitPlaceholder := len(args) + 1 offsetPlaceholder := len(args) + 2 listQuery := fmt.Sprintf( `SELECT l.id, l.province_id, l.title, l.status%s%s ORDER BY l.id LIMIT $%d OFFSET $%d`, fromClause, whereClause, limitPlaceholder, offsetPlaceholder, ) listArgs := append(args, filter.Limit, offset) rows, err := r.client.Query(ctx, listQuery, listArgs...) if err != nil { return location.ListLocationDTO{}, err } defer rows.Close() var items []location.LocationDTO for rows.Next() { item, err := scanLocation(rows) if err != nil { return location.ListLocationDTO{}, err } items = append(items, item) } if err := rows.Err(); err != nil { return location.ListLocationDTO{}, err } return location.ListLocationDTO{ Count: count, Locations: items, }, nil } func buildListQuery(filter location.ListFilter) (fromClause, whereClause string, args []interface{}) { fromClause = ` FROM location l` if filter.ProvinceName != "" { fromClause += ` JOIN province p ON p.id = l.province_id` } var conditions []string if filter.ProvinceID != nil { args = append(args, *filter.ProvinceID) conditions = append(conditions, fmt.Sprintf("l.province_id = $%d", len(args))) } if filter.ProvinceName != "" { args = append(args, likePattern(filter.ProvinceName)) n := len(args) conditions = append(conditions, fmt.Sprintf(`( p.title->>'en' ILIKE $%[1]d OR p.title->>'ru' ILIKE $%[1]d OR p.title->>'tm' ILIKE $%[1]d )`, n)) } if filter.LocationName != "" { args = append(args, likePattern(filter.LocationName)) n := len(args) conditions = append(conditions, fmt.Sprintf(`( l.title->>'en' ILIKE $%[1]d OR l.title->>'ru' ILIKE $%[1]d OR l.title->>'tm' ILIKE $%[1]d )`, n)) } if filter.Status != nil { args = append(args, *filter.Status) conditions = append(conditions, fmt.Sprintf("l.status = $%d", len(args))) } if len(conditions) == 0 { return fromClause, "", args } return fromClause, " WHERE " + strings.Join(conditions, " AND "), args } func likePattern(term string) string { term = strings.ReplaceAll(term, `\`, `\\`) term = strings.ReplaceAll(term, `%`, `\%`) term = strings.ReplaceAll(term, `_`, `\_`) return "%" + term + "%" } func (r *repository) GetByID(ctx context.Context, id int64) (location.LocationDTO, error) { row := r.client.QueryRow(ctx, `SELECT id, province_id, title, status FROM location WHERE id = $1`, id, ) item, err := scanLocation(row) if errors.Is(err, pgx.ErrNoRows) { return location.LocationDTO{}, err } return item, err } func (r *repository) Create(ctx context.Context, dto location.CreateLocationDTO) (location.LocationDTO, error) { if err := r.ensureProvinceExists(ctx, dto.ProvinceId); err != nil { return location.LocationDTO{}, err } title, err := json.Marshal(dto.Title) if err != nil { return location.LocationDTO{}, err } status := true if dto.Status != nil { status = *dto.Status } row := r.client.QueryRow(ctx, `INSERT INTO location (province_id, title, status) VALUES ($1, $2, $3) RETURNING id, province_id, title, status`, dto.ProvinceId, title, status, ) return scanLocation(row) } func (r *repository) Update(ctx context.Context, id int64, dto location.UpdateLocationDTO) (location.LocationDTO, error) { if err := r.ensureProvinceExists(ctx, dto.ProvinceId); err != nil { return location.LocationDTO{}, err } title, err := json.Marshal(dto.Title) if err != nil { return location.LocationDTO{}, err } row := r.client.QueryRow(ctx, `UPDATE location SET province_id = $1, title = $2, status = $3 WHERE id = $4 RETURNING id, province_id, title, status`, dto.ProvinceId, title, dto.Status, id, ) item, err := scanLocation(row) if errors.Is(err, pgx.ErrNoRows) { return location.LocationDTO{}, err } return item, err } func (r *repository) UpdateStatus(ctx context.Context, id int64, status bool) (location.LocationDTO, error) { row := r.client.QueryRow(ctx, `UPDATE location SET status = $1 WHERE id = $2 RETURNING id, province_id, title, status`, status, id, ) item, err := scanLocation(row) if errors.Is(err, pgx.ErrNoRows) { return location.LocationDTO{}, err } return item, err } func (r *repository) Delete(ctx context.Context, id int64) error { tag, err := r.client.Exec(ctx, `DELETE FROM location WHERE id = $1`, id) if err != nil { return err } if tag.RowsAffected() == 0 { return pgx.ErrNoRows } return nil } func (r *repository) ensureProvinceExists(ctx context.Context, provinceID int64) error { var id int64 err := r.client.QueryRow(ctx, `SELECT id FROM province WHERE id = $1`, provinceID).Scan(&id) if errors.Is(err, pgx.ErrNoRows) { return fmt.Errorf("province not found") } return err } type scannable interface { Scan(dest ...interface{}) error } func scanLocation(row scannable) (location.LocationDTO, error) { var item location.LocationDTO var titleJSON []byte if err := row.Scan(&item.Id, &item.ProvinceId, &titleJSON, &item.Status); err != nil { return location.LocationDTO{}, err } if err := json.Unmarshal(titleJSON, &item.Title); err != nil { return location.LocationDTO{}, err } return item, nil }