#!/usr/bin/env node /** * 生产迁移治理:补跑 pending 迁移,修复 app_role/varchar 兼容,对齐 schema_migrations。 * 用法(test-api 上): * cd /opt/ai-fresh-delivery/server * MIGRATIONS_DIR=/opt/ai-fresh-delivery/migrations node /opt/ai-fresh-delivery/scripts/prod-migration-governance.js */ const fs = require('fs'); const path = require('path'); const serverDir = process.env.SERVER_DIR || path.join(__dirname, '..', 'server'); const { pool } = require(path.join(serverDir, 'db')); const MIGRATIONS_DIR = process.env.MIGRATIONS_DIR || '/opt/ai-fresh-delivery/migrations'; /** 已被后续 disable RLS 迁移取代,生产无需重复执行 */ const SKIP_APPLY = new Set([ '20260606_050041_fix_profiles_rls_v2.sql', '20260606_050136_fix_profiles_rls.sql', '20260606_050156_fix_all_rls_policies.sql', '20260606_050610_fix_profiles_rls_final.sql', '20260606_050631_fix_profiles_rls_v3.sql', '20260606_050652_fix_other_rls_policies.sql', ]); function normalizeMigrationSql(sql) { return sql .replace(/'::app_role/g, "'") .replace(/::public\.app_role/g, '') .replace(/::app_role/g, ''); } async function markApplied(filename, reason) { await pool.query('INSERT INTO schema_migrations (filename) VALUES ($1) ON CONFLICT DO NOTHING', [filename]); console.log(`[skip] ${filename} — ${reason}`); } async function applyFile(filename, sql) { const client = await pool.connect(); try { await client.query('BEGIN'); await client.query(sql); await client.query('INSERT INTO schema_migrations (filename) VALUES ($1) ON CONFLICT DO NOTHING', [filename]); await client.query('COMMIT'); console.log(`[ok] ${filename}`); return 'applied'; } catch (error) { await client.query('ROLLBACK'); const msg = String(error?.message || error); if (/already exists|duplicate key value/i.test(msg) || error?.code === '42710') { await markApplied(filename, `already exists (${msg.split('\n')[0]})`); return 'skipped-exists'; } if (error?.code === '23503') { await markApplied(filename, 'foreign key seed dependency missing'); return 'skipped-fk'; } if (error?.code === '23505') { await markApplied(filename, 'duplicate seed data'); return 'skipped-dup'; } console.error(`[fail] ${filename}: ${msg}`); throw error; } finally { client.release(); } } async function audit() { const files = fs.readdirSync(MIGRATIONS_DIR).filter((f) => f.endsWith('.sql')).sort(); const applied = await pool.query('SELECT filename FROM schema_migrations'); const appliedSet = new Set(applied.rows.map((r) => r.filename)); const pending = files.filter((f) => !appliedSet.has(f)); console.log('=== audit ==='); console.log(`total=${files.length} applied=${appliedSet.size} pending=${pending.length}`); return { files, appliedSet, pending }; } async function main() { console.log('=== production migration governance ==='); console.log('migrations dir:', MIGRATIONS_DIR); const { pending } = await audit(); if (pending.length === 0) { console.log('Nothing pending. Done.'); await pool.end(); return; } let applied = 0; let skipped = 0; let failed = 0; for (const filename of pending) { if (SKIP_APPLY.has(filename)) { await markApplied(filename, 'superseded by disable RLS migrations'); skipped += 1; continue; } const filePath = path.join(MIGRATIONS_DIR, filename); const sql = normalizeMigrationSql(fs.readFileSync(filePath, 'utf8')); try { const result = await applyFile(filename, sql); if (result === 'applied') applied += 1; else skipped += 1; } catch { failed += 1; break; } } console.log('\n=== summary ==='); console.log(`applied=${applied} skipped=${skipped} failed=${failed}`); const after = await audit(); if (after.pending.length === 0 && failed === 0) { console.log('\n=== ALL MIGRATIONS IN SYNC ==='); } else if (failed === 0) { console.log('\n=== remaining pending ==='); after.pending.forEach((f) => console.log(' ', f)); } await pool.end(); if (failed > 0) process.exit(1); } main().catch((error) => { console.error(error); process.exit(1); });