Spaces:
Sleeping
Sleeping
File size: 9,046 Bytes
992fce0 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 | """Loads a local SQLite financial_risk.db into a PostgreSQL database.
This is the seed path the repo otherwise lacks: the Docker image ships only
db/schema.sql, so a freshly provisioned Postgres has tables and zero rows and
every /risk-score call returns 404 until this is run.
Usage:
# inspect what would happen, no writes, no psycopg2 needed
python src/load_to_postgres.py --source financial_risk.db --dry-run
# create the schema and load everything
python src/load_to_postgres.py \\
--source financial_risk.db \\
--target "postgresql://user:pw@host:6543/postgres" \\
--create-schema
# reload from scratch over an existing database
python src/load_to_postgres.py --source financial_risk.db --truncate
If --target is omitted the DATABASE_URL environment variable is used.
Notes on the translation, which is not a straight copy:
* SQLite has no boolean type and stores 0/1 in columns declared BOOLEAN.
Those columns are detected from the source schema rather than hardcoded,
so a new BOOLEAN column does not silently break the load.
* db/schema.sql declares INTEGER PRIMARY KEY AUTOINCREMENT, which becomes
SERIAL in Postgres. Inserting explicit ids does not advance the backing
sequence, so every sequence is reset after the load -- without that, the
first application INSERT collides with an existing id.
* Tables load in foreign-key order.
"""
import argparse
import os
import re
import sqlite3 as _shimmed_sqlite3
import sys
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
SCHEMA_PATH = BASE_DIR / "db" / "schema.sql"
# Foreign-key safe insert order. Tables present in the source but not listed
# here are loaded afterwards, in whatever order SQLite reports them.
LOAD_ORDER = [
"users",
"accounts",
"transactions",
"feature_snapshots",
"risk_outcomes",
"model_predictions",
"shadow_model_predictions",
"repayment_outcomes",
"human_overrides",
"feature_trust_logs",
"calibration_memory",
"archetype_evolution_logs",
"portfolio_telemetry",
"autonomous_learning_runs",
"api_keys",
]
BATCH_SIZE = 1000
def real_sqlite3():
"""Returns the genuine stdlib sqlite3.
src/sqlite3.py shadows the stdlib module and reroutes connect() to Postgres
whenever DATABASE_URL is set -- which is exactly the situation this script
runs in, so it must reach past the shim to read the source file.
"""
return getattr(_shimmed_sqlite3, "real_sqlite3", _shimmed_sqlite3)
def translate_schema(script):
"""Converts the SQLite schema DDL to PostgreSQL."""
script = re.sub(r"INTEGER\s+PRIMARY\s+KEY\s+AUTOINCREMENT", "SERIAL PRIMARY KEY",
script, flags=re.IGNORECASE)
script = re.sub(r"BOOLEAN\s+NOT\s+NULL\s+DEFAULT\s+0", "BOOLEAN NOT NULL DEFAULT FALSE",
script, flags=re.IGNORECASE)
script = re.sub(r"BOOLEAN\s+NOT\s+NULL\s+DEFAULT\s+1", "BOOLEAN NOT NULL DEFAULT TRUE",
script, flags=re.IGNORECASE)
script = re.sub(r"PRAGMA\s+[^;]+;", "", script, flags=re.IGNORECASE)
return script
def inspect_source(src_conn):
"""Returns [(table, [columns], {bool columns}, row_count)] in load order."""
cur = src_conn.cursor()
cur.execute("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'")
present = {r[0] for r in cur.fetchall()}
ordered = [t for t in LOAD_ORDER if t in present]
ordered += sorted(present - set(ordered))
tables = []
for table in ordered:
cur.execute(f'PRAGMA table_info("{table}")')
info = cur.fetchall()
columns = [row[1] for row in info]
# row[2] is the declared type; SQLite keeps the literal text.
bool_cols = {row[1] for row in info if str(row[2]).upper().startswith("BOOL")}
cur.execute(f'SELECT COUNT(*) FROM "{table}"')
count = cur.fetchone()[0]
tables.append((table, columns, bool_cols, count))
return tables
def coerce_row(row, columns, bool_cols):
"""Maps a SQLite row to Postgres-native Python values."""
out = []
for col, val in zip(columns, row):
if col in bool_cols and val is not None:
out.append(bool(val))
else:
out.append(val)
return tuple(out)
def reset_sequences(pg_cur, tables):
"""Advances SERIAL sequences past the highest explicitly inserted id.
Loading explicit primary keys leaves the sequence at 1, so the first
application INSERT would raise a duplicate key error.
"""
reset = []
for table, columns, _bool_cols, _count in tables:
for col in columns:
pg_cur.execute("SELECT pg_get_serial_sequence(%s, %s)", (table, col))
seq = pg_cur.fetchone()[0]
if not seq:
continue
pg_cur.execute(
f'SELECT setval(%s, COALESCE((SELECT MAX("{col}") FROM "{table}"), 0) + 1, false)',
(seq,))
reset.append(f"{table}.{col}")
return reset
def main():
ap = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--source", default=str(BASE_DIR / "financial_risk.db"),
help="path to the source SQLite database")
ap.add_argument("--target", default=None,
help="PostgreSQL DSN (defaults to $DATABASE_URL)")
ap.add_argument("--create-schema", action="store_true",
help="apply db/schema.sql to the target before loading")
ap.add_argument("--truncate", action="store_true",
help="empty the target tables before loading")
ap.add_argument("--dry-run", action="store_true",
help="report what would be loaded and exit without connecting")
args = ap.parse_args()
source = Path(args.source)
if not source.exists():
sys.exit(f"Source database not found: {source}")
src = real_sqlite3().connect(str(source))
tables = inspect_source(src)
total = sum(c for _t, _c, _b, c in tables)
print(f"Source: {source}")
print(f"{'table':<28}{'rows':>10} boolean columns")
print("-" * 68)
for table, _columns, bool_cols, count in tables:
print(f"{table:<28}{count:>10} {', '.join(sorted(bool_cols)) or '-'}")
print("-" * 68)
print(f"{'TOTAL':<28}{total:>10}")
if args.dry_run:
print("\nDry run: nothing written.")
return
dsn = args.target or os.environ.get("DATABASE_URL")
if not dsn:
sys.exit("No target given. Pass --target or set DATABASE_URL.")
if dsn.startswith("postgres://"):
dsn = dsn.replace("postgres://", "postgresql://", 1)
try:
import psycopg2
from psycopg2.extras import execute_values
except ImportError:
sys.exit("psycopg2 is required to load. Install with: pip install psycopg2-binary")
print(f"\nTarget: {re.sub(r'//[^@]*@', '//***@', dsn)}")
pg = psycopg2.connect(dsn)
try:
cur = pg.cursor()
if args.create_schema:
if not SCHEMA_PATH.exists():
sys.exit(f"Schema file not found: {SCHEMA_PATH}")
print("Applying schema...")
cur.execute(translate_schema(SCHEMA_PATH.read_text(encoding="utf-8")))
pg.commit()
print(" schema applied.")
if args.truncate:
names = ", ".join(f'"{t}"' for t, _c, _b, _n in tables)
print("Truncating target tables...")
cur.execute(f"TRUNCATE {names} RESTART IDENTITY CASCADE")
pg.commit()
print(" truncated.")
loaded = 0
for table, columns, bool_cols, count in tables:
if count == 0:
print(f" {table:<28} skipped (empty)")
continue
collist = ", ".join(f'"{c}"' for c in columns)
sql = f'INSERT INTO "{table}" ({collist}) VALUES %s ON CONFLICT DO NOTHING'
src_cur = src.cursor()
src_cur.execute(f'SELECT {collist} FROM "{table}"')
written = 0
while True:
rows = src_cur.fetchmany(BATCH_SIZE)
if not rows:
break
execute_values(cur, sql,
[coerce_row(r, columns, bool_cols) for r in rows],
page_size=BATCH_SIZE)
written += len(rows)
pg.commit()
loaded += written
print(f" {table:<28} {written:>10} rows")
print("\nResetting SERIAL sequences...")
reset = reset_sequences(cur, tables)
pg.commit()
for name in reset:
print(f" {name}")
if not reset:
print(" (none found)")
print(f"\nDone. {loaded} rows loaded into PostgreSQL.")
except Exception:
pg.rollback()
raise
finally:
pg.close()
src.close()
if __name__ == "__main__":
main()
|