import { readFileSync } from 'node:fs'; import path from 'node:path'; import { describe, expect, it } from 'vitest'; import { buildWhere } from '../src/services/queryExecutor'; /** * M2:网关未知过滤操作符**不得静默丢弃条件**(2026-09-24 修)。 * * 原行为:`switch (filter.op)` 的 `default: break;` → 不认识的操作符被整体丢掉, * 该条件不产生任何 SQL,查询从"按条件查"退化成"不过滤",返回更大范围的数据, * 而且**不报错**(前端以为加了条件,实际看到的是范围错的数据)。 * 修后:未知 op 抛 `bad_request`,由 `routes/data.ts` 映射成 HTTP 400。 * * 落地前预检(全仓 `op: '...'` 取值集合):调用方只用到 * `eq / in / neq / is / or / lte / lt / ilike / gte / gt / expr`,全部受支持 → * 对现有功能无影响(本测试同时把这些 op 逐个跑通,防未来改名单向漂移)。 */ const SRC = (rel: string) => readFileSync(path.join(__dirname, '..', rel), 'utf8'); describe('M2 网关过滤操作符', () => { it('未知 op 必须报 bad_request(旧行为是静默丢弃条件)', () => { expect(() => buildWhere('t', [{ column: 'status', op: 'contains' as never, value: 1 }]) ).toThrowError(/不支持的过滤操作符/); try { buildWhere('t', [{ column: 'created_at', op: 'between' as never, value: [1, 2] }]); throw new Error('应当抛错但没有'); } catch (error: any) { expect(error.code).toBe('bad_request'); expect(String(error.message)).toContain('between'); } }); it('全部受支持 op 仍照常生成条件(现有调用方只用到这些)', () => { const binary: Array<[string, string]> = [ ['eq', '= $1'], ['neq', '<> $1'], ['gt', '> $1'], ['gte', '>= $1'], ['lt', '< $1'], ['lte', '<= $1'], ['in', '= ANY($1)'], ['ilike', 'ILIKE $1'], ]; for (const [op, fragment] of binary) { const { whereSql, params } = buildWhere('t', [ { column: 'c', op: op as never, value: op === 'in' ? [1] : 1 }, ]); expect(whereSql, `op=${op}`).toContain(fragment); expect(params.length).toBe(1); } expect(buildWhere('t', [{ column: 'c', op: 'is' as never, value: null }]).whereSql).toContain( 'IS NULL' ); expect( buildWhere('t', [{ column: 'c', op: 'empty_or_null' as never }]).whereSql ).toContain('BTRIM'); // 无 filter 时不生成 WHERE(不能因本次改动变成恒假/恒真) expect(buildWhere('t', []).whereSql).toBe(''); }); it('契约:不得回退成静默 break', () => { const src = SRC('src/services/queryExecutor.ts'); expect(src).toContain('不支持的过滤操作符'); expect(src).not.toContain(' default:\n break;\n }'); }); });