来源仓库: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 经哈希比对与线上同值), 整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。 供应商系统后续开发自本提交开始。
190 lines
7.4 KiB
TypeScript
190 lines
7.4 KiB
TypeScript
/**
|
||
* 审计:找出**同一张表上键相同的多个唯一索引**(唯一约束被重复/遮蔽的隐患)。
|
||
*
|
||
* 为什么需要它:2026-09-22 出过一次真实事故 ——
|
||
* `cost_details` 上 (order_code, sku_code, COALESCE(cost_source,'')) 存在两条唯一索引,
|
||
* 一条带 `order_item_id IS NULL` 谓词、一条不带;而删旧索引的迁移**按名字删**且名字写错,
|
||
* DROP INDEX IF EXISTS 静默跳过,遗留的那条把「同单同 SKU 新明细行」的成本写入挡死 → 保存 500。
|
||
* 见 migrations/20260922_drop_legacy_cost_details_sku_uq.sql
|
||
*
|
||
* 判定是**按定义**做的(与索引名无关,故不受改名影响):
|
||
* 1. 按 (schema, 表, 规范化后的键表达式) 分组;组内 ≥2 条唯一索引即为「重复键」;
|
||
* 2. 若这组里存在**谓词不同**且**一条谓词蕴含另一条**(子集关系)→ 高风险(会互相遮蔽);
|
||
* 谓词完全相同 → 记为冗余(浪费写入,但不会遮蔽)。
|
||
*
|
||
* 用法(只读;本地或只读快照库):
|
||
* npm run audit:unique-indexes
|
||
* 退出码:发现高风险 → 1;否则 0(可直接用作发布前闸门)。
|
||
*/
|
||
import pg from 'pg';
|
||
|
||
const { Pool } = pg;
|
||
|
||
/** 去掉类型转换/多余空白,便于同名键比较 */
|
||
function normExpr(expr: string): string {
|
||
return String(expr)
|
||
.replace(/::(character varying|text|numeric|integer|bigint|uuid)/gi, '')
|
||
.replace(/\s+/g, ' ')
|
||
.trim()
|
||
.toLowerCase();
|
||
}
|
||
|
||
/** 谓词拆成 AND 项集合(粗粒度即可用于"蕴含"判断) */
|
||
function predTerms(pred: string | null): Set<string> {
|
||
if (!pred || pred === '(无)') return new Set(['<none>']);
|
||
return new Set(
|
||
String(pred)
|
||
.replace(/::(character varying|text|numeric|integer|bigint|uuid)/gi, '')
|
||
.replace(/[()]/g, '')
|
||
.split(/\s+and\s+/i)
|
||
.map((s) => s.replace(/\s+/g, ' ').trim().toLowerCase())
|
||
.filter(Boolean)
|
||
);
|
||
}
|
||
|
||
const isSubset = (a: Set<string>, b: Set<string>) => [...a].every((x) => b.has(x));
|
||
|
||
/** 取谓词里的 `列 = '字面量'` 等式约束;同一列出现互不相同的字面量 ⇒ 两个谓词互斥 */
|
||
function equalityLiterals(terms: Set<string>): Map<string, Set<string>> {
|
||
const out = new Map<string, Set<string>>();
|
||
for (const t of terms) {
|
||
const m = /^([a-z_][a-z0-9_.]*)\s*=\s*'([^']*)'$/.exec(t);
|
||
if (!m) continue;
|
||
const col = m[1];
|
||
if (!out.has(col)) out.set(col, new Set());
|
||
out.get(col)!.add(m[2]);
|
||
}
|
||
return out;
|
||
}
|
||
|
||
/** 两个谓词是否互斥(存在同列不同字面量的等式约束) */
|
||
function isDisjoint(a: Set<string>, b: Set<string>): boolean {
|
||
const la = equalityLiterals(a);
|
||
const lb = equalityLiterals(b);
|
||
for (const [col, va] of la) {
|
||
const vb = lb.get(col);
|
||
if (!vb) continue;
|
||
if ([...va].every((x) => !vb.has(x))) return true;
|
||
}
|
||
return false;
|
||
}
|
||
|
||
type Row = {
|
||
sch: string;
|
||
tbl: string;
|
||
idx: string;
|
||
pred: string | null;
|
||
keys: string[];
|
||
};
|
||
|
||
(async () => {
|
||
const url = String(process.env.DATABASE_URL || '');
|
||
if (!url) throw new Error('缺少 DATABASE_URL(用 npm run audit:unique-indexes 会带 --env-file=.env)');
|
||
const pool = new Pool({ connectionString: url, max: 2 });
|
||
try {
|
||
const schemas = (
|
||
await pool.query(
|
||
`SELECT nspname FROM pg_namespace
|
||
WHERE nspname IN ('public', 'legacy_public', 'tenant_template') OR nspname LIKE 'tenant\\_%'
|
||
ORDER BY 1`
|
||
)
|
||
).rows.map((r) => String(r.nspname));
|
||
|
||
const rows = (
|
||
await pool.query(
|
||
`SELECT n.nspname AS sch, t.relname AS tbl, i.relname AS idx,
|
||
pg_get_expr(x.indpred, x.indrelid) AS pred,
|
||
(SELECT array_agg(pg_get_indexdef(x.indexrelid, k, true) ORDER BY k)
|
||
FROM generate_series(1, x.indnkeyatts) k) AS keys
|
||
FROM pg_index x
|
||
JOIN pg_class t ON t.oid = x.indrelid
|
||
JOIN pg_namespace n ON n.oid = t.relnamespace
|
||
JOIN pg_class i ON i.oid = x.indexrelid
|
||
WHERE x.indisunique AND t.relkind = 'r' AND n.nspname = ANY($1::text[])`,
|
||
[schemas]
|
||
)
|
||
).rows as Row[];
|
||
|
||
const groups = new Map<string, Row[]>();
|
||
for (const r of rows) {
|
||
const key = `${r.sch}|${r.tbl}|${r.keys.map(normExpr).join(' , ')}`;
|
||
if (!groups.has(key)) groups.set(key, []);
|
||
groups.get(key)!.push(r);
|
||
}
|
||
|
||
let highRisk = 0;
|
||
let redundant = 0;
|
||
let disjoint = 0;
|
||
for (const [key, list] of groups) {
|
||
if (list.length < 2) continue;
|
||
const [sch, tbl] = key.split('|');
|
||
const preds = list.map((r) => predTerms(r.pred));
|
||
const identical = preds.every((p) => isSubset(p, preds[0]) && isSubset(preds[0], p));
|
||
const allDisjoint = preds.every((a, i) => preds.every((b, j) => i === j || isDisjoint(a, b)));
|
||
const shadowing =
|
||
!identical &&
|
||
!allDisjoint &&
|
||
preds.some((a, i) => preds.some((b, j) => i !== j && isSubset(a, b) && !isSubset(b, a)));
|
||
if (shadowing) highRisk += 1;
|
||
else if (allDisjoint) disjoint += 1;
|
||
else redundant += 1;
|
||
const level = shadowing
|
||
? '高风险(会互相遮蔽)'
|
||
: allDisjoint
|
||
? '互斥(不冲突)'
|
||
: identical
|
||
? '冗余(谓词相同)'
|
||
: '需人工判定';
|
||
console.log(`[${level}] ${sch}.${tbl} 键=(${list[0].keys.map(normExpr).join(', ')})`);
|
||
for (const r of list) console.log(` - ${r.idx} | 谓词: ${r.pred || '(无)'}`);
|
||
}
|
||
|
||
console.log(
|
||
`\n结果:重复键组 ${highRisk + redundant + disjoint} 个 —— 高风险 ${highRisk},冗余/待判 ${redundant},互斥 ${disjoint},涉及 schema ${schemas.length} 个`
|
||
);
|
||
|
||
// 补充:键互为前缀的唯一索引(更老形态的遗留索引,例如 (order_code, sku_code) 与
|
||
// (order_code, sku_code, cost_source) 并存)。只作提示,不判失败。
|
||
const byTable = new Map<string, Row[]>();
|
||
for (const r of rows) {
|
||
const k = `${r.sch}|${r.tbl}`;
|
||
if (!byTable.has(k)) byTable.set(k, []);
|
||
byTable.get(k)!.push(r);
|
||
}
|
||
let prefixPairs = 0;
|
||
for (const [k, list] of byTable) {
|
||
for (let i = 0; i < list.length; i += 1) {
|
||
for (let j = i + 1; j < list.length; j += 1) {
|
||
const ka = list[i].keys.map(normExpr);
|
||
const kb = list[j].keys.map(normExpr);
|
||
const [short, long] = ka.length <= kb.length ? [ka, kb] : [kb, ka];
|
||
if (short.length === long.length) continue; // 等长已在上面的分组里处理
|
||
if (!short.every((x, idx) => long[idx] === x)) continue;
|
||
const [pa, pb] = [predTerms(list[i].pred), predTerms(list[j].pred)];
|
||
if (isDisjoint(pa, pb)) continue;
|
||
prefixPairs += 1;
|
||
const [sch, tbl] = k.split('|');
|
||
console.log(
|
||
`[提示:键前缀重叠] ${sch}.${tbl} ${list[i].idx}(${ka.join(', ')}) 与 ${list[j].idx}(${kb.join(', ')})`
|
||
);
|
||
}
|
||
}
|
||
}
|
||
console.log(`键前缀重叠组:${prefixPairs}(提示级,多为既有设计;若有"遗留旧键"需人工确认)`);
|
||
if (highRisk) {
|
||
console.log('⚠ 高风险组会让其中一条唯一约束被另一条遮蔽(写入路径可能意外报 23505),必须处理。');
|
||
process.exitCode = 1;
|
||
} else {
|
||
console.log('✔ 未发现互相遮蔽的唯一索引。');
|
||
}
|
||
} finally {
|
||
await pool.end();
|
||
}
|
||
})().then(
|
||
() => process.exit(process.exitCode || 0),
|
||
(e) => {
|
||
console.error('FATAL', (e as Error).message);
|
||
process.exit(1);
|
||
}
|
||
);
|