/** * 清空本地开发库业务数据(保留 schema_migrations / 表结构)。 * 仅允许连接 localhost / 127.0.0.1。 * * node --env-file=.env scripts/clear-dev-db.mjs # dry-run * node --env-file=.env scripts/clear-dev-db.mjs --execute */ import pg from 'pg'; const execute = process.argv.includes('--execute'); function assertLocalUrl(url) { let parsed; try { parsed = new URL(url); } catch { throw new Error('DATABASE_URL 无效'); } const host = (parsed.hostname || '').toLowerCase(); if (!['localhost', '127.0.0.1', '::1'].includes(host)) { throw new Error(`拒绝执行:DATABASE_URL 主机为 ${host},仅允许本地开发库`); } return parsed; } async function listSchemas(client) { const { rows } = await client.query(` SELECT nspname FROM pg_namespace WHERE nspname = 'public' OR nspname = 'tenant_template' OR nspname LIKE 'tenant_%' ORDER BY nspname `); return rows.map((r) => r.nspname); } async function listTables(client, schema) { const { rows } = await client.query( ` SELECT tablename FROM pg_tables WHERE schemaname = $1 AND tablename NOT IN ('schema_migrations', 'spatial_ref_sys') ORDER BY tablename `, [schema] ); return rows.map((r) => r.tablename); } async function main() { const url = process.env.DATABASE_URL; if (!url) throw new Error('缺少 DATABASE_URL'); const parsed = assertLocalUrl(url); console.log(`目标库: ${parsed.hostname}:${parsed.port || 5432}${parsed.pathname}`); console.log(execute ? '模式: EXECUTE(将清空数据)' : '模式: dry-run(加 --execute 才真正清空)'); const client = new pg.Client({ connectionString: url }); await client.connect(); try { const schemas = await listSchemas(client); let totalTables = 0; for (const schema of schemas) { const tables = await listTables(client, schema); totalTables += tables.length; console.log(` schema ${schema}: ${tables.length} 张表`); } if (!execute) { console.log(`将 TRUNCATE CASCADE 约 ${totalTables} 张表(跳过 schema_migrations)。未执行。`); return; } await client.query('BEGIN'); for (const schema of schemas) { const tables = await listTables(client, schema); if (!tables.length) continue; const fq = tables.map((t) => `"${schema}"."${t}"`).join(', '); console.log(`清空 ${schema} (${tables.length})...`); await client.query(`TRUNCATE TABLE ${fq} RESTART IDENTITY CASCADE`); } await client.query('COMMIT'); console.log('业务数据已清空。建议接着执行: npm run db:migrate && npm run seed:dev-passwords'); } catch (error) { try { await client.query('ROLLBACK'); } catch { /* ignore */ } throw error; } finally { await client.end(); } } main().catch((error) => { console.error(error.message || error); process.exit(1); });