Files
MetonaSqlark/tests/edge-coverage.test.ts
T
thzxx b20d47bd93 feat(B-3): 单管线 —— QueryBuilder 只产出 AST,执行一律经 Executor
背景(PLAN-v0.7.5.md 根因 2/4):
三个 builder 的 execute() 各自执行写入/查询,与 SQL 路径构成**两条管线**:
  - SelectQueryBuilder:无 JOIN 时直接调 engine.find(只有 JOIN 才走 executor)
  - UpdateQueryBuilder / DeleteQueryBuilder:直接调 engine.update/delete

于是同一条语义在两条路径上规则各写一份,实测差异:
  - `db.table('t').select(['t.n'])` 行键保留 `t.n`,SQL 路径归一化为 `n`
  - `select(['nope'])` 静默产出 `[{},{},{}]`(引擎不校验列存在性)
  - 不受 maxRowsPerQuery 约束
  - UPDATE/DELETE 的 `$subquery`/`$col`/`$exists` 无人解析 → 引擎判 UNKNOWN
    → **静默影响 0 行**(引擎层此前为此加了"检测到未解析标记就抛 NOT_SUPPORTED"
    的防御 —— 那是把"管线缺失"暴露成用户错误,方向错了)

改动:
1. SelectQueryBuilder / UpdateQueryBuilder / DeleteQueryBuilder 的 execute()
   统一为 `executor.execute(toAST())`;构造函数不再接收 engine。
   删掉 `if (joins.length > 0 && executor)` 的分支 —— executor 自己会在安全时
   下推到引擎,不需要 builder 代劳。
2. 生命周期钩子(beforeUpdate/afterUpdate/beforeDelete/afterDelete + onWrite
   广播)改由 Table 以回调形式注入 builder,顺序与修复前一致
   (before → executor → onWrite → after)。回调接收**实际语句**,
   因此 beforeUpdate 的 `query.where` 不再是空对象 —— 修复前 builder 路径的
   钩子能拿到 where,现在仍然能(新增测试锁定)。
3. Table 新增 requireExecutor():拿不到执行器时**明确报错**,不再静默退化为
   "直接调引擎"。Transaction.table() 相应构造绑定同一引擎的 QueryExecutor
   (事务原子性仍由引擎的 begin/commit/rollback 提供)。
4. 删除引擎层 4 处 `containsUnresolvedSubqueries → NOT_SUPPORTED` 防御:
   写路径已不可能出现未解析标记(builder 与 SQL 都经 Executor),
   留着它会让后来者误以为"这里需要防御"。

验证:新增 tests/v080-single-pipeline.test.ts(TABLE API 与 SQL API 逐值等价,
4 引擎 × 12 项 + 跨引擎 1 项,共 57 断言);全量 84 套件 / 1646 测试通过;
typecheck(src+tests) 与 lint 零错误。
2026-09-15 00:15:41 +08:00

212 lines
7.8 KiB
TypeScript

