From e4089c9f75603c8c081331b79ba7d3f8484efc93 Mon Sep 17 00:00:00 2001 From: Deep Koluguri Date: Sun, 5 Apr 2026 15:47:51 -0400 Subject: [PATCH] updated migration script --- backend/scripts/migrate-pg-to-sqlite.js | 29 ++++++++++++------------- 1 file changed, 14 insertions(+), 15 deletions(-) diff --git a/backend/scripts/migrate-pg-to-sqlite.js b/backend/scripts/migrate-pg-to-sqlite.js index 4f81778..f66a101 100644 --- a/backend/scripts/migrate-pg-to-sqlite.js +++ b/backend/scripts/migrate-pg-to-sqlite.js @@ -112,10 +112,6 @@ async function fetchPostgresTable(pg, table) { } } -async function clearSqliteTable(sqlite, table) { - await sqlite.query(`DELETE FROM "${table}"`, { type: QueryTypes.DELETE }); -} - async function insertRows(sqlite, table, rows) { if (!rows.length) { console.log(` ${table}: 0 rows`); @@ -182,20 +178,23 @@ async function main() { } } - console.log('\n🗑️ Clearing SQLite tables (child → parent order)…'); - await sqlite.transaction(async (transaction) => { - await sqlite.query('PRAGMA foreign_keys = OFF', { transaction }); + // SQLite enforces FKs on INSERT. `users.created_by` → `users.id` must not depend on row + // order from Postgres; same for optional refs. Turn FKs off for the whole clear+copy, then on. + console.log('\n🗑️ Clearing SQLite tables…'); + await sqlite.query('PRAGMA foreign_keys = OFF'); + try { for (const table of TABLES_DELETE_REVERSE) { - await sqlite.query(`DELETE FROM "${table}"`, { type: QueryTypes.DELETE, transaction }); + await sqlite.query(`DELETE FROM "${table}"`, { type: QueryTypes.DELETE }); } - await sqlite.query('PRAGMA foreign_keys = ON', { transaction }); - }); - console.log(' Done.\n'); + console.log(' Done.\n'); - console.log('📥 Copying from PostgreSQL → SQLite…\n'); - for (const table of TABLES_ORDER) { - const rows = await fetchPostgresTable(pg, table); - await insertRows(sqlite, table, rows); + console.log('📥 Copying from PostgreSQL → SQLite…\n'); + for (const table of TABLES_ORDER) { + const rows = await fetchPostgresTable(pg, table); + await insertRows(sqlite, table, rows); + } + } finally { + await sqlite.query('PRAGMA foreign_keys = ON'); } await pg.close();