|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * [#19975] The read-scope compiler never binds a LIST into an equality — in |
| 5 | + * either spelling of the equality slot, at any depth. |
| 6 | + * |
| 7 | + * Ruling 乙 on #19757 refuses a list in the equality slot at the shared |
| 8 | + * comparand-shape face, for every driver at once. `compileScopedFilterToSql` |
| 9 | + * never meets that face (a read scope arrives through `getReadScope`), so the |
| 10 | + * ruling is pushed down to it here: |
| 11 | + * |
| 12 | + * - the EXPLICIT spelling, `{ f: { $eq: [...] } }`, used to compile to |
| 13 | + * `col = ?` with the whole list bound as one parameter, and what that |
| 14 | + * predicate selected was the executing engine's reading of a list. It is |
| 15 | + * now refused ({@link assertNoListInEqualitySlot} in `read-scope-sql.ts`); |
| 16 | + * - the IMPLICIT spelling, `{ f: [...] }` — the shape a CEL `field == <list>` |
| 17 | + * policy lowers to — was already refused; the depth pins below hold it. |
| 18 | + * |
| 19 | + * Both refusals carry this module's envelope, `READ_SCOPE_COMPILE_FAILED` / 500 |
| 20 | + * (the #5367 ruling), never the shared face's `INVALID_FILTER` / 400: the |
| 21 | + * producer is a policy the caller cannot author. |
| 22 | + * |
| 23 | + * Four blocks: the explicit spelling at every depth, the implicit spelling at |
| 24 | + * every depth, the neighbouring shapes that must keep compiling exactly as |
| 25 | + * before, and the two strategy faces that reach this compiler, driven over a |
| 26 | + * real engine — where the refusal must land before any statement runs. |
| 27 | + */ |
| 28 | + |
| 29 | +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; |
| 30 | +import { SqliteWasmDriver } from '@objectstack/driver-sqlite-wasm'; |
| 31 | +import type { Cube, FilterCondition } from '@objectstack/spec/data'; |
| 32 | +import type { AnalyticsQuery, StrategyContext } from '@objectstack/spec/contracts'; |
| 33 | + |
| 34 | +import { compileScopedFilterToSql } from '../read-scope-sql.js'; |
| 35 | +import { NativeSQLStrategy } from '../strategies/native-sql-strategy.js'; |
| 36 | +import { ObjectQLStrategy } from '../strategies/objectql-strategy.js'; |
| 37 | + |
| 38 | +interface Refusal extends Error { |
| 39 | + code?: unknown; |
| 40 | + status?: unknown; |
| 41 | +} |
| 42 | + |
| 43 | +function refusalOf(scope: unknown): Refusal { |
| 44 | + try { |
| 45 | + const out = compileScopedFilterToSql(scope as FilterCondition, 't'); |
| 46 | + throw new Error(`expected a refusal, but the scope compiled to ${JSON.stringify(out)}`); |
| 47 | + } catch (e) { |
| 48 | + return e as Refusal; |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +function expectEnvelope(err: Refusal): void { |
| 53 | + expect(err.code).toBe('READ_SCOPE_COMPILE_FAILED'); |
| 54 | + expect(err.status).toBe(500); |
| 55 | +} |
| 56 | + |
| 57 | +// ───────────────────────────────────────────────────────────────────────────── |
| 58 | + |
| 59 | +describe('[#19975] a list under $eq is refused, never bound', () => { |
| 60 | + const CASES: Array<[string, unknown]> = [ |
| 61 | + ['two members', { status: { $eq: ['open', 'pending'] } }], |
| 62 | + ['one member', { status: { $eq: ['open'] } }], |
| 63 | + ['the empty list', { status: { $eq: [] } }], |
| 64 | + ['beside another operator, listed first', { status: { $eq: ['open'], $ne: 'closed' } }], |
| 65 | + ['beside another operator, listed last', { status: { $ne: 'closed', $eq: ['open'] } }], |
| 66 | + ['under $and', { $and: [{ team_id: 't1' }, { status: { $eq: ['open'] } }] }], |
| 67 | + ['under $or', { $or: [{ team_id: 't1' }, { status: { $eq: ['open'] } }] }], |
| 68 | + // The widening direction: a negated equality that can never hold is |
| 69 | + // constant TRUE, so this is the spelling that used to admit every row. |
| 70 | + ['under $not', { $not: { status: { $eq: ['open'] } } }], |
| 71 | + ['under $not over $or', { $not: { $or: [{ team_id: 't1' }, { status: { $eq: ['open'] } }] } }], |
| 72 | + ]; |
| 73 | + |
| 74 | + for (const [name, scope] of CASES) { |
| 75 | + it(`${name}: READ_SCOPE_COMPILE_FAILED / 500, naming the field and $eq`, () => { |
| 76 | + const err = refusalOf(scope); |
| 77 | + expectEnvelope(err); |
| 78 | + expect(err.message).toContain('"status".$eq'); |
| 79 | + }); |
| 80 | + } |
| 81 | + |
| 82 | + it('a list is diagnosed as the list, not by one of its members', () => { |
| 83 | + // The member gates (#6125's undefined comparand, #7598's field reference) |
| 84 | + // would otherwise answer first and send the operator to the wrong repair. |
| 85 | + for (const scope of [ |
| 86 | + { status: { $eq: [undefined] } }, |
| 87 | + { status: { $eq: [{ $field: 'prior_status' }] } }, |
| 88 | + ]) { |
| 89 | + const err = refusalOf(scope); |
| 90 | + expectEnvelope(err); |
| 91 | + expect(err.message).toContain('"status".$eq'); |
| 92 | + expect(err.message).not.toMatch(/is undefined|field reference/); |
| 93 | + } |
| 94 | + }); |
| 95 | +}); |
| 96 | + |
| 97 | +describe('[#19975] the implicit spelling — what a CEL `field == <list>` lowers to — stays refused at every depth', () => { |
| 98 | + const CASES: Array<[string, unknown]> = [ |
| 99 | + ['top level', { status: ['open', 'pending'] }], |
| 100 | + ['the empty list', { status: [] }], |
| 101 | + ['under $and', { $and: [{ team_id: 't1' }, { status: ['open'] }] }], |
| 102 | + ['under $or', { $or: [{ team_id: 't1' }, { status: ['open'] }] }], |
| 103 | + ['under $not', { $not: { status: ['open'] } }], |
| 104 | + ]; |
| 105 | + |
| 106 | + for (const [name, scope] of CASES) { |
| 107 | + it(`${name}: READ_SCOPE_COMPILE_FAILED / 500, as a bare array`, () => { |
| 108 | + const err = refusalOf(scope); |
| 109 | + expectEnvelope(err); |
| 110 | + expect(err.message).toContain('bare array value for "status"'); |
| 111 | + }); |
| 112 | + } |
| 113 | +}); |
| 114 | + |
| 115 | +describe('[#19975] the neighbouring shapes keep compiling exactly as before', () => { |
| 116 | + const ACCEPTED: Array<[string, unknown, string, unknown[]]> = [ |
| 117 | + ['a scalar under $eq', { status: { $eq: 'open' } }, '"t"."status" = ?', ['open']], |
| 118 | + ['a number under $eq', { amount: { $eq: 0 } }, '"t"."amount" = ?', [0]], |
| 119 | + ['null under $eq — the has-no-value predicate', { status: { $eq: null } }, '"t"."status" IS NULL', []], |
| 120 | + ['the implicit scalar', { status: 'open' }, '"t"."status" = ?', ['open']], |
| 121 | + ['a list under $in — the prescribed spelling', { status: { $in: ['open', 'pending'] } }, '"t"."status" IN (?, ?)', ['open', 'pending']], |
| 122 | + ['the empty $in — the FALSE constant (#5243)', { status: { $in: [] } }, '1 = 0', []], |
| 123 | + ]; |
| 124 | + |
| 125 | + for (const [name, scope, sql, params] of ACCEPTED) { |
| 126 | + it(name, () => { |
| 127 | + const out = compileScopedFilterToSql(scope as FilterCondition, 't'); |
| 128 | + expect(out.sql).toBe(sql); |
| 129 | + expect(out.params).toEqual(params); |
| 130 | + }); |
| 131 | + } |
| 132 | + |
| 133 | + it('a Date under $eq still binds', () => { |
| 134 | + const at = new Date('2026-01-01T00:00:00.000Z'); |
| 135 | + const out = compileScopedFilterToSql({ created_at: { $eq: at } } as FilterCondition, 't'); |
| 136 | + expect(out.sql).toBe('"t"."created_at" = ?'); |
| 137 | + expect(out.params).toEqual([at]); |
| 138 | + }); |
| 139 | +}); |
| 140 | + |
| 141 | +// ───────────────────────────────────────────────────────────────────────────── |
| 142 | + |
| 143 | +const OBJECT = 'ticket'; |
| 144 | +const ROWS = [ |
| 145 | + { id: 'r1', status: 'open' }, |
| 146 | + { id: 'r2', status: 'pending' }, |
| 147 | + { id: 'r3', status: 'closed' }, |
| 148 | + { id: 'r4', status: null }, |
| 149 | +]; |
| 150 | +const CUBE: Cube = { |
| 151 | + name: 'tickets', |
| 152 | + sql: OBJECT, |
| 153 | + measures: { n: { sql: '*', type: 'count', title: 'n' } }, |
| 154 | + dimensions: Object.fromEntries( |
| 155 | + ['id', 'status'].map((n) => [n, { name: n, label: n, type: 'string', sql: n }]), |
| 156 | + ), |
| 157 | + public: false, |
| 158 | +} as unknown as Cube; |
| 159 | +const QUERY = { cube: 'tickets', dimensions: ['id'], measures: ['n'] } as AnalyticsQuery; |
| 160 | + |
| 161 | +describe('[#19975] both faces that reach the compiler refuse before any statement runs (real engine)', () => { |
| 162 | + let driver: SqliteWasmDriver; |
| 163 | + let statements = 0; |
| 164 | + |
| 165 | + const runRawSql = async (sql: string, params: unknown[]): Promise<Record<string, unknown>[]> => { |
| 166 | + statements++; |
| 167 | + const result = await driver.execute(sql.replace(/\$\d+/g, '?'), params); |
| 168 | + if (Array.isArray(result)) return result as Record<string, unknown>[]; |
| 169 | + if (result && typeof result === 'object' && 'rows' in (result as Record<string, unknown>)) { |
| 170 | + return (result as { rows: Record<string, unknown>[] }).rows; |
| 171 | + } |
| 172 | + return []; |
| 173 | + }; |
| 174 | + |
| 175 | + const ctxFor = (scope: unknown, nativeSql: boolean): StrategyContext => |
| 176 | + ({ |
| 177 | + getCube: (name: string) => (name === 'tickets' ? CUBE : undefined), |
| 178 | + queryCapabilities: () => ({ nativeSql, objectqlAggregate: !nativeSql, inMemory: false }), |
| 179 | + getReadScope: () => (scope ?? undefined) as FilterCondition | undefined, |
| 180 | + executeRawSql: (_object: string, sql: string, params: unknown[]) => runRawSql(sql, params), |
| 181 | + sqlDialect: () => 'sqlite', |
| 182 | + }) as unknown as StrategyContext; |
| 183 | + |
| 184 | + /** NativeSQL EXECUTE: `applyReadScope` → `ctx.executeRawSql`. */ |
| 185 | + const nativeIds = async (scope: unknown): Promise<string[]> => { |
| 186 | + const result = await new NativeSQLStrategy().execute(QUERY, ctxFor(scope, true)); |
| 187 | + return result.rows.map((r) => String(r.id)).sort(); |
| 188 | + }; |
| 189 | + |
| 190 | + /** The `/analytics/sql` echo, its SQL then run on the same engine. */ |
| 191 | + const echoIds = async (scope: unknown): Promise<string[]> => { |
| 192 | + const { sql, params } = await new ObjectQLStrategy().generateSql(QUERY, ctxFor(scope, false)); |
| 193 | + const rows = await runRawSql(sql, params); |
| 194 | + return rows.map((r) => String(r.id)).sort(); |
| 195 | + }; |
| 196 | + |
| 197 | + const FACES = [ |
| 198 | + ['native execute', nativeIds], |
| 199 | + ['echo', echoIds], |
| 200 | + ] as const; |
| 201 | + |
| 202 | + beforeAll(async () => { |
| 203 | + driver = new SqliteWasmDriver({ filename: ':memory:' }); |
| 204 | + await driver.initObjects([ |
| 205 | + { |
| 206 | + name: OBJECT, |
| 207 | + fields: { id: { type: 'text', name: 'id' }, status: { type: 'text', name: 'status' } }, |
| 208 | + } as never, |
| 209 | + ]); |
| 210 | + for (const row of ROWS) await driver.create(OBJECT, { ...row }); |
| 211 | + }); |
| 212 | + |
| 213 | + afterAll(async () => { |
| 214 | + await driver?.disconnect?.(); |
| 215 | + }); |
| 216 | + |
| 217 | + it('CONTROL: no scope serves every row, and the prescribed $in serves exactly the named rows', async () => { |
| 218 | + // Without this, the refusals below could pass on a harness that serves nothing. |
| 219 | + for (const [face, run] of FACES) { |
| 220 | + expect(await run(null), `${face}: no scope`).toEqual(['r1', 'r2', 'r3', 'r4']); |
| 221 | + expect(await run({ status: { $in: ['open', 'pending'] } }), `${face}: $in`).toEqual(['r1', 'r2']); |
| 222 | + } |
| 223 | + }); |
| 224 | + |
| 225 | + for (const [name, scope] of [ |
| 226 | + ['a list under $eq', { status: { $eq: ['open', 'pending'] } }], |
| 227 | + ['a list under $eq, negated', { $not: { status: { $eq: ['open'] } } }], |
| 228 | + ['the implicit list', { status: ['open', 'pending'] }], |
| 229 | + ] as const) { |
| 230 | + for (const [face, run] of FACES) { |
| 231 | + it(`${face}: ${name} is refused, and no statement reaches the engine`, async () => { |
| 232 | + statements = 0; |
| 233 | + let err: Refusal | undefined; |
| 234 | + let served: string[] | undefined; |
| 235 | + try { |
| 236 | + served = await run(scope); |
| 237 | + } catch (e) { |
| 238 | + err = e as Refusal; |
| 239 | + } |
| 240 | + expect(served, `${face}: expected a refusal, got rows`).toBeUndefined(); |
| 241 | + expect(err).toBeInstanceOf(Error); |
| 242 | + expectEnvelope(err as Refusal); |
| 243 | + expect(statements).toBe(0); |
| 244 | + }); |
| 245 | + } |
| 246 | + } |
| 247 | +}); |
0 commit comments