gendesign/tradein-mvp/backend/data/sql/044_external_valuations_link.sql
lekss361 d019b5327e feat(tradein): SQL 040-046 — matching schema delta (Phase 1.1)
Multi-Source Integration Phase 1.1 thin-delta migrations. Gap audit showed
80%+ of planned schema already in 014/017/020/026/028/029/030/031 —
this PR adds only the missing pieces:

- 040 houses_extend: complex_id + avito_validated_at + cian_validated_at
- 041 house_sources_noop: COMMENT aliases for ext_source/ext_id/matched_method
- 042 listing_sources_price_divergence_idx: partial index for /search
- 043 house_reviews_extend: likes column
- 044 external_valuations_link: house_id/listing_id FKs + low/high price band
- 045 house_placement_history_extend: source_confidence + notes + 3-col UNIQUE
- 046 views: v_price_divergence + v_cross_source_health + v_data_quality

All BEGIN/COMMIT, IF NOT EXISTS, FK ON DELETE CASCADE.
Idempotent — safe re-apply on prod.

Refs Master Plan sec 1, 4-8 + Cross_Source_Matching sec 2-4.
2026-05-23 16:22:58 +03:00

37 lines
1.6 KiB
PL/PgSQL

-- 044_external_valuations_link.sql
-- Purpose: Link external_valuations to canonical entities (house/listing) + add
-- sale band columns (low/high) per Cross_Source_Matching sec 13.1.
-- Table base in 026 + 029. Existing UNIQUE (source, cache_key) preserved.
-- Dependencies: 026_external_valuations.sql, 029_extend_matching_valuation_dynamics.sql,
-- 009_houses.sql, 002_core_tables.sql (listings)
BEGIN;
ALTER TABLE external_valuations
ADD COLUMN IF NOT EXISTS house_id bigint REFERENCES houses(id) ON DELETE CASCADE,
ADD COLUMN IF NOT EXISTS listing_id bigint REFERENCES listings(id) ON DELETE CASCADE,
ADD COLUMN IF NOT EXISTS low_price bigint,
ADD COLUMN IF NOT EXISTS high_price bigint;
CREATE INDEX IF NOT EXISTS external_valuations_house_idx
ON external_valuations (house_id)
WHERE house_id IS NOT NULL;
CREATE INDEX IF NOT EXISTS external_valuations_listing_idx
ON external_valuations (listing_id)
WHERE listing_id IS NOT NULL;
CREATE UNIQUE INDEX IF NOT EXISTS external_valuations_canonical_uniq_idx
ON external_valuations (source, house_id, listing_id)
WHERE house_id IS NOT NULL AND listing_id IS NOT NULL;
COMMENT ON COLUMN external_valuations.house_id IS
'FK to canonical house (post-matching). NULL for pre-matching cache rows keyed by cache_key.';
COMMENT ON COLUMN external_valuations.listing_id IS
'FK to canonical listing (post-matching). NULL for house-level estimates.';
COMMENT ON COLUMN external_valuations.low_price IS
'Lower bound of sale band (Cian sometimes returns; NULL for Avito IMV).';
COMMENT ON COLUMN external_valuations.high_price IS
'Upper bound of sale band.';
COMMIT;