Spaces:
Running

hub / backend /scripts /migrate_sqlite_to_pg.py
Andre
deploy: snapshot c96b9ab -- Inventory Journals (Lagerforandringsjournal) na Contabilidade (v1.3.61)
77db408
Raw History Blame Contribute Delete
7.18 kB
r"""One-time SQLite -> Postgres data copy for the Gateway ERP cutover.
Copies the OPERATIONAL tables only — auth, audit trail, usage logs,
translation memory, app metadata and sync history:
users, api_tokens, event_logs, access_logs, page_views,
translation_cache, app_meta, etl_sync_requests
Business data (items/customers/invoices/GL) is deliberately NOT copied:
Visma is the source of truth, and a full force sync re-imports everything
through the exact code paths that will write to Postgres from then on.
The processed_files dedupe ledger is left empty on purpose so that first
sync imports every file (same semantics as a purge).
Usage (from backend/, with the venv python):
set NEON_DATABASE_URL=postgresql://... REM or: call ..\run-local.secrets.cmd
python scripts\migrate_sqlite_to_pg.py --source C:\path\to\inventory-snapshot.db
The target URL is read ONLY from the environment (NEON_DATABASE_URL, else
DATABASE_URL) so the secret never lands in a command line or shell history.
Re-runnable: --wipe-target clears previously copied rows first; without it
the script refuses to write into a non-empty table.
"""
from __future__ import annotations
import argparse
import os
import sys
from pathlib import Path
import sqlalchemy as sa
sys.path.insert(0, str(Path(__file__).resolve().parents[1])) # backend/
import database # noqa: E402
import models # noqa: E402
# FK-safe order (users before api_tokens; the rest are independent).
COPY_MODELS = [
models.User,
models.ApiToken,
models.EventLog,
models.AccessLog,
models.PageView,
models.TranslationCache,
models.AppMeta,
models.EtlSyncRequest,
]
BATCH = 1000
def _target_url() -> str:
raw = os.environ.get("NEON_DATABASE_URL") or os.environ.get("DATABASE_URL") or ""
if raw.startswith("postgres://"):
raw = "postgresql+psycopg://" + raw[len("postgres://"):]
elif raw.startswith("postgresql://"):
raw = "postgresql+psycopg://" + raw[len("postgresql://"):]
if not raw.startswith("postgresql+psycopg://"):
sys.exit("ERROR: set NEON_DATABASE_URL (or DATABASE_URL) to a postgresql:// "
"connection string before running. Refusing to guess a target.")
return raw
def _apply_schema(target_url: str) -> None:
"""Run `alembic upgrade head` against the target."""
from alembic import command
from alembic.config import Config
backend_dir = Path(__file__).resolve().parents[1]
cfg = Config(str(backend_dir / "alembic.ini"))
cfg.set_main_option("script_location", str(backend_dir / "alembic"))
# env.py reads the resolved URL off the (already imported) database module.
database.SQLALCHEMY_DATABASE_URL = target_url
command.upgrade(cfg, "head")
def main() -> int:
p = argparse.ArgumentParser(description="Copy operational tables from a SQLite snapshot to Postgres.")
p.add_argument("--source", required=True, type=Path,
help="SQLite snapshot file (e.g. the Admin backup download)")
p.add_argument("--wipe-target", action="store_true",
help="Delete previously copied rows in the target tables first")
p.add_argument("--dry-run", action="store_true",
help="Read + report source counts; write nothing")
args = p.parse_args()
if not args.source.exists():
sys.exit(f"ERROR: source file not found: {args.source}")
src_engine = sa.create_engine(f"sqlite:///{args.source}")
src_inspector = sa.inspect(src_engine)
if args.dry_run:
print("DRY RUN — source row counts:")
with src_engine.connect() as conn:
for model in COPY_MODELS:
t = model.__tablename__
n = conn.execute(sa.text(f'SELECT COUNT(*) FROM "{t}"')).scalar() \
if src_inspector.has_table(t) else "(table absent)"
print(f" {t:20} {n}")
return 0
target_url = _target_url()
print("Applying schema on target (alembic upgrade head)...")
_apply_schema(target_url)
tgt_engine = sa.create_engine(target_url, pool_pre_ping=True)
failures: list[str] = []
with tgt_engine.begin() as tgt:
if args.wipe_target:
for model in reversed(COPY_MODELS):
n = tgt.execute(sa.delete(model.__table__)).rowcount
if n:
print(f" wiped {n} rows from {model.__tablename__}")
for model in COPY_MODELS:
table = model.__table__
name = model.__tablename__
if not src_inspector.has_table(name):
print(f" {name:20} absent in source — skipped")
continue
existing = tgt.execute(sa.select(sa.func.count()).select_from(table)).scalar()
if existing:
sys.exit(f"ERROR: target table {name} already has {existing} rows. "
"Re-run with --wipe-target to replace them.")
src_cols = {c["name"] for c in src_inspector.get_columns(name)}
cols = [c for c in table.columns if c.name in src_cols]
missing = [c.name for c in table.columns if c.name not in src_cols]
if missing:
print(f" {name}: source snapshot lacks columns {missing} — they get column defaults/NULL")
copied = 0
with src_engine.connect() as src:
# Select through the REAL metadata columns so column types
# apply on read — critical for JSON columns: a bare
# sa.column() read returns SQLite's serialized text, which the
# typed insert then re-serializes into double-encoded JSON
# (bit event_logs.changes on the 2026-08-19 cutover).
result = src.execute(sa.select(*cols))
while True:
rows = result.fetchmany(BATCH)
if not rows:
break
payload = [dict(zip([c.name for c in cols], row)) for row in rows]
tgt.execute(sa.insert(table), payload)
copied += len(payload)
with src_engine.connect() as src:
src_count = src.execute(sa.text(f'SELECT COUNT(*) FROM "{name}"')).scalar()
print(f" {name:20} copied {copied}/{src_count}")
if copied != src_count:
failures.append(f"{name}: copied {copied} of {src_count}")
# Explicit ids were inserted — bump the identity sequence so the
# next app-generated row doesn't collide.
pk = list(table.primary_key.columns)
if len(pk) == 1 and isinstance(pk[0].type, sa.Integer):
tgt.execute(sa.text(
f"SELECT setval(pg_get_serial_sequence('{name}', '{pk[0].name}'), "
f"COALESCE((SELECT MAX({pk[0].name}) FROM {name}), 0) + 1, false)"
))
if failures:
print("FAILED verification:\n " + "\n ".join(failures))
return 1
print("Copy complete and verified. Business data comes from the first force sync.")
return 0
if __name__ == "__main__":
sys.exit(main())