/** * Compare local vs production DB: schema_migrations + public tables + key grants. * Usage (from server/): npx tsx --env-file=.env scripts/compare-local-prod-db.ts * Prod snapshot file: ../tmp/prod-db-snapshot.json (written by SSH helper) */ import fs from 'fs'; import path from 'path'; import pg from 'pg'; type Snapshot = { label: string; migrations: string[]; tables: string[]; registryGrant?: string | null; registryCount?: number | null; tableCounts?: Record; }; type Snapshot = { label: string; migrations: string[]; tables: string[]; tenantSchemas?: string[]; registryRows?: string[]; registryGrant?: string | null; registryCount?: number | null; countSource?: string | null; tableCounts?: Record; }; async function snapshotLocal(): Promise { const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL }); try { const mig = await pool.query( `SELECT filename FROM schema_migrations ORDER BY filename` ); const tables = await pool.query( `SELECT tablename FROM pg_tables WHERE schemaname = 'public' ORDER BY tablename` ); const schemas = await pool.query( `SELECT nspname FROM pg_namespace WHERE nspname LIKE 'tenant_%' ORDER BY nspname` ); let registryGrant: string | null = null; let registryCount: number | null = null; let registryRows: string[] = []; try { const g = await pool.query( `SELECT COALESCE( (SELECT string_agg(privilege_type, ',' ORDER BY privilege_type) FROM information_schema.role_table_grants WHERE table_schema='public' AND table_name='tenant_schema_registry' AND grantee='canteen_app_rls'), '(no grants)' ) AS grants` ); registryGrant = g.rows[0]?.grants || null; } catch { registryGrant = '(query failed)'; } try { const c = await pool.query(`SELECT count(*)::int AS n FROM public.tenant_schema_registry`); registryCount = c.rows[0].n; const rows = await pool.query( `SELECT branch_code || ':' || schema_name || ':' || status AS row FROM public.tenant_schema_registry ORDER BY branch_code` ); registryRows = rows.rows.map((r) => r.row); } catch { registryCount = null; } const countTables = [ 'orders', 'skus', 'customers', 'categories', 'cost_details', 'branches', ]; const tableCounts: Record = {}; let countSource: string | null = null; const publicOrders = await pool.query(`SELECT to_regclass('public.orders') AS reg`); if (publicOrders.rows[0]?.reg) { countSource = 'public'; } else { const active = await pool.query( `SELECT schema_name FROM public.tenant_schema_registry WHERE status='active' ORDER BY branch_code LIMIT 1` ); countSource = active.rows[0]?.schema_name || null; } for (const t of countTables) { try { if (!countSource) { tableCounts[t] = -1; continue; } const r2 = await pool.query( `SELECT count(*)::int AS n FROM "${countSource.replace(/"/g, '')}"."${t.replace(/"/g, '')}"` ); tableCounts[t] = r2.rows[0].n; } catch { tableCounts[t] = -1; } } return { label: 'local', migrations: mig.rows.map((r) => r.filename), tables: tables.rows.map((r) => r.tablename), tenantSchemas: schemas.rows.map((r) => r.nspname), registryRows, registryGrant, registryCount, countSource, tableCounts, }; } finally { await pool.end(); } } function diffLists(a: string[], b: string[]) { const as = new Set(a); const bs = new Set(b); return { onlyA: a.filter((x) => !bs.has(x)), onlyB: b.filter((x) => !as.has(x)), }; } async function main() { const local = await snapshotLocal(); const prodPath = path.resolve(process.cwd(), '../tmp/prod-db-snapshot.json'); if (!fs.existsSync(prodPath)) { console.error('Missing prod snapshot:', prodPath); console.error('Run the SSH snapshot step first.'); process.exit(1); } const raw = fs.readFileSync(prodPath, 'utf8').replace(/^\uFEFF/, ''); const prod = JSON.parse(raw) as Snapshot; const migDiff = diffLists(local.migrations, prod.migrations); const tableDiff = diffLists(local.tables, prod.tables); console.log('=== Database comparison ==='); console.log(`Local migrations: ${local.migrations.length}`); console.log(`Prod migrations: ${prod.migrations.length}`); console.log(`Only local migrations (${migDiff.onlyA.length}):`); for (const f of migDiff.onlyA) console.log(' +', f); console.log(`Only prod migrations (${migDiff.onlyB.length}):`); for (const f of migDiff.onlyB) console.log(' -', f); console.log(''); console.log(`Local public tables: ${local.tables.length}`); console.log(`Prod public tables: ${prod.tables.length}`); console.log(`Only local tables (${tableDiff.onlyA.length}):`); for (const t of tableDiff.onlyA) console.log(' +', t); console.log(`Only prod tables (${tableDiff.onlyB.length}):`); for (const t of tableDiff.onlyB) console.log(' -', t); console.log(''); console.log('tenant schemas:'); console.log(' local:', (local.tenantSchemas || []).join(', ') || '(none)'); console.log(' prod :', (prod.tenantSchemas || []).join(', ') || '(none)'); console.log('registry rows:'); console.log(' local:', (local.registryRows || []).join(' | ') || '(none)'); console.log(' prod :', (prod.registryRows || []).join(' | ') || '(none)'); console.log(''); console.log('tenant_schema_registry:'); console.log(' local grants to canteen_app_rls:', local.registryGrant); console.log(' prod grants to canteen_app_rls:', prod.registryGrant); console.log(' local row count:', local.registryCount); console.log(' prod row count:', prod.registryCount); console.log(' local count source:', local.countSource); console.log(' prod count source:', prod.countSource); console.log(''); console.log('Row counts (public):'); const keys = new Set([ ...Object.keys(local.tableCounts || {}), ...Object.keys(prod.tableCounts || {}), ]); for (const k of [...keys].sort()) { console.log( ` ${k}: local=${local.tableCounts?.[k] ?? '?'} prod=${prod.tableCounts?.[k] ?? '?'}` ); } if (local.migrations.length) { console.log(''); console.log('Latest local migration:', local.migrations[local.migrations.length - 1]); } if (prod.migrations.length) { console.log('Latest prod migration:', prod.migrations[prod.migrations.length - 1]); } } void main();