/**
* Executor + Builder + Memory 边缘覆盖测试
*/
import { MetonaSqlark } from '../src/core';
import { MemoryEngine } from '../src/engine/memory';
import { SelectQueryBuilder } from '../src/query/builder';
import { createSchema } from '../src/table/schema';
import { QueryExecutor } from '../src/query/executor';
describe('边缘覆盖', () => {
let db: MetonaSqlark;
beforeEach(async () => {
db = new MetonaSqlark({ name: 'test-edge', mode: 'memory' });
await db.init();
await db.defineTable('users', {
id: { type: 'string', primaryKey: true },
name: { type: 'string', required: true },
age: { type: 'number' },
active: { type: 'boolean', default: true },
});
await db.table('users').insertMany([
{ id: '1', name: 'Alice', age: 30, active: true },
{ id: '2', name: 'Bob', age: 25, active: true },
{ id: '3', name: 'Charlie', age: 35, active: false },
{ id: '4', name: 'Diana', age: 30, active: true },
]);
});
afterEach(async () => { await db.close(); });
// ---- DISTINCT ----
describe('DISTINCT', () => {
it('SELECT DISTINCT 去重', async () => {
const result = await db.query('SELECT DISTINCT age FROM users ORDER BY age') as Record<string, unknown>[];
expect(result).toHaveLength(3); // 30,25,35
});
it('DISTINCT with WHERE', async () => {
const result = await db.query("SELECT DISTINCT age FROM users WHERE active = TRUE") as Record<string, unknown>[];
expect(result).toHaveLength(2); // 30,25
});
});
// ---- $and / $or / $not ----
describe('复杂 Where 条件', () => {
it('$and 条件 (MemoryEngine 直接)', async () => {
// $and 在 MemoryEngine 的 matchWhere 中解析
const engine = new MemoryEngine();
await engine.open('test', 1);
await engine.createTable(createSchema('users', {
id: { type: 'string', primaryKey: true }, age: { type: 'number' }, active: { type: 'boolean' },
}));
await engine.insert('users', [
{ id: '1', age: 30, active: true },
{ id: '2', age: 25, active: true },
{ id: '3', age: 30, active: false },
]);
const rows = await engine.find('users', {
table: 'users',
where: { $and: [{ age: 30 }, { active: true }] } as any,
});
expect(rows).toHaveLength(1);
await engine.close();
});
it('$or 条件 (MemoryEngine 直接)', async () => {
const engine = new MemoryEngine();
await engine.open('test2', 1);
await engine.createTable(createSchema('users', {
id: { type: 'string', primaryKey: true }, name: { type: 'string' },
}));
await engine.insert('users', [
{ id: '1', name: 'Alice' }, { id: '2', name: 'Bob' }, { id: '3', name: 'Charlie' },
]);
const rows = await engine.find('users', {
table: 'users',
where: { $or: [{ name: 'Alice' }, { name: 'Bob' }] } as any,
});
expect(rows).toHaveLength(2);
await engine.close();
});
it('$not 条件', async () => {
const rows = await db.table('users').select().where({
name: { $not: { $eq: 'Alice' } } as any,
}).execute();
expect(rows).toHaveLength(3);
});
it('$in + $nin', async () => {
const r1 = await db.table('users').select().where({ age: { $in: [25, 35] } }).execute();
expect(r1).toHaveLength(2);
const r2 = await db.table('users').select().where({ age: { $nin: [30] } }).execute();
expect(r2).toHaveLength(2);
});
it('$lt + $lte', async () => {
const r = await db.table('users').select().where({ age: { $lt: 30 } }).execute();
expect(r).toHaveLength(1); // Bob(25)
const r2 = await db.table('users').select().where({ age: { $lte: 30 } }).execute();
expect(r2).toHaveLength(3); // Alice+Diana(30)+Bob(25)
});
});
// ---- QueryBuilder 全覆盖 ----
describe('QueryBuilder 全覆盖', () => {
let engine: MemoryEngine;
beforeEach(async () => {
engine = new MemoryEngine();
await engine.open('test', 1);
await engine.createTable(createSchema('users', {
id: { type: 'string', primaryKey: true },
name: { type: 'string', required: true },
}));
await engine.insert('users', [{ id: '1', name: 'Alice' }, { id: '2', name: 'Bob' }]);
});
afterEach(async () => { await engine.close(); });
it('SelectQueryBuilder.as 别名', () => {
const qb = new SelectQueryBuilder('users', new QueryExecutor(engine)).as('u');
expect(qb.toAST().alias).toBe('u');
});
it('rightJoin', () => {
const qb = new SelectQueryBuilder('users', new QueryExecutor(engine));
qb.rightJoin('orders', { 'users.id': { $col: 'orders.user_id' } }, 'o');
expect(qb.toAST().joins![0].type).toBe('RIGHT');
});
it('join 默认为 INNER', () => {
const qb = new SelectQueryBuilder('users', new QueryExecutor(engine));
qb.join('orders', { 'users.id': { $col: 'orders.user_id' } });
expect(qb.toAST().joins![0].type).toBe('INNER');
});
});
// ---- RIGHT JOIN SQL ----
describe('RIGHT JOIN', () => {
beforeEach(async () => {
await db.defineTable('departments', {
id: { type: 'number', primaryKey: true },
name: { type: 'string' },
});
await db.table('departments').insertMany([
{ id: 1, name: 'Eng' }, { id: 2, name: 'Sales' },
]);
await db.defineTable('emp', {
id: { type: 'string', primaryKey: true },
name: { type: 'string' },
dept_id: { type: 'number' },
});
await db.table('emp').insert({ id: '1', name: 'Alice', dept_id: 1 });
});
it('RIGHT JOIN 保留右表无匹配行', async () => {
const result = await db.query(
'SELECT emp.name, departments.name FROM emp RIGHT JOIN departments ON emp.dept_id = departments.id',
) as Record<string, unknown>[];
expect(result.length).toBeGreaterThanOrEqual(2);
});
});
// ---- MemoryEngine 索引 ----
describe('MemoryEngine 索引查找', () => {
it('索引列 $eq 查询', async () => {
// age 列标记为 index
await db.defineTable('indexed_users', {
id: { type: 'string', primaryKey: true },
name: { type: 'string' },
score: { type: 'number', index: true },
});
await db.table('indexed_users').insertMany([
{ id: '1', name: 'A', score: 100 },
{ id: '2', name: 'B', score: 200 },
{ id: '3', name: 'C', score: 100 },
]);
// $eq 查询应使用索引
const rows = await db.table('indexed_users').select().where({ score: 100 }).execute();
expect(rows).toHaveLength(2);
});
it('唯一索引列查询', async () => {
await db.defineTable('unique_users', {
id: { type: 'string', primaryKey: true },
email: { type: 'string', unique: true },
});
await db.table('unique_users').insertMany([
{ id: '1', email: 'a@t.com' },
{ id: '2', email: 'b@t.com' },
]);
const rows = await db.table('unique_users').select().where({ email: 'a@t.com' }).execute();
expect(rows).toHaveLength(1);
});
});
// ---- GROUP BY 边缘 ----
describe('GROUP BY 边缘', () => {
it('单个 GROUP BY 列', async () => {
const result = await db.query('SELECT active, COUNT(*) FROM users GROUP BY active') as Record<string, unknown>[];
expect(result).toHaveLength(2);
});
it('AVG 空值处理 (GROUP BY)', async () => {
await db.defineTable('scores', { id: { type: 'string', primaryKey: true }, dept: { type: 'string' }, val: { type: 'number' } });
await db.table('scores').insertMany([{ id: '1', dept: 'A', val: 100 }, { id: '2', dept: 'A', val: 200 }]);
const result = await db.query('SELECT dept, AVG(val) FROM scores GROUP BY dept') as Record<string, unknown>[];
expect(result[0]['AVG(val)']).toBe(150);
});
});
});