import { readFileSync } from 'node:fs'; import { describe, expect, it } from 'vitest'; import { existsFormalPurchaseForSkuSql, existsOrderGoodsForSkuSql, purchaseCostBucketExpr, } from '../src/services/purchaseCostBucketSql'; /** * 成本 KPI / 成本销售预警 自连接的性能回归钉子(2026-09-22)。 * * 事故:`purchaseCostBucketSql` 的三个自连接谓词用 * `o.order_code IS NOT DISTINCT FROM cd.order_code` * 比较**两列** —— Postgres 无法用索引 → `cost_details` 被全表扫 2 万次 * (EXPLAIN: Nested Loop Semi Join, Rows Removed by Join Filter = 47,226,650)。 * 实测:成本/销售预警单客户 22.1s、全客户 48.7s;财务概览 5.2s、采购成本账本 3.8s。 * * 修复:改成 NULL 安全但可索引的等价写法 + 非唯一部分索引 * `cost_details(order_code, sku_code) WHERE cost_type='purchase'`。 * 改后:预警单客户 1.0s / 全客户 1.5s;财务概览 0.22s;账本 0.08s,**输出逐字节一致**。 * * 见 docs/design/20260922-kpi-cost-self-join-index-usable.md */ const read = (rel: string) => readFileSync(new URL(`../../${rel}`, import.meta.url), 'utf8'); const NULL_SAFE_ORDER_CODE = "((o.order_code = cd.order_code) OR (cd.order_code IS NULL AND o.order_code IS NULL))"; describe('成本 KPI 自连接:可索引且 NULL 安全', () => { it('三个谓词的 order_code 用 NULL 安全等值(不是两列 IS NOT DISTINCT FROM)', () => { expect(existsFormalPurchaseForSkuSql('cd')).toContain(NULL_SAFE_ORDER_CODE); expect(existsOrderGoodsForSkuSql('cd')).toContain( "((g.order_code = cd.order_code) OR (cd.order_code IS NULL AND g.order_code IS NULL))" ); expect(purchaseCostBucketExpr('cd')).toContain( "((po.order_code = cd.order_code) OR (cd.order_code IS NULL AND po.order_code IS NULL))" ); }); it('回归钉子:不得再出现「两列 IS NOT DISTINCT FROM」的 order_code 比较', () => { const src = read('server/src/services/purchaseCostBucketSql.ts'); // 允许注释里提到该写法(说明为什么禁用),但不得出现在可执行 SQL 里 const executable = src .split('\n') .filter((line) => !line.trim().startsWith('*') && !line.trim().startsWith('//') && !line.trim().startsWith('/*')) .join('\n'); expect(executable).not.toMatch(/order_code IS NOT DISTINCT FROM/); // sku_code 仍保持原语义(改动不影响性能,故不动) expect(executable).toMatch(/sku_code IS NOT DISTINCT FROM/); }); it('迁移必须建**非唯一**部分索引(不表达任何唯一约束)', () => { const mig = read('migrations/20260922_cost_details_order_sku_kpi_index.sql'); expect(mig).toContain('idx_cost_details_order_sku_purchase'); expect(mig).toContain('(order_code, sku_code)'); expect(mig).toContain("WHERE cost_type = ''purchase''"); expect(mig).not.toMatch(/CREATE\s+UNIQUE\s+INDEX/i); }); });