Files
SupplierSystem/server/scripts/verify-tenant-schema.mjs
T
Ubuntu deb3e72750
CI / server typecheck + tests (push) Canceled after 0s
CI / web typecheck + tests + miniprogram syntax (push) Canceled after 0s
CI / eslint (观察项,C7 骨架) (push) Canceled after 0s
CI / npm audit (critical 硬拦) (push) Canceled after 0s
chore: 以 AI 生鲜配送系统 当前版本作为 SupplierSystem 起点
来源仓库:jxc/ai-fresh-delivery
来源提交:f0b1a180e2deb7e4673b9d1c8542619f7bc0f73d
快照树:  09f679334ff38f0ff25e907961c94a8223bcaedd(与来源 HEAD 工作树逐字节一致,3801 个文件)

按约定本仓库不带任何历史提交:来源仓库的历史中含真实凭据
(生产 SSH 私钥 deploy/id_rsa_tencent、server/.env、.env.tencent/.env.production/.env.gitea、
deploy/小程序AppSecret.txt,其中 MP_APPSECRET / S3 AccessKey 经哈希比对与线上同值),
整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。
供应商系统后续开发自本提交开始。
2026-10-08 17:35:43 +08:00

184 lines
7.2 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 校验 Schema 分租:template / registry / search_path 不串读;列数与 template 抽样一致
// 运行前需已注入 DATABASE_URL(勿依赖 dotenv,生产 omit=dev)
import pg from 'pg';
const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });
function assert(cond, msg) {
if (!cond) throw new Error(msg);
}
const COLUMN_SAMPLE = ['orders', 'order_items', 'product_catalog', 'order_item_fulfillments'];
const allowNotValid = process.argv.includes('--allow-not-valid');
const CORE_FKS = [
{ child: 'order_items', childColumn: 'order_code', parent: 'orders', parentColumn: 'order_code' },
{ child: 'order_item_fulfillments', childColumn: 'order_item_id', parent: 'order_items', parentColumn: 'id' },
{ child: 'picking_items', childColumn: 'pick_code', parent: 'picking_tasks', parentColumn: 'pick_code' },
];
const client = await pool.connect();
try {
const template = await client.query(
`SELECT COUNT(*)::int AS n FROM information_schema.tables
WHERE table_schema = 'tenant_template'`
);
console.log(`tenant_template tables: ${template.rows[0].n}`);
assert(Number(template.rows[0].n) > 10, 'tenant_template should contain business tables');
const registry = await client.query(
`SELECT branch_code, schema_name, status FROM public.tenant_schema_registry ORDER BY branch_code`
);
console.log('registry rows:', registry.rowCount);
assert((registry.rowCount || 0) > 0, 'tenant_schema_registry should list branches');
const pending = registry.rows.filter((r) => r.status === 'pending');
console.log(`pending schemas: ${pending.length}`);
if (registry.rows.length >= 2) {
const a = registry.rows[0];
const b = registry.rows[1];
await client.query('BEGIN');
await client.query(`SELECT set_config('search_path', $1, true)`, [`${a.schema_name}, public`]);
const countA = await client.query(`SELECT COUNT(*)::int AS n FROM product_catalog`);
await client.query(`SELECT set_config('search_path', $1, true)`, [`${b.schema_name}, public`]);
const countB = await client.query(`SELECT COUNT(*)::int AS n FROM product_catalog`);
await client.query('ROLLBACK');
console.log(
`${a.schema_name}.product_catalog=${countA.rows[0].n}; ${b.schema_name}.product_catalog=${countB.rows[0].n}`
);
// 阶段 5 后 public 无业务表;若误落到 public 会 relation does not exist 或 0
const publicExists = await client.query(
`SELECT to_regclass('public.product_catalog') IS NOT NULL AS ok`
);
if (publicExists.rows[0].ok) {
const publicCount = await client.query(
`SELECT COUNT(*)::int AS n FROM public.product_catalog WHERE item_type = 'category'`
);
console.log(`public.product_catalog categories=${publicCount.rows[0].n}`);
if (
Number(countA.rows[0].n) === Number(publicCount.rows[0].n) &&
Number(publicCount.rows[0].n) > 0
) {
throw new Error('search_path appears to resolve product_catalog to public (leak)');
}
} else {
console.log('public.product_catalog absent (expected after legacy archive)');
}
}
// 列级漂移:各 tenant 与 template 同表列数一致
for (const row of registry.rows) {
for (const table of COLUMN_SAMPLE) {
const tpl = await client.query(
`SELECT count(*)::int AS n FROM information_schema.columns
WHERE table_schema='tenant_template' AND table_name=$1`,
[table]
);
if (!Number(tpl.rows[0].n)) continue;
const ten = await client.query(
`SELECT count(*)::int AS n FROM information_schema.columns
WHERE table_schema=$1 AND table_name=$2`,
[row.schema_name, table]
);
assert(
Number(ten.rows[0].n) === Number(tpl.rows[0].n),
`${row.schema_name}.${table} cols=${ten.rows[0].n} template=${tpl.rows[0].n}`
);
}
console.log(`OK columns ${row.branch_code} → ${row.schema_name}`);
}
const tenantSchemas = [
'tenant_template',
...registry.rows
.filter((row) => row.status === 'active' || row.status === 'pending')
.map((row) => String(row.schema_name)),
];
const fkResult = await client.query(`
SELECT
con.conname,
src_ns.nspname AS source_schema,
src.relname AS child_table,
dst_ns.nspname AS target_schema,
dst.relname AS parent_table,
con.convalidated,
ARRAY(
SELECT a.attname
FROM unnest(con.conkey) WITH ORDINALITY AS k(attnum, ord)
JOIN pg_attribute a ON a.attrelid = con.conrelid AND a.attnum = k.attnum
ORDER BY k.ord
) AS child_columns,
ARRAY(
SELECT a.attname
FROM unnest(con.confkey) WITH ORDINALITY AS k(attnum, ord)
JOIN pg_attribute a ON a.attrelid = con.confrelid AND a.attnum = k.attnum
ORDER BY k.ord
) AS parent_columns
FROM pg_constraint con
JOIN pg_class src ON src.oid = con.conrelid
JOIN pg_namespace src_ns ON src_ns.oid = src.relnamespace
JOIN pg_class dst ON dst.oid = con.confrelid
JOIN pg_namespace dst_ns ON dst_ns.oid = dst.relnamespace
WHERE con.contype = 'f'
AND src_ns.nspname = ANY($1::text[])
`, [tenantSchemas]);
for (const schema of tenantSchemas) {
for (const expected of CORE_FKS) {
const match = fkResult.rows.find(
(fk) =>
fk.source_schema === schema &&
fk.target_schema === schema &&
fk.child_table === expected.child &&
fk.parent_table === expected.parent &&
fk.child_columns?.join(',') === expected.childColumn &&
fk.parent_columns?.join(',') === expected.parentColumn
);
assert(
match,
`${schema} missing core FK ${expected.child}.${expected.childColumn} → ${expected.parent}.${expected.parentColumn}`
);
if (!allowNotValid) {
assert(match.convalidated === true, `${schema}.${match.conname} is NOT VALID`);
}
}
console.log(`OK core FKs ${schema}${allowNotValid ? ' (NOT VALID allowed)' : ''}`);
}
const crossSchemaFks = fkResult.rows.filter((fk) => fk.target_schema !== fk.source_schema);
assert(
crossSchemaFks.length === 0,
`tenant cross-schema FK found: ${crossSchemaFks
.map((fk) => `${fk.source_schema}.${fk.child_table}→${fk.target_schema}.${fk.parent_table}`)
.join(', ')}`
);
console.log('OK no tenant→public/legacy/other-tenant business FKs');
// 不应再有 public → legacy_public 业务 FK
const badFk = await client.query(`
SELECT n1.nspname||'.'||c1.relname AS src, con.conname
FROM pg_constraint con
JOIN pg_class c1 ON c1.oid = con.conrelid
JOIN pg_namespace n1 ON n1.oid = c1.relnamespace
JOIN pg_class c2 ON c2.oid = con.confrelid
JOIN pg_namespace n2 ON n2.oid = c2.relnamespace
WHERE con.contype = 'f'
AND n1.nspname = 'public'
AND n2.nspname = 'legacy_public'
`);
assert(
(badFk.rowCount || 0) === 0,
`public→legacy_public FK still present: ${badFk.rows.map((r) => r.src).join(',')}`
);
console.log('OK no public→legacy_public FKs');
const nameFn = await client.query(`SELECT public.tenant_schema_name('BR002') AS s`);
assert(nameFn.rows[0].s === 'tenant_br002', 'tenant_schema_name(BR002) should be tenant_br002');
console.log('verify-tenant-schema: OK');
} finally {
client.release();
await pool.end();
}