#!/usr/bin/env node // 全租户只读引用完整性巡检。只输出计数和少量标识,不修复数据。 import pg from 'pg'; const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL }); const SAMPLE_LIMIT = 5; const VALID_SCHEMA = /^tenant_[a-z0-9_-]{2,30}$/; const checks = [ { name: 'order_items.order', child: 'order_items', childColumn: 'order_code', parent: 'orders', parentColumn: 'order_code', sample: 'order_code' }, { name: 'order_item_fulfillments.item', child: 'order_item_fulfillments', childColumn: 'order_item_id', parent: 'order_items', parentColumn: 'id', sample: 'order_item_id' }, { name: 'picking_items.task', child: 'picking_items', childColumn: 'pick_code', parent: 'picking_tasks', parentColumn: 'pick_code', sample: 'pick_code' }, { name: 'purchase_orders.order', child: 'purchase_orders', childColumn: 'order_code', parent: 'orders', parentColumn: 'order_code', sample: 'order_code' }, { name: 'supplier_preparations.order', child: 'supplier_preparations', childColumn: 'order_code', parent: 'orders', parentColumn: 'order_code', sample: 'order_code' }, { name: 'inspections.order', child: 'inspections', childColumn: 'order_code', parent: 'orders', parentColumn: 'order_code', sample: 'order_code' }, { name: 'processing_tasks.order', child: 'processing_tasks', childColumn: 'order_code', parent: 'orders', parentColumn: 'order_code', sample: 'order_code' }, { name: 'delivery_tasks.order', child: 'delivery_tasks', childColumn: 'order_code', parent: 'orders', parentColumn: 'order_code', sample: 'order_code' }, { name: 'cost_adjustments.cost_detail', child: 'cost_adjustments', childColumn: 'cost_detail_id', parent: 'cost_details', parentColumn: 'id', sample: 'cost_detail_id' }, ]; function quoteIdent(value) { return `"${String(value).replaceAll('"', '""')}"`; } async function relationExists(client, schema, table) { const result = await client.query(`SELECT to_regclass($1) IS NOT NULL AS ok`, [`${schema}.${table}`]); return result.rows[0]?.ok === true; } async function columnExists(client, schema, table, column) { const result = await client.query( `SELECT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = $1 AND table_name = $2 AND column_name = $3 ) AS ok`, [schema, table, column] ); return result.rows[0]?.ok === true; } async function auditCheck(client, schema, check) { const required = [ [check.child, check.childColumn], [check.child, check.sample], [check.parent, check.parentColumn], ]; for (const [table, column] of required) { if (!(await relationExists(client, schema, table)) || !(await columnExists(client, schema, table, column))) { return { check: check.name, status: 'skipped', count: 0, samples: [], reason: `missing ${table}.${column}` }; } } const s = quoteIdent(schema); const child = quoteIdent(check.child); const parent = quoteIdent(check.parent); const childColumn = quoteIdent(check.childColumn); const parentColumn = quoteIdent(check.parentColumn); const sampleColumn = quoteIdent(check.sample); const predicate = `c.${childColumn} IS NOT NULL AND NOT EXISTS ( SELECT 1 FROM ${s}.${parent} p WHERE p.${parentColumn} = c.${childColumn} )`; const countResult = await client.query( `SELECT COUNT(*)::int AS count FROM ${s}.${child} c WHERE ${predicate}` ); const sampleResult = await client.query( `SELECT c.${sampleColumn}::text AS value FROM ${s}.${child} c WHERE ${predicate} ORDER BY c.${sampleColumn}::text LIMIT $1`, [SAMPLE_LIMIT] ); return { check: check.name, status: 'checked', count: Number(countResult.rows[0]?.count) || 0, samples: sampleResult.rows.map((row) => String(row.value)), }; } const client = await pool.connect(); let report; try { await client.query('BEGIN READ ONLY'); const registry = await client.query( `SELECT branch_code, schema_name, status FROM public.tenant_schema_registry WHERE status IN ('active', 'pending') ORDER BY branch_code` ); const schemas = [ { branchCode: null, schema: 'tenant_template', status: 'template' }, ...registry.rows .filter((row) => VALID_SCHEMA.test(String(row.schema_name || ''))) .map((row) => ({ branchCode: String(row.branch_code || ''), schema: String(row.schema_name), status: String(row.status), })), ]; const schemaReports = []; for (const target of schemas) { const exists = await client.query( `SELECT EXISTS (SELECT 1 FROM pg_namespace WHERE nspname = $1) AS ok`, [target.schema] ); if (exists.rows[0]?.ok !== true) { schemaReports.push({ ...target, status: target.status, error: 'schema_missing', checks: [] }); continue; } const results = []; for (const check of checks) { results.push(await auditCheck(client, target.schema, check)); } schemaReports.push({ ...target, checks: results }); } const violations = schemaReports.reduce( (sum, item) => sum + item.checks.reduce((n, check) => n + Number(check.count || 0), 0), 0 ); const missingSchemas = schemaReports.filter((item) => item.error).length; report = { generatedAt: new Date().toISOString(), readOnly: true, schemaCount: schemaReports.length, violations, missingSchemas, schemas: schemaReports, }; await client.query('ROLLBACK'); } catch (error) { await client.query('ROLLBACK').catch(() => undefined); throw error; } finally { client.release(); await pool.end(); } for (const item of report.schemas) { const violations = item.checks.reduce((sum, check) => sum + Number(check.count || 0), 0); console.log(`${item.schema} [${item.status}]: ${item.error || `${violations} violation(s)`}`); for (const check of item.checks.filter((entry) => entry.count > 0 || entry.status === 'skipped')) { console.log(` ${check.check}: ${check.status === 'skipped' ? check.reason : `${check.count} [${check.samples.join(', ')}]`}`); } } console.log(JSON.stringify(report, null, 2)); process.exitCode = report.violations > 0 || report.missingSchemas > 0 ? 1 : 0;