Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

sql-predicate-semantics.e2e.test.ts

512 lines16.8 KB

1import { fc } from '@fast-check/vitest'
2import electricClientPackage from '@electric-sql/client/package.json'
3import { IR } from '@tanstack/db'
4import { afterAll, beforeAll, describe, expect, inject, it } from 'vitest'
5import { makePgClient } from '../../db-collection-e2e/support/global-setup'
6import { compileSQL } from '../src/sql-compiler'
7import type { Client } from 'pg'
8​
9type Row = {
10 id: number
11 count: number | null
12 label: string | null
13 enabled: boolean | null
15​
16type Column = `count` | `label` | `enabled`
17type Comparable = number | string | boolean
18type Comparison = `eq` | `gt` | `gte` | `lt` | `lte`
19type Truth = boolean | null
20type Predicate =
21 | { type: `compare`; op: Comparison; column: Column; value: Comparable }
22 | { type: `isNull`; column: Column }
23 | { type: `not`; value: Predicate }
24 | { type: `and`; left: Predicate; right: Predicate }
25 | { type: `or`; left: Predicate; right: Predicate }
26 | {
27 type: `test`
28 op: `eq` | `in` | `isNull`
29 value: Predicate
30 expected: boolean
31 both: boolean
32 }
33​
34/*
35Compiler contract inventory:
36​
37| Contract | Focused owner | Semantic owner |
38| -------------------------------- | ------------------------- | -------------- |
39| comparison operators and values | sql-compiler.test.ts | this suite |
40| Boolean grouping | sql-compiler.test.ts | this suite |
41| IS NULL / SQL three-valued logic | sql-compiler.test.ts | this suite |
42| parameter binding and quoting | sql-compiler.test.ts | this suite |
43| stable wire text and name mapping| sql-compiler.test.ts | focused only |
44| unsupported expressions/errors | sql-compiler.test.ts | focused only |
45​
46This suite sends the compiler's emitted SQL and serialized parameters to
47PostgreSQL, then compares selected IDs with a separately specified finite
48three-valued evaluator. The focused-only rows are intentionally not inferred
49from semantic equality.
50*/
51​
52const electricClientVersion = electricClientPackage.version
53​
54const integerComparison = fc.record({
55 type: fc.constant(`compare` as const),
56 op: fc.constantFrom<Comparison>(`eq`, `gt`, `gte`, `lt`, `lte`),
57 column: fc.constant(`count` as const),
58 value: fc.integer({ min: -2, max: 2 }),
59})
60const stringComparison = fc.record({
61 type: fc.constant(`compare` as const),
62 // Text ordering depends on the database collation; equality does not.
63 op: fc.constant(`eq` as const),
64 column: fc.constant(`label` as const),
65 value: fc.constantFrom(``, `a`, `b`, `O'Reilly`, `"quoted"`),
66})
67const booleanComparison = fc.record({
68 type: fc.constant(`compare` as const),
69 op: fc.constant(`eq` as const),
70 column: fc.constant(`enabled` as const),
71 value: fc.boolean(),
72})
73const nullCheck = fc.record({
74 type: fc.constant(`isNull` as const),
75 column: fc.constantFrom<Column>(`count`, `label`, `enabled`),
76})
77const leaf = fc.oneof(
78 integerComparison,
79 stringComparison,
80 booleanComparison,
81 nullCheck,
83const predicate: fc.Memo<Predicate> = fc.memo<Predicate>((depth) =>
84 depth <= 1
85 ? leaf
86 : fc.oneof(
87 leaf,
88 fc.record({
89 type: fc.constant(`not` as const),
90 value: predicate(depth - 1),
91 }),
92 fc.record({
93 type: fc.constant(`and` as const),
94 left: predicate(depth - 1),
95 right: predicate(depth - 1),
96 }),
97 fc.record({
98 type: fc.constant(`or` as const),
99 left: predicate(depth - 1),
100 right: predicate(depth - 1),
101 }),
102 fc.record({
103 type: fc.constant(`test` as const),
104 op: fc.constantFrom(`eq` as const, `in` as const, `isNull` as const),
105 value: predicate(depth - 1),
106 expected: fc.boolean(),
107 both: fc.boolean(),
108 }),
109 ),
111​
112const rows = fc.uniqueArray(
113 fc.record({
114 id: fc.integer({ min: 1, max: 20 }),
115 count: fc.option(fc.integer({ min: -3, max: 3 }), { nil: null }),
116 label: fc.option(fc.constantFrom(``, `a`, `b`, `O'Reilly`, `"quoted"`), {
117 nil: null,
118 }),
119 enabled: fc.option(fc.boolean(), { nil: null }),
120 }),
121 { minLength: 1, maxLength: 12, selector: ({ id }) => id },
123​
124const requiredReach = [
125 `predicate:and`,
126 `predicate:or`,
127 `predicate:not`,
128 `predicate:isNull`,
129 `context:eq`,
130 `context:in`,
131 `context:isNull`,
132 `comparison:eq`,
133 `comparison:gt`,
134 `comparison:gte`,
135 `comparison:lt`,
136 `comparison:lte`,
137 `column:label`,
138 `column:enabled`,
139 `literal:empty-string`,
140 `literal:single-quote`,
141 `literal:quoted-string`,
142 `row:null-count`,
143 `row:null-label`,
144 `row:null-enabled`,
145] as const
146​
147function recordPredicateReach(value: Predicate, reached: Set<string>): void {
148 reached.add(`predicate:${value.type}`)
149 if (value.type === `test`) {
150 reached.add(`context:${value.op}`)
151 recordPredicateReach(value.value, reached)
152 return
153 }
154 if (value.type === `compare`) {
155 reached.add(`comparison:${value.op}`)
156 reached.add(`column:${value.column}`)
157 if (value.value === ``) reached.add(`literal:empty-string`)
158 if (value.value === `O'Reilly`) reached.add(`literal:single-quote`)
159 if (value.value === `"quoted"`) reached.add(`literal:quoted-string`)
160 return
161 }
162 if (value.type === `not`) {
163 recordPredicateReach(value.value, reached)
164 return
165 }
166 if (value.type === `and` || value.type === `or`) {
167 recordPredicateReach(value.left, reached)
168 recordPredicateReach(value.right, reached)
169 }
171​
172function recordRowReach(world: Array<Row>, reached: Set<string>): void {
173 for (const row of world) {
174 if (row.count === null) reached.add(`row:null-count`)
175 if (row.label === null) reached.add(`row:null-label`)
176 if (row.enabled === null) reached.add(`row:null-enabled`)
177 }
179​
180function toExpression(value: Predicate): IR.BasicExpression<boolean> {
181 if (value.type === `test`) {
182 const inner = toExpression(value.value)
183 return new IR.Func(
184 value.op,
185 value.op === `isNull`
186 ? [inner]
187 : [
188 inner,
189 new IR.Value(
190 value.op === `eq`
191 ? value.expected
192 : value.both
193 ? [true, false]
194 : [value.expected],
195 ),
196 ],
197 )
198 }
199 if (value.type === `compare`) {
200 return new IR.Func(value.op, [
201 new IR.PropRef([value.column]),
202 new IR.Value(value.value),
203 ])
204 }
205 if (value.type === `isNull`) {
206 return new IR.Func(`isNull`, [new IR.PropRef([value.column])])
207 }
208 if (value.type === `not`) {
209 return new IR.Func(`not`, [toExpression(value.value)])
210 }
211 return new IR.Func(value.type, [
212 toExpression(value.left),
213 toExpression(value.right),
214 ])
216​
217function negate(value: Truth): Truth {
218 return value === null ? null : !value
220​
221function combine(type: `and` | `or`, left: Truth, right: Truth): Truth {
222 if (type === `and`) {
223 if (left === false || right === false) return false
224 return left === true && right === true ? true : null
225 }
226 if (left === true || right === true) return true
227 return left === false && right === false ? false : null
229​
230function evaluate(value: Predicate, row: Row): Truth {
231 if (value.type === `test`) {
232 const actual = evaluate(value.value, row)
233 if (value.op === `isNull`) return actual === null
234 if (actual === null) return null
235 return value.op === `in` && value.both ? true : actual === value.expected
236 }
237 if (value.type === `isNull`) return row[value.column] === null
238 if (value.type === `not`) return negate(evaluate(value.value, row))
239 if (value.type === `and` || value.type === `or`) {
240 return combine(
241 value.type,
242 evaluate(value.left, row),
243 evaluate(value.right, row),
244 )
245 }
246 const actual = row[value.column]
247 if (actual === null) return null
248 if (typeof actual !== typeof value.value) {
249 throw new Error(`Generated a comparison across PostgreSQL type domains`)
250 }
251 if (value.op === `eq`) return actual === value.value
252 if (value.op === `gt`) return actual > value.value
253 if (value.op === `gte`) return actual >= value.value
254 if (value.op === `lt`) return actual < value.value
255 return actual <= value.value
257​
258describe(`Electric predicate compiler semantics`, () => {
259 let client: Client
260 let table: string
261​
262 beforeAll(async () => {
263 client = makePgClient()
264 await client.connect()
265 await client.query(`SET search_path TO ${inject(`testSchema`)}`)
266 table = `predicate_semantics_${Date.now().toString(16)}`
267 await client.query(
268 `CREATE TABLE "${table}" (
269 id INTEGER PRIMARY KEY,
270 count INTEGER,
271 label TEXT,
272 enabled BOOLEAN,
273 roles TEXT[],
274 integer_roles INTEGER[],
275 required_role VARCHAR(16)
276 )`,
277 )
278 })
279​
280 afterAll(async () => {
281 await client.query(`DROP TABLE IF EXISTS "${table}"`)
282 await client.end()
283 })
284​
285 it(`matches PostgreSQL over finite row worlds`, async () => {
286 let executedCells = 0
287 const reached = new Set<string>()
288 const version = await client.query<{ server_version: string }>(
289 `SHOW server_version`,
290 )
291 await fc.assert(
292 fc.asyncProperty(
293 rows,
294 predicate(3),
295 async (world, generatedPredicate) => {
296 recordRowReach(world, reached)
297 recordPredicateReach(generatedPredicate, reached)
298 await client.query(`TRUNCATE "${table}"`)
299 for (const row of world) {
300 await client.query(
301 `INSERT INTO "${table}" (id, count, label, enabled) VALUES ($1, $2, $3, $4)`,
302 [row.id, row.count, row.label, row.enabled],
303 )
304 }
305 const compiled = compileSQL({
306 where: toExpression(generatedPredicate),
307 })
308 const params = Object.entries(compiled.params ?? {})
309 .sort(([left], [right]) => Number(left) - Number(right))
310 .map(([, value]) => value)
311 const result = await client.query<{ id: number }>(
312 `SELECT id FROM "${table}" WHERE ${compiled.where} ORDER BY id`,
313 params,
314 )
315 const expected = world
316 .filter((row) => evaluate(generatedPredicate, row) === true)
317 .map(({ id }) => id)
318 .sort((left, right) => left - right)
319 expect(result.rows.map(({ id }) => id)).toEqual(expected)
320 executedCells++
321 },
322 ),
323 {
324 seed: 1814,
325 numRuns: 50,
326 // Compound booleans are values too: cross comparison, membership, and
327 // null tests, including NOT with both possible membership values.
328 examples: [
329 ...([`eq`, `in`, `isNull`] as const).map(
330 (op): [Array<Row>, Predicate] => [
331 [
332 { id: 1, count: 4, label: null, enabled: true },
333 { id: 2, count: 2, label: `a`, enabled: false },
334 { id: 3, count: null, label: `O'Reilly`, enabled: null },
335 ],
336 {
337 type: `test`,
338 op,
339 expected: true,
340 both: true,
341 value:
342 op === `in`
343 ? {
344 type: `not`,
345 value: {
346 type: `compare`,
347 op: `eq`,
348 column: `enabled`,
349 value: true,
350 },
351 }
352 : { type: `compare`, op: `gt`, column: `count`, value: 3 },
353 },
354 ],
355 ),
356 [
357 [{ id: 1, count: 0, label: `O'Reilly`, enabled: null }],
358 { type: `compare`, op: `eq`, column: `label`, value: `O'Reilly` },
359 ],
360 ],
361 },
362 )
363 expect(executedCells).toBe(50)
364 expect([...reached].sort()).toEqual(
365 expect.arrayContaining([...requiredReach]),
366 )
367 console.info(
368 `Electric predicate semantics: PostgreSQL ${version.rows[0]?.server_version}; Electric client ${electricClientVersion}; 50 generated cells; ${reached.size} reached categories`,
369 )
370 })
371​
372 it(`preserves boolean grouping beneath a comparison`, async () => {
373 const world: Array<Row> = [
374 { id: 1, count: 0, label: null, enabled: true },
375 { id: 2, count: 0, label: null, enabled: false },
376 { id: 3, count: 0, label: null, enabled: null },
377 ]
378 await client.query(`TRUNCATE "${table}"`)
379 for (const row of world) {
380 await client.query(
381 `INSERT INTO "${table}" (id, count, label, enabled) VALUES ($1, $2, $3, $4)`,
382 [row.id, row.count, row.label, row.enabled],
383 )
384 }
385 const compiled = compileSQL({
386 where: new IR.Func(`eq`, [
387 new IR.Func(`or`, [new IR.PropRef([`enabled`]), new IR.Value(false)]),
388 new IR.Value(false),
389 ]),
390 })
391 const result = await client.query<{ id: number }>(
392 `SELECT id FROM "${table}" WHERE ${compiled.where} ORDER BY id`,
393 Object.values(compiled.params ?? {}),
394 )
395​
396 expect(result.rows.map(({ id }) => id)).toEqual([2])
397 })
398​
399 it(`preserves PostgreSQL array membership semantics`, async () => {
400 await client.query(`TRUNCATE "${table}"`)
401 await client.query(
402 `INSERT INTO "${table}" (id, roles, integer_roles, required_role) VALUES
403 (1, ARRAY['admin', 'editor'], ARRAY[1, 2], 'admin'),
404 (2, ARRAY['viewer'], ARRAY[3], 'admin'),
405 (3, NULL, NULL, NULL),
406 (4, ARRAY[NULL]::TEXT[], ARRAY[NULL]::INTEGER[], 'admin')`,
407 )
408​
409 const ref = (column: string) => new IR.PropRef([column])
410 const call = (name: string, ...args: Array<IR.BasicExpression>) =>
411 new IR.Func<boolean>(name, args)
412 const selectedIds = async (
413 where: IR.BasicExpression<boolean>,
414 ): Promise<Array<number>> => {
415 const compiled = compileSQL({ where })
416 const params = Object.entries(compiled.params ?? {})
417 .sort(([left], [right]) => Number(left) - Number(right))
418 .map(([, value]) => value)
419 const result = await client.query<{ id: number }>(
420 `SELECT id FROM "${table}" WHERE ${compiled.where} ORDER BY id`,
421 params,
422 )
423 return result.rows.map(({ id }) => id)
424 }
425​
426 const integerMembership = call(`in`, new IR.Value(2), ref(`integer_roles`))
427 expect(await selectedIds(integerMembership)).toEqual([1])
428 expect(await selectedIds(call(`not`, integerMembership))).toEqual([2, 3, 4])
429 expect(
430 await selectedIds(call(`in`, ref(`required_role`), ref(`roles`))),
431 ).toEqual([1])
432​
433 const reversedContainment = await client.query<{ id: number }>(
434 `SELECT id FROM "${table}" WHERE ARRAY[$1] @> roles ORDER BY id`,
435 [`admin`],
436 )
437 expect(reversedContainment.rows.map(({ id }) => id)).not.toEqual([1])
438 await expect(
439 client.query(
440 `SELECT id FROM "${table}" WHERE integer_roles @> ARRAY[$1]`,
441 [`2`],
442 ),
443 ).rejects.toMatchObject({ code: `42883` })
444 })
445​
446 it(`rejects representative compiler faults against PostgreSQL`, async () => {
447 const world: Array<Row> = [
448 { id: 1, count: 2, label: null, enabled: true },
449 { id: 2, count: 2, label: null, enabled: false },
450 { id: 3, count: null, label: null, enabled: true },
451 { id: 4, count: 0, label: null, enabled: true },
452 ]
453 await client.query(`TRUNCATE "${table}"`)
454 for (const row of world) {
455 await client.query(
456 `INSERT INTO "${table}" (id, count, label, enabled) VALUES ($1, $2, $3, $4)`,
457 [row.id, row.count, row.label, row.enabled],
458 )
459 }
460 const faultControlPredicate: Predicate = {
461 type: `and`,
462 left: {
463 type: `or`,
464 left: { type: `compare`, op: `gt`, column: `count`, value: 1 },
465 right: { type: `isNull`, column: `count` },
466 },
467 right: { type: `compare`, op: `eq`, column: `enabled`, value: true },
468 }
469 const expected = world
470 .filter((row) => evaluate(faultControlPredicate, row) === true)
471 .map(({ id }) => id)
472 const compiled = compileSQL({ where: toExpression(faultControlPredicate) })
473 const compiledResult = await client.query<{ id: number }>(
474 `SELECT id FROM "${table}" WHERE ${compiled.where} ORDER BY id`,
475 Object.values(compiled.params ?? {}),
476 )
477 expect(compiledResult.rows.map(({ id }) => id)).toEqual(expected)
478​
479 const faults = [
480 {
481 name: `wrong bound`,
482 sql: `("count" > $1 OR "count" IS NULL) AND "enabled" = $2`,
483 params: [`2`, `true`],
484 },
485 {
486 name: `lost predicate`,
487 sql: `"count" > $1 OR "count" IS NULL`,
488 params: [`1`],
489 },
490 {
491 name: `incorrect null handling`,
492 sql: `"count" > $1 AND "enabled" = $2`,
493 params: [`1`, `true`],
494 },
495 {
496 name: `swapped comparison direction`,
497 sql: `("count" < $1 OR "count" IS NULL) AND "enabled" = $2`,
498 params: [`1`, `true`],
499 },
500 ]
501 for (const fault of faults) {
502 const result = await client.query<{ id: number }>(
503 `SELECT id FROM "${table}" WHERE ${fault.sql} ORDER BY id`,
504 fault.params,
505 )
506 expect(
507 result.rows.map(({ id }) => id),
508 fault.name,
509 ).not.toEqual(expected)
510 }
511 })
512})