322 lines
11 KiB
Python
322 lines
11 KiB
Python
#!/usr/bin/env python3
|
|
"""Convert backup_2026-08-05.sql COPY data into init.up seed INSERTs."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import re
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parents[2]
|
|
BACKUP = ROOT / "public" / "images" / "backup_2026-08-05.sql"
|
|
OUT = Path(__file__).resolve().parent / "seed_from_backup.sql"
|
|
|
|
COPY_RE = re.compile(
|
|
r"^COPY public\.(\w+) \(([^)]+)\) FROM stdin;\n(.*?)^\\\.\n",
|
|
re.MULTILINE | re.DOTALL,
|
|
)
|
|
|
|
|
|
def copy_unescape(s: str) -> str:
|
|
"""Decode PostgreSQL COPY text-format escapes."""
|
|
out: list[str] = []
|
|
i = 0
|
|
while i < len(s):
|
|
if s[i] != "\\" or i + 1 >= len(s):
|
|
out.append(s[i])
|
|
i += 1
|
|
continue
|
|
n = s[i + 1]
|
|
if n == "\\":
|
|
out.append("\\")
|
|
i += 2
|
|
elif n == "b":
|
|
out.append("\b")
|
|
i += 2
|
|
elif n == "f":
|
|
out.append("\f")
|
|
i += 2
|
|
elif n == "n":
|
|
out.append("\n")
|
|
i += 2
|
|
elif n == "r":
|
|
out.append("\r")
|
|
i += 2
|
|
elif n == "t":
|
|
out.append("\t")
|
|
i += 2
|
|
elif n == "v":
|
|
out.append("\v")
|
|
i += 2
|
|
elif n == "x" and i + 3 < len(s):
|
|
out.append(chr(int(s[i + 2 : i + 4], 16)))
|
|
i += 4
|
|
elif n.isdigit():
|
|
j = i + 1
|
|
while j < len(s) and j < i + 4 and s[j].isdigit():
|
|
j += 1
|
|
out.append(chr(int(s[i + 1 : j], 8)))
|
|
i = j
|
|
else:
|
|
out.append(n)
|
|
i += 2
|
|
return "".join(out)
|
|
|
|
|
|
def parse_copy_rows(body: str, columns: list[str]) -> list[dict[str, str | None]]:
|
|
rows: list[dict[str, str | None]] = []
|
|
if not body.strip():
|
|
return rows
|
|
for line in body.split("\n"):
|
|
if line == "" or line == "\\.":
|
|
continue
|
|
parts = line.split("\t")
|
|
if len(parts) != len(columns):
|
|
raise SystemExit(
|
|
f"column count mismatch: expected {len(columns)}, got {len(parts)}: {line[:120]!r}"
|
|
)
|
|
row: dict[str, str | None] = {}
|
|
for col, raw in zip(columns, parts):
|
|
if raw == "\\N":
|
|
row[col] = None
|
|
else:
|
|
row[col] = copy_unescape(raw)
|
|
rows.append(row)
|
|
return rows
|
|
|
|
|
|
def load_tables(path: Path) -> dict[str, list[dict[str, str | None]]]:
|
|
text = path.read_text(encoding="utf-8")
|
|
tables: dict[str, list[dict[str, str | None]]] = {}
|
|
for m in COPY_RE.finditer(text):
|
|
name = m.group(1)
|
|
cols = [c.strip() for c in m.group(2).split(",")]
|
|
tables[name] = parse_copy_rows(m.group(3), cols)
|
|
return tables
|
|
|
|
|
|
def sql_str(value: str | None) -> str:
|
|
if value is None:
|
|
return "NULL"
|
|
tag = "s"
|
|
n = 0
|
|
while f"${tag}$" in value:
|
|
n += 1
|
|
tag = f"s{n}"
|
|
return f"${tag}${value}${tag}$"
|
|
|
|
|
|
def sql_json(value: str | None) -> str:
|
|
if not value:
|
|
return "'{}'::json"
|
|
# Normalize via json round-trip so we emit valid JSON text.
|
|
obj = json.loads(value)
|
|
dumped = json.dumps(obj, ensure_ascii=False, separators=(",", ":"))
|
|
return f"{sql_str(dumped)}::json"
|
|
|
|
|
|
def lang_parts(content: str | None) -> tuple[str, str, str]:
|
|
if not content:
|
|
return "", "", ""
|
|
obj = json.loads(content)
|
|
if not isinstance(obj, dict):
|
|
return "", "", ""
|
|
return (
|
|
str(obj.get("tm") or ""),
|
|
str(obj.get("ru") or ""),
|
|
str(obj.get("en") or ""),
|
|
)
|
|
|
|
|
|
def ts(value: str | None) -> str:
|
|
if not value:
|
|
return "DEFAULT"
|
|
# date-only → midnight
|
|
if re.fullmatch(r"\d{4}-\d{2}-\d{2}", value):
|
|
value = f"{value} 00:00:00"
|
|
return sql_str(value)
|
|
|
|
|
|
def setval(table: str) -> str:
|
|
return (
|
|
f"SELECT setval(pg_get_serial_sequence('{table}', 'id'), "
|
|
f"COALESCE((SELECT MAX(id) FROM {table}), 1));"
|
|
)
|
|
|
|
|
|
def build_seed(tables: dict[str, list[dict[str, str | None]]]) -> str:
|
|
lines: list[str] = []
|
|
lines.append("-- Auto-generated from backup_2026-08-05.sql — do not edit by hand")
|
|
lines.append("")
|
|
|
|
# ---- categories ----
|
|
cat_map: dict[str, int] = {}
|
|
cats = tables.get("categories", [])
|
|
if cats:
|
|
lines.append("-- categories")
|
|
for i, row in enumerate(cats, start=1):
|
|
uid = row["uuid"]
|
|
assert uid
|
|
cat_map[uid] = i
|
|
lines.append(
|
|
"INSERT INTO categories (id, name, status, img, updated_at, created_at) VALUES ("
|
|
f"{i}, {sql_json(row.get('name'))}, true, '', "
|
|
f"{ts(row.get('updated_at'))}, {ts(row.get('created_at'))});"
|
|
)
|
|
lines.append(setval("categories"))
|
|
lines.append("")
|
|
|
|
# ---- sub_categories + content ----
|
|
sub_map: dict[str, int] = {}
|
|
subs = tables.get("sub_cat", [])
|
|
if subs:
|
|
lines.append("-- sub_categories")
|
|
for i, row in enumerate(subs, start=1):
|
|
uid = row["uuid"]
|
|
assert uid
|
|
sub_map[uid] = i
|
|
cat_id_uuid = row.get("cat_id")
|
|
if not cat_id_uuid or cat_id_uuid not in cat_map:
|
|
raise SystemExit(f"unknown sub_cat.cat_id={cat_id_uuid!r} for uuid={uid}")
|
|
category_id = cat_map[cat_id_uuid]
|
|
lines.append(
|
|
"INSERT INTO sub_categories (id, category_id, name, status, count, updated_at, created_at) VALUES ("
|
|
f"{i}, {category_id}, {sql_json(row.get('name'))}, true, 0, "
|
|
f"{ts(row.get('updated_at'))}, {ts(row.get('created_at'))});"
|
|
)
|
|
lines.append(setval("sub_categories"))
|
|
lines.append("")
|
|
|
|
lines.append("-- sub_categories_content")
|
|
for i, row in enumerate(subs, start=1):
|
|
tm, ru, en = lang_parts(row.get("content"))
|
|
lines.append(
|
|
"INSERT INTO sub_categories_content (id, sub_category_id, en, ru, tm, updated_at, created_at) VALUES ("
|
|
f"{i}, {i}, {sql_str(en)}, {sql_str(ru)}, {sql_str(tm)}, "
|
|
f"{ts(row.get('updated_at'))}, {ts(row.get('created_at'))});"
|
|
)
|
|
lines.append(setval("sub_categories_content"))
|
|
lines.append("")
|
|
|
|
# ---- banner (from sliders) ----
|
|
sliders = tables.get("sliders", [])
|
|
if sliders:
|
|
lines.append("-- banner (from sliders)")
|
|
for i, row in enumerate(sliders, start=1):
|
|
tm, ru, en = lang_parts(row.get("content"))
|
|
img = row.get("image_path") or ""
|
|
lines.append(
|
|
"INSERT INTO banner (id, title, content_tm, content_ru, content_en, img, updated_at, created_at) VALUES ("
|
|
f"{i}, {sql_json(row.get('title'))}, {sql_str(tm)}, {sql_str(ru)}, {sql_str(en)}, "
|
|
f"{sql_str(img)}, {ts(row.get('updated_at'))}, {ts(row.get('created_at'))});"
|
|
)
|
|
lines.append(setval("banner"))
|
|
lines.append("")
|
|
|
|
# ---- setting (replace empty seed) ----
|
|
settings = tables.get("settings", [])
|
|
if settings:
|
|
lines.append("-- setting")
|
|
for i, row in enumerate(settings, start=1):
|
|
uid = row["uuid"]
|
|
assert uid
|
|
lines.append(
|
|
"INSERT INTO setting (id, uuid, logo_r, phone_number, fax_number, help_number, updated_at, created_at) VALUES ("
|
|
f"{i}, {sql_str(uid)}::uuid, {sql_str(row.get('logo_r') or '')}, "
|
|
f"{sql_str(row.get('phone_number') or '')}, {sql_str(row.get('fax_number') or '')}, "
|
|
f"{sql_str(row.get('help_number') or '')}, "
|
|
f"{ts(row.get('updated_at'))}, {ts(row.get('created_at'))});"
|
|
)
|
|
lines.append(setval("setting"))
|
|
lines.append("")
|
|
|
|
# ---- news + news_content ----
|
|
news_rows = tables.get("news", [])
|
|
if news_rows:
|
|
lines.append("-- news")
|
|
for i, row in enumerate(news_rows, start=1):
|
|
img = row.get("image_path") or "default.jpg"
|
|
date_raw = row.get("date") or row.get("created_at")
|
|
lines.append(
|
|
"INSERT INTO news (id, img, title, date_release, updated_at, created_at) VALUES ("
|
|
f"{i}, {sql_str(img)}, {sql_json(row.get('title'))}, "
|
|
f"{ts(date_raw)}, {ts(row.get('updated_at'))}, {ts(row.get('created_at'))});"
|
|
)
|
|
lines.append(setval("news"))
|
|
lines.append("")
|
|
|
|
lines.append("-- news_content")
|
|
for i, row in enumerate(news_rows, start=1):
|
|
tm, ru, en = lang_parts(row.get("content"))
|
|
lines.append(
|
|
"INSERT INTO news_content (id, news_id, en, ru, tm, updated_at, created_at) VALUES ("
|
|
f"{i}, {i}, {sql_str(en)}, {sql_str(ru)}, {sql_str(tm)}, "
|
|
f"{ts(row.get('updated_at'))}, {ts(row.get('created_at'))});"
|
|
)
|
|
lines.append(setval("news_content"))
|
|
lines.append("")
|
|
|
|
# ---- static (from four_category) ----
|
|
four = tables.get("four_category", [])
|
|
if four:
|
|
lines.append("-- static (from four_category)")
|
|
for i, row in enumerate(four, start=1):
|
|
tm, ru, en = lang_parts(row.get("content"))
|
|
logo = row.get("image_path") or ""
|
|
lines.append(
|
|
"INSERT INTO static (id, logo, title, content_tm, content_ru, content_en, updated_at, created_at) VALUES ("
|
|
f"{i}, {sql_str(logo)}, {sql_json(row.get('title'))}, "
|
|
f"{sql_str(tm)}, {sql_str(ru)}, {sql_str(en)}, "
|
|
f"{ts(row.get('updated_at'))}, {ts(row.get('created_at'))});"
|
|
)
|
|
lines.append(setval("static"))
|
|
lines.append("")
|
|
|
|
# ---- currency ----
|
|
curr = tables.get("currency", [])
|
|
if curr:
|
|
lines.append("-- currency")
|
|
for i, row in enumerate(curr, start=1):
|
|
tm, ru, en = lang_parts(row.get("content"))
|
|
path = row.get("video_path") or ""
|
|
lines.append(
|
|
"INSERT INTO currency (id, title, content_tm, content_ru, content_en, path, updated_at, created_at) VALUES ("
|
|
f"{i}, {sql_json(row.get('title'))}, {sql_str(tm)}, {sql_str(ru)}, {sql_str(en)}, "
|
|
f"{sql_str(path)}, {ts(row.get('updated_at'))}, {ts(row.get('created_at'))});"
|
|
)
|
|
lines.append(setval("currency"))
|
|
lines.append("")
|
|
|
|
return "\n".join(lines)
|
|
|
|
|
|
def main() -> None:
|
|
backup = Path(sys.argv[1]) if len(sys.argv) > 1 else BACKUP
|
|
out = Path(sys.argv[2]) if len(sys.argv) > 2 else OUT
|
|
tables = load_tables(backup)
|
|
expected = {
|
|
"categories": 8,
|
|
"sub_cat": 31,
|
|
"news": 73,
|
|
"sliders": 6,
|
|
"four_category": 4,
|
|
"currency": 1,
|
|
"settings": 1,
|
|
}
|
|
for name, n in expected.items():
|
|
got = len(tables.get(name, []))
|
|
if got != n:
|
|
raise SystemExit(f"{name}: expected {n} rows, got {got}")
|
|
seed = build_seed(tables)
|
|
out.write_text(seed, encoding="utf-8")
|
|
print(f"wrote {out} ({len(seed):,} bytes)")
|
|
print(
|
|
"counts:",
|
|
{k: len(tables[k]) for k in expected},
|
|
)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|