gendesign/tradein-mvp/deploy/import-rosreestr.sh
Light1YT b51893f7c3 fix(tradein): plain natural-key dedup_hash for rosreestr deals (#576)
rosreestr ДКП deals used dedup_hash = md5('ros:dkp:' || id) — a hash of
an already-unique natural key. The md5 is collision-prone (theoretically),
not human-readable, and irreversible (can't recover the source id from it,
which mattered because deals.source_id was never populated).

Replace with the plain natural key 'ros:dkp:' || id (injective, zero
collision, reversible) and populate deals.source_id going forward, in both
the live scheduler import (import_rosreestr_dkp) and the legacy
deploy/import-rosreestr.sh.

Migration 077 backfills the existing 49,791 rows: recovers the original id
from FDW foreign table gendesign_rosreestr_deals by matching the old md5,
then writes the plain key + source_id. Idempotent; plain keys and md5 hex
are format-disjoint so no transient UNIQUE violation on deals_dedup_hash_key.
Verified via prod dry-run (ROLLBACK): UPDATE 49791, 0 md5 remaining, 3.85s.

Closes #576
2026-05-29 11:55:15 +05:00

87 lines
4.3 KiB
Bash
Executable file
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env bash
# Импорт реальных сделок Росреестра из gendesign-БД в tradein deals.
#
# Источник: gendesign-postgres-1 / rosreestr_deals (6.8М строк, партиц.).
# Берём ЕКБ квартиры (realestate_type_code=002001003000) за последние ~18 мес.
# rooms выводим из площади (Росреестр не отдаёт кол-во комнат).
# Координаты — NULL, проставляются отдельно (geocode по street).
#
# Только ДКП (вторичка) — ДДУ застройщиков скёюят median, отделены сознательно. См. PR-A.
#
# Запуск на прод-хосте: ./import-rosreestr.sh
# Повторяемо: дедуп по dedup_hash, новый запуск подтянет свежие кварталы.
set -euo pipefail
SRC_PG="${SRC_PG:-gendesign-postgres-1}"
DST_PG="${DST_PG:-tradein-postgres}"
SRC_DB="${SRC_DB:-gendesign}"
SRC_USER="${SRC_USER:-gendesign}"
SINCE="${SINCE:-2024-01-01}"
echo "[$(date -u +%H:%M:%S)] import-rosreestr: ЕКБ квартиры с $SINCE"
# 1. Staging-таблица в tradein.
docker exec "$DST_PG" psql -U tradein -d tradein -v ON_ERROR_STOP=on -c "
-- DROP перед CREATE: страхует от устаревшей формы staging-таблицы, если прошлый
-- запуск упал между CREATE и финальным DROP под старым кодом (без source_id).
DROP TABLE IF EXISTS deals_ros_staging;
CREATE TABLE deals_ros_staging (
dedup_hash text PRIMARY KEY, source_id text, address text, rooms int, area_m2 numeric,
floor int, year_built int, price_rub bigint, price_per_m2 int, deal_date date
);
"
# 2. Трансформируем на gendesign-стороне, пайпим CSV в staging.
docker exec "$SRC_PG" psql -U "$SRC_USER" -d "$SRC_DB" -v ON_ERROR_STOP=on -c "
COPY (
SELECT
'ros:dkp:' || id::text AS dedup_hash,
id::text AS source_id,
'Екатеринбург, ' || trim(street) AS address,
CASE
WHEN area < 30 THEN 0 WHEN area < 44 THEN 1
WHEN area < 62 THEN 2 WHEN area < 85 THEN 3
ELSE 4 END AS rooms,
round(area, 2) AS area_m2,
LEAST(NULLIF(substring(floor from '[0-9]+'), '')::int, 100) AS floor,
year_build AS year_built,
round(deal_price)::bigint AS price_rub,
round(price_per_sqm)::int AS price_per_m2,
period_start_date AS deal_date
FROM rosreestr_deals
WHERE region_code = 66
AND city ILIKE '%катеринбург%'
AND realestate_type_code = '002001003000'
AND area BETWEEN 18 AND 200
AND deal_price BETWEEN 1000000 AND 100000000
AND street IS NOT NULL AND trim(street) <> ''
AND doc_type = 'ДКП'
AND period_start_date >= '$SINCE'
) TO STDOUT WITH CSV
" | docker exec -i "$DST_PG" psql -U tradein -d tradein -v ON_ERROR_STOP=on -c "
COPY deals_ros_staging FROM STDIN WITH CSV
"
STAGED=$(docker exec "$DST_PG" psql -U tradein -d tradein -tAc "SELECT count(*) FROM deals_ros_staging")
echo "[$(date -u +%H:%M:%S)] staged: $STAGED строк"
# 3. Удаляем старые синтетические сделки, вставляем реальные (дедуп).
docker exec "$DST_PG" psql -U tradein -d tradein -v ON_ERROR_STOP=on -c "
DELETE FROM deals WHERE address = 'Екатеринбург, реальная сделка';
INSERT INTO deals (
source, dedup_hash, source_id, address, rooms, area_m2, floor,
year_built, price_rub, price_per_m2, deal_date
)
SELECT 'rosreestr', dedup_hash, source_id, address, rooms, area_m2, floor,
year_built, price_rub, price_per_m2, deal_date
FROM deals_ros_staging
ON CONFLICT (dedup_hash) DO NOTHING;
DROP TABLE deals_ros_staging;
"
TOTAL=$(docker exec "$DST_PG" psql -U tradein -d tradein -tAc "SELECT count(*) FROM deals")
echo "[$(date -u +%H:%M:%S)] deals всего: $TOTAL"
echo "Координаты проставит geocode-deals (отдельный шаг)."