ForensicBench / tools /load_postgres.py
WaguyMZ's picture
ForensicBench unlabelled ledgers, loader, submission validator and card
f03ba44 verified
Raw History Blame Contribute Delete
2 kB
"""Load one ForensicBench sector into a PostgreSQL database.
Usage:
python tools/load_postgres.py --sector energy --dsn "dbname=forensicbench_energy user=postgres"
The database must already exist. Tables are created from the parquet schemas.
Requires: pandas, pyarrow, psycopg2-binary.
"""
import argparse, io
import pandas as pd
import pyarrow.parquet as pq
import psycopg2
PG_TYPES = {"string": "text", "large_string": "text", "int64": "bigint", "int32": "integer",
"double": "double precision", "float": "real", "bool": "boolean",
"date32[day]": "date"}
TABLES = ["je_header", "je_line", "chart_of_accounts", "vendors", "customers", "employees"]
def pg_type(arrow_type) -> str:
s = str(arrow_type)
if s.startswith("timestamp"):
return "timestamp"
return PG_TYPES.get(s, "text")
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--sector", required=True, choices=["energy", "healthcare", "luxurygoods", "manufacturing", "transport"])
ap.add_argument("--dsn", required=True)
ap.add_argument("--data-dir", default="data")
args = ap.parse_args()
conn = psycopg2.connect(args.dsn)
cur = conn.cursor()
for t in TABLES:
path = f"{args.data_dir}/{args.sector}/{t}.parquet"
schema = pq.read_schema(path)
cols = ", ".join(f'"{f.name}" {pg_type(f.type)}' for f in schema)
cur.execute(f'DROP TABLE IF EXISTS {t} CASCADE')
cur.execute(f'CREATE TABLE {t} ({cols})')
df = pd.read_parquet(path)
buf = io.StringIO()
df.to_csv(buf, index=False, header=False, na_rep="\\N")
buf.seek(0)
cur.copy_expert(f"COPY {t} FROM STDIN WITH (FORMAT csv, NULL '\\N')", buf)
print(f"{t}: {len(df)} rows")
cur.execute("CREATE INDEX IF NOT EXISTS je_line_doc ON je_line (document_id)")
cur.execute("CREATE INDEX IF NOT EXISTS je_header_doc ON je_header (document_id)")
conn.commit()
conn.close()
if __name__ == "__main__":
main()