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

sql-predicate-semantics.e2e.test.ts

117 lines4.0 KB

1// Ordinary PostgreSQL compiler checks for boolean grouping beneath a comparison and
2// array membership. The predicate meaning law (selected IDs match a finite
3// three-valued evaluator) is owned by sql-predicate-semantics-oracle.e2e.test.ts.
4import { IR } from '@tanstack/db'
5import { afterAll, beforeAll, describe, expect, inject, it } from 'vitest'
6import { makePgClient } from '../../db-collection-e2e/support/global-setup'
7import { compileSQL } from '../src/sql-compiler'
8import type { Client } from 'pg'
9​
10type Row = {
11 id: number
12 count: number | null
13 label: string | null
14 enabled: boolean | null
16​
17describe(`Electric predicate compiler semantics`, () => {
18 let client: Client
19 let table: string
20​
21 beforeAll(async () => {
22 client = makePgClient()
23 await client.connect()
24 await client.query(`SET search_path TO ${inject(`testSchema`)}`)
25 table = `predicate_semantics_${Date.now().toString(16)}`
26 await client.query(
27 `CREATE TABLE "${table}" (
28 id INTEGER PRIMARY KEY,
29 count INTEGER,
30 label TEXT,
31 enabled BOOLEAN,
32 roles TEXT[],
33 integer_roles INTEGER[],
34 required_role VARCHAR(16)
35 )`,
36 )
37 })
38​
39 afterAll(async () => {
40 await client.query(`DROP TABLE IF EXISTS "${table}"`)
41 await client.end()
42 })
43​
44 it(`preserves boolean grouping beneath a comparison`, async () => {
45 const world: Array<Row> = [
46 { id: 1, count: 0, label: null, enabled: true },
47 { id: 2, count: 0, label: null, enabled: false },
48 { id: 3, count: 0, label: null, enabled: null },
49 ]
50 await client.query(`TRUNCATE "${table}"`)
51 for (const row of world) {
52 await client.query(
53 `INSERT INTO "${table}" (id, count, label, enabled) VALUES ($1, $2, $3, $4)`,
54 [row.id, row.count, row.label, row.enabled],
55 )
56 }
57 const compiled = compileSQL({
58 where: new IR.Func(`eq`, [
59 new IR.Func(`or`, [new IR.PropRef([`enabled`]), new IR.Value(false)]),
60 new IR.Value(false),
61 ]),
62 })
63 const result = await client.query<{ id: number }>(
64 `SELECT id FROM "${table}" WHERE ${compiled.where} ORDER BY id`,
65 Object.values(compiled.params ?? {}),
66 )
67​
68 expect(result.rows.map(({ id }) => id)).toEqual([2])
69 })
70​
71 it(`preserves PostgreSQL array membership semantics`, async () => {
72 await client.query(`TRUNCATE "${table}"`)
73 await client.query(
74 `INSERT INTO "${table}" (id, roles, integer_roles, required_role) VALUES
75 (1, ARRAY['admin', 'editor'], ARRAY[1, 2], 'admin'),
76 (2, ARRAY['viewer'], ARRAY[3], 'admin'),
77 (3, NULL, NULL, NULL),
78 (4, ARRAY[NULL]::TEXT[], ARRAY[NULL]::INTEGER[], 'admin')`,
79 )
80​
81 const ref = (column: string) => new IR.PropRef([column])
82 const call = (name: string, ...args: Array<IR.BasicExpression>) =>
83 new IR.Func<boolean>(name, args)
84 const selectedIds = async (
85 where: IR.BasicExpression<boolean>,
86 ): Promise<Array<number>> => {
87 const compiled = compileSQL({ where })
88 const params = Object.entries(compiled.params ?? {})
89 .sort(([left], [right]) => Number(left) - Number(right))
90 .map(([, value]) => value)
91 const result = await client.query<{ id: number }>(
92 `SELECT id FROM "${table}" WHERE ${compiled.where} ORDER BY id`,
93 params,
94 )
95 return result.rows.map(({ id }) => id)
96 }
97​
98 const integerMembership = call(`in`, new IR.Value(2), ref(`integer_roles`))
99 expect(await selectedIds(integerMembership)).toEqual([1])
100 expect(await selectedIds(call(`not`, integerMembership))).toEqual([2, 3, 4])
101 expect(
102 await selectedIds(call(`in`, ref(`required_role`), ref(`roles`))),
103 ).toEqual([1])
104​
105 const reversedContainment = await client.query<{ id: number }>(
106 `SELECT id FROM "${table}" WHERE ARRAY[$1] @> roles ORDER BY id`,
107 [`admin`],
108 )
109 expect(reversedContainment.rows.map(({ id }) => id)).not.toEqual([1])
110 await expect(
111 client.query(
112 `SELECT id FROM "${table}" WHERE integer_roles @> ARRAY[$1]`,
113 [`2`],
114 ),
115 ).rejects.toMatchObject({ code: `42883` })
116 })
117})