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