import { execFileSync } from "node:child_process"; import { Pool } from "pg"; import { poolConfig } from "../db/client"; const sqlitePath = process.argv[2]; const url = process.env.DATABASE_URL; if (!sqlitePath || !url) { console.error("Usage: DATABASE_URL=... node --import tsx scripts/import_sqlite_to_postgres.ts "); process.exit(2); } const tables = [ "users", "tasks", "clips", "assignments", "ratings", "payouts", "payout_items", "activity_log", "rater_profiles", "profile_changes", "integrity_events", ] as const; const identifier = (value: string) => `"${value.replaceAll('"', '""')}"`; const pool = new Pool({ ...poolConfig(url), max: 1, options: "-c search_path=voice_acting_arena", }); const client = await pool.connect(); try { await client.query("BEGIN"); await client.query("SELECT pg_advisory_xact_lock(hashtext('voice_acting_arena_import'))"); for (const table of tables) { const output = execFileSync("sqlite3", [sqlitePath, "-json", `SELECT * FROM ${table}`], { encoding: "utf8", maxBuffer: 100 * 1024 * 1024 }); const rows = (output.trim() ? JSON.parse(output) : []) as Record[]; for (const row of rows) { const columns = Object.keys(row), values = Object.values(row); await client.query( `INSERT INTO ${identifier(table)} (${columns.map(identifier).join(",")}) VALUES (${values.map((_, index) => `$${index + 1}`).join(",")}) ON CONFLICT DO NOTHING`, values, ); } const target = await client.query(`SELECT count(*)::int count FROM ${identifier(table)}`); console.log(`${table}: source=${rows.length} target=${target.rows[0].count}`); } await client.query("COMMIT"); } catch (error) { await client.query("ROLLBACK"); throw error; } finally { client.release(); await pool.end(); }