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

sql-compiler.test.ts

660 lines22.7 KB

1import { describe, expect, it } from 'vitest'
2import { compileSQL } from '../src/sql-compiler'
3import type { IR } from '@tanstack/db'
4​
5// Helper to create a value expression
6function val<T>(value: T): IR.BasicExpression<T> {
7 return { type: `val`, value } as IR.BasicExpression<T>
8}
9​
10// Helper to create a reference expression
11function ref(...path: Array<string>): IR.BasicExpression {
12 return { type: `ref`, path } as IR.BasicExpression
14​
15// Helper to create a function expression
16​
17function func(name: string, args: Array<any>): IR.BasicExpression<boolean> {
18 return { type: `func`, name, args } as IR.BasicExpression<boolean>
20​
21describe(`sql-compiler`, () => {
22 describe(`compileSQL`, () => {
23 describe(`basic where clauses`, () => {
24 it(`should compile eq with string value`, () => {
25 const result = compileSQL({
26 where: func(`eq`, [ref(`name`), val(`John`)]),
27 })
28 expect(result.where).toBe(`"name" = $1`)
29 expect(result.params).toEqual({ '1': `John` })
30 })
31​
32 it(`should compile eq with number value`, () => {
33 const result = compileSQL({
34 where: func(`eq`, [ref(`age`), val(25)]),
35 })
36 expect(result.where).toBe(`"age" = $1`)
37 expect(result.params).toEqual({ '1': `25` })
38 })
39​
40 it(`should compile gt operator`, () => {
41 const result = compileSQL({
42 where: func(`gt`, [ref(`age`), val(18)]),
43 })
44 expect(result.where).toBe(`"age" > $1`)
45 expect(result.params).toEqual({ '1': `18` })
46 })
47​
48 it(`should compile lt operator`, () => {
49 const result = compileSQL({
50 where: func(`lt`, [ref(`price`), val(100)]),
51 })
52 expect(result.where).toBe(`"price" < $1`)
53 expect(result.params).toEqual({ '1': `100` })
54 })
55​
56 it(`should compile gte operator`, () => {
57 const result = compileSQL({
58 where: func(`gte`, [ref(`quantity`), val(10)]),
59 })
60 expect(result.where).toBe(`"quantity" >= $1`)
61 expect(result.params).toEqual({ '1': `10` })
62 })
63​
64 it(`should compile lte operator`, () => {
65 const result = compileSQL({
66 where: func(`lte`, [ref(`rating`), val(5)]),
67 })
68 expect(result.where).toBe(`"rating" <= $1`)
69 expect(result.params).toEqual({ '1': `5` })
70 })
71​
72 it.each([
73 [`gt`, false, `left`, `("enabled") <> ("enabled")`],
74 [`gt`, false, `right`, `("enabled") = TRUE`],
75 [`gt`, true, `left`, `("enabled") = FALSE`],
76 [`gt`, true, `right`, `("enabled") <> ("enabled")`],
77 [`gte`, false, `left`, `("enabled") = FALSE`],
78 [`gte`, false, `right`, `("enabled") = ("enabled")`],
79 [`gte`, true, `left`, `("enabled") = ("enabled")`],
80 [`gte`, true, `right`, `("enabled") = TRUE`],
81 [`lt`, false, `left`, `("enabled") = TRUE`],
82 [`lt`, false, `right`, `("enabled") <> ("enabled")`],
83 [`lt`, true, `left`, `("enabled") <> ("enabled")`],
84 [`lt`, true, `right`, `("enabled") = FALSE`],
85 [`lte`, false, `left`, `("enabled") = ("enabled")`],
86 [`lte`, false, `right`, `("enabled") = FALSE`],
87 [`lte`, true, `left`, `("enabled") = TRUE`],
88 [`lte`, true, `right`, `("enabled") = ("enabled")`],
89 ] as const)(
90 `folds boolean %s with %s on the %s`,
91 (operator, literal, literalSide, expected) => {
92 const column = ref(`enabled`)
93 const value = val(literal)
94 const args =
95 literalSide === `left` ? [value, column] : [column, value]
96 const result = compileSQL({ where: func(operator, args) })
97​
98 expect(result.where).toBe(expected)
99 expect(result.params).toEqual({})
100 },
101 )
102​
103 // Regression test for https://github.com/TanStack/db/issues/1147
104 it(`should compile eq with empty string value`, () => {
105 const result = compileSQL({
106 where: func(`eq`, [ref(`status`), val(``)]),
107 })
108 expect(result.where).toBe(`"status" = $1`)
109 expect(result.params).toEqual({ '1': `` })
110 })
111​
112 it(`should compile eq with empty string in AND clause`, () => {
113 const result = compileSQL({
114 where: func(`and`, [
115 func(`eq`, [ref(`projectId`), val(`uuid-123`)]),
116 func(`eq`, [ref(`status`), val(``)]),
117 ]),
118 })
119 expect(result.where).toBe(`"projectId" = $1 AND "status" = $2`)
120 expect(result.params).toEqual({ '1': `uuid-123`, '2': `` })
121 })
122​
123 it(`should handle multiple empty strings with correct param indices`, () => {
124 const result = compileSQL({
125 where: func(`and`, [
126 func(`eq`, [ref(`field1`), val(``)]),
127 func(`eq`, [ref(`field2`), val(``)]),
128 ]),
129 })
130 expect(result.where).toBe(`"field1" = $1 AND "field2" = $2`)
131 // Both empty strings should be present with correct indices
132 expect(result.params).toEqual({ '1': ``, '2': `` })
133 })
134​
135 it(`should compile like with empty string pattern`, () => {
136 const result = compileSQL({
137 where: func(`like`, [ref(`description`), val(``)]),
138 })
139 expect(result.where).toBe(`"description" LIKE $1`)
140 expect(result.params).toEqual({ '1': `` })
141 })
142​
143 it(`should compile ilike with empty string pattern`, () => {
144 const result = compileSQL({
145 where: func(`ilike`, [ref(`title`), val(``)]),
146 })
147 expect(result.where).toBe(`"title" ILIKE $1`)
148 expect(result.params).toEqual({ '1': `` })
149 })
150 })
151​
152 describe(`array membership`, () => {
153 it(`uses containment for a scalar value in an array-valued reference`, () => {
154 const result = compileSQL({
155 where: func(`in`, [val(`admin`), ref(`roles`)]),
156 })
157​
158 expect(result.where).toBe(
159 `$1 = ANY("roles") AND "roles" @> ARRAY[$1] AND "roles" IS NOT NULL`,
160 )
161 expect(result.params).toEqual({ '1': `admin` })
162 })
163​
164 it(`uses ANY for compatible reference-to-array membership`, () => {
165 const result = compileSQL({
166 where: func(`in`, [ref(`requiredRole`), ref(`roles`)]),
167 })
168​
169 expect(result.where).toBe(`"requiredRole" = ANY("roles")`)
170 expect(result.params).toEqual({})
171 })
172​
173 it(`uses ANY for a scalar reference in a literal list`, () => {
174 const result = compileSQL({
175 where: func(`in`, [ref(`status`), val([`active`, `pending`])]),
176 })
177​
178 expect(result.where).toBe(`"status" = ANY($1)`)
179 expect(result.params).toEqual({ '1': `{"active","pending"}` })
180 })
181​
182 it(`rejects nullish membership operands before binding parameters`, () => {
183 const invalidExpressions = [
184 func(`in`, [val(null), ref(`roles`)]),
185 func(`in`, [val(undefined), ref(`roles`)]),
186 func(`in`, [ref(`status`), val(null)]),
187 func(`in`, [ref(`status`), val(undefined)]),
188 ]
189​
190 for (const where of invalidExpressions) {
191 expect(() => compileSQL({ where })).toThrow(
192 `Cannot use null/undefined value with 'in' operator`,
193 )
194 }
195 })
196​
197 it(`rejects an array-valued element`, () => {
198 for (const array of [ref(`roles`), val([`admin`, `editor`])]) {
199 expect(() =>
200 compileSQL({
201 where: func(`in`, [val([`admin`, `editor`]), array]),
202 }),
203 ).toThrow(/array-valued.+left|left.+array-valued/i)
204 }
205 })
206 })
207​
208 describe(`unsupported nested references`, () => {
209 it(`fails before emitting unsupported subset predicates`, () => {
210 for (const where of [
211 ref(`payload`, `enabled`),
212 func(`eq`, [ref(`payload`, `score`), val(10)]),
213 func(`isNull`, [ref(`payload`, `nullable`)]),
214 func(`in`, [val(`admin`), ref(`payload`, `roles`)]),
215 func(`in`, [ref(`payload`, `score`), val([])]),
216 func(`in`, [ref(`payload`, `score`), val([null])]),
217 func(`in`, [ref(`payload`, `score`), val([1, `one`])]),
218 func(`in`, [ref(`payload`, `role`), ref(`roles`)]),
219 func(`upper`, [ref(`payload`, `name`)]),
220 func(`lower`, [ref(`payload`, `name`)]),
221 ]) {
222 expect(() => compileSQL({ where })).toThrow(
223 `Compiler can't handle nested properties: payload.`,
224 )
225 }
226 })
227​
228 it(`fails before emitting unsupported subset ordering`, () => {
229 expect(() =>
230 compileSQL({
231 orderBy: [
232 {
233 expression: ref(`payload`, `score`),
234 compareOptions: { direction: `asc`, nulls: `last` },
235 },
236 ],
237 }),
238 ).toThrow(`Compiler can't handle nested properties: payload.score`)
239 })
240 })
241​
242 describe(`compound where clauses`, () => {
243 it(`preserves boolean grouping beneath a comparison`, () => {
244 const result = compileSQL({
245 where: func(`eq`, [
246 func(`or`, [ref(`enabled`), ref(`visible`)]),
247 val(false),
248 ]),
249 })
250​
251 expect(result.where).toBe(`("enabled" OR "visible") = $1`)
252 expect(result.params).toEqual({ '1': `false` })
253 })
254​
255 it(`preserves nested boolean grouping`, () => {
256 const result = compileSQL({
257 where: func(`and`, [
258 func(`or`, [
259 func(`eq`, [ref(`status`), val(`active`)]),
260 func(`eq`, [ref(`status`), val(`pending`)]),
261 ]),
262 func(`eq`, [ref(`visible`), val(true)]),
263 ]),
264 })
265​
266 expect(result.where).toBe(
267 `("status" = $1 OR "status" = $2) AND "visible" = $3`,
268 )
269 })
270​
271 it(`should compile AND with two conditions`, () => {
272 const result = compileSQL({
273 where: func(`and`, [
274 func(`eq`, [ref(`projectId`), val(`uuid-123`)]),
275 func(`gt`, [ref(`name`), val(`cursor-value`)]),
276 ]),
277 })
278 // Note: 2-arg AND doesn't add parentheses around the operands
279 expect(result.where).toBe(`"projectId" = $1 AND "name" > $2`)
280 expect(result.params).toEqual({ '1': `uuid-123`, '2': `cursor-value` })
281 })
282​
283 it(`should compile AND with more than two conditions`, () => {
284 const result = compileSQL({
285 where: func(`and`, [
286 func(`eq`, [ref(`a`), val(`1`)]),
287 func(`eq`, [ref(`b`), val(`2`)]),
288 func(`eq`, [ref(`c`), val(`3`)]),
289 ]),
290 })
291 // >2 args adds parentheses
292 expect(result.where).toBe(`"a" = $1 AND "b" = $2 AND "c" = $3`)
293 expect(result.params).toEqual({ '1': `1`, '2': `2`, '3': `3` })
294 })
295​
296 it(`should compile OR with two conditions`, () => {
297 const result = compileSQL({
298 where: func(`or`, [
299 func(`eq`, [ref(`status`), val(`active`)]),
300 func(`eq`, [ref(`status`), val(`pending`)]),
301 ]),
302 })
303 expect(result.where).toBe(`"status" = $1 OR "status" = $2`)
304 expect(result.params).toEqual({ '1': `active`, '2': `pending` })
305 })
306 })
307​
308 describe(`null/undefined value handling`, () => {
309 it(`should throw error for eq(col, null)`, () => {
310 // Users should use isNull() instead of eq(col, null)
311 expect(() =>
312 compileSQL({
313 where: func(`eq`, [ref(`deletedAt`), val(null)]),
314 }),
315 ).toThrow(`Cannot use null/undefined value with 'eq' operator`)
316 })
317​
318 it(`should throw error for eq(col, undefined)`, () => {
319 expect(() =>
320 compileSQL({
321 where: func(`eq`, [ref(`deletedAt`), val(undefined)]),
322 }),
323 ).toThrow(`Cannot use null/undefined value with 'eq' operator`)
324 })
325​
326 it(`should throw error for eq(null, col) (reversed order)`, () => {
327 expect(() =>
328 compileSQL({
329 where: func(`eq`, [val(null), ref(`name`)]),
330 }),
331 ).toThrow(`Cannot use null/undefined value with 'eq' operator`)
332 })
333​
334 it(`should throw error for gt with null value`, () => {
335 expect(() =>
336 compileSQL({
337 where: func(`gt`, [ref(`age`), val(null)]),
338 }),
339 ).toThrow(`Cannot use null/undefined value with 'gt' operator`)
340 })
341​
342 it(`should throw error for lt with undefined value`, () => {
343 expect(() =>
344 compileSQL({
345 where: func(`lt`, [ref(`age`), val(undefined)]),
346 }),
347 ).toThrow(`Cannot use null/undefined value with 'lt' operator`)
348 })
349​
350 it(`should throw error for gte with null value`, () => {
351 expect(() =>
352 compileSQL({
353 where: func(`gte`, [ref(`price`), val(null)]),
354 }),
355 ).toThrow(`Cannot use null/undefined value with 'gte' operator`)
356 })
357​
358 it(`should throw error for lte with null value`, () => {
359 expect(() =>
360 compileSQL({
361 where: func(`lte`, [ref(`rating`), val(null)]),
362 }),
363 ).toThrow(`Cannot use null/undefined value with 'lte' operator`)
364 })
365​
366 it(`should throw error for like with null value`, () => {
367 expect(() =>
368 compileSQL({
369 where: func(`like`, [ref(`name`), val(null)]),
370 }),
371 ).toThrow(`Cannot use null/undefined value with 'like' operator`)
372 })
373​
374 it(`should throw error for ilike with null value`, () => {
375 expect(() =>
376 compileSQL({
377 where: func(`ilike`, [ref(`name`), val(null)]),
378 }),
379 ).toThrow(`Cannot use null/undefined value with 'ilike' operator`)
380 })
381​
382 it(`should throw error for eq(col, null) in AND clause`, () => {
383 expect(() =>
384 compileSQL({
385 where: func(`and`, [
386 func(`eq`, [ref(`projectId`), val(`uuid-123`)]),
387 func(`eq`, [ref(`deletedAt`), val(null)]),
388 ]),
389 }),
390 ).toThrow(`Cannot use null/undefined value with 'eq' operator`)
391 })
392​
393 it(`should throw error for eq(col, null) in mixed conditions`, () => {
394 expect(() =>
395 compileSQL({
396 where: func(`and`, [
397 func(`eq`, [ref(`status`), val(`active`)]),
398 func(`eq`, [ref(`archivedAt`), val(null)]),
399 func(`gt`, [ref(`createdAt`), val(`2024-01-01`)]),
400 ]),
401 }),
402 ).toThrow(`Cannot use null/undefined value with 'eq' operator`)
403 })
404​
405 it(`should not include params for null values in complex queries`, () => {
406 // This test simulates the bug scenario: a query with both valid params and null
407 // Before the fix, this would generate:
408 // where: "projectId" = $1 AND "name" > $2
409 // params: { "1": "uuid" } // missing $2!
410 // After the fix, gt(name, null) throws an error
411 expect(() =>
412 compileSQL({
413 where: func(`and`, [
414 func(`eq`, [ref(`projectId`), val(`uuid`)]),
415 func(`gt`, [ref(`name`), val(null)]),
416 ]),
417 }),
418 ).toThrow(`Cannot use null/undefined value with 'gt' operator`)
419 })
420​
421 it(`should throw error for eq(null, null)`, () => {
422 // Both args are null - this is nonsensical and would cause missing params
423 expect(() =>
424 compileSQL({
425 where: func(`eq`, [val(null), val(null)]),
426 }),
427 ).toThrow(`Cannot use null/undefined value with 'eq' operator`)
428 })
429​
430 it(`should throw error for eq(null, literal)`, () => {
431 // Comparing null to a literal is nonsensical (always evaluates to UNKNOWN)
432 expect(() =>
433 compileSQL({
434 where: func(`eq`, [val(null), val(42)]),
435 }),
436 ).toThrow(`Cannot use null/undefined value with 'eq' operator`)
437 })
438​
439 it(`should throw error for eq(col, null) - use isNull(col) instead`, () => {
440 // eq(col, null) should throw an error
441 // Users should use isNull(col) which works correctly
442 expect(() =>
443 compileSQL({
444 where: func(`eq`, [ref(`email`), val(null)]),
445 }),
446 ).toThrow(`Cannot use null/undefined value with 'eq' operator`)
447​
448 // isNull(col) should work correctly
449 const isNullResult = compileSQL({
450 where: func(`isNull`, [ref(`email`)]),
451 })
452 expect(isNullResult.where).toBe(`"email" IS NULL`)
453 expect(isNullResult.params).toEqual({})
454 })
455​
456 it(`should throw error for eq(col, null) in OR clause`, () => {
457 expect(() =>
458 compileSQL({
459 where: func(`or`, [
460 func(`eq`, [ref(`deletedAt`), val(null)]),
461 func(`eq`, [ref(`status`), val(`active`)]),
462 ]),
463 }),
464 ).toThrow(`Cannot use null/undefined value with 'eq' operator`)
465 })
466 })
467​
468 describe(`isNull/isUndefined operators`, () => {
469 it(`should compile isNull correctly`, () => {
470 const result = compileSQL({
471 where: func(`isNull`, [ref(`deletedAt`)]),
472 })
473 expect(result.where).toBe(`"deletedAt" IS NULL`)
474 expect(result.params).toEqual({})
475 })
476​
477 it(`should compile isUndefined correctly`, () => {
478 const result = compileSQL({
479 where: func(`isUndefined`, [ref(`field`)]),
480 })
481 expect(result.where).toBe(`"field" IS NULL`)
482 expect(result.params).toEqual({})
483 })
484​
485 it(`should compile NOT isNull correctly`, () => {
486 const result = compileSQL({
487 where: func(`not`, [func(`isNull`, [ref(`name`)])]),
488 })
489 expect(result.where).toBe(`"name" IS NOT NULL`)
490 expect(result.params).toEqual({})
491 })
492​
493 it(`validates negated null-check arity before simplifying it`, () => {
494 expect(() =>
495 compileSQL({
496 where: func(`not`, [func(`isNull`, [ref(`name`)]), val(true)]),
497 }),
498 ).toThrow(`NOT expects 1 argument`)
499​
500 expect(() =>
501 compileSQL({
502 where: func(`not`, [
503 func(`isNull`, [ref(`name`), ref(`fallback`)]),
504 ]),
505 }),
506 ).toThrow(`isNull expects 1 argument`)
507 })
508​
509 it(`binds negated expression null checks once`, () => {
510 const result = compileSQL({
511 where: func(`not`, [
512 func(`isNull`, [func(`eq`, [ref(`enabled`), val(true)])]),
513 ]),
514 })
515​
516 expect(result.where).toBe(`("enabled" = $1) IS NOT NULL`)
517 expect(result.params).toEqual({ '1': `true` })
518 })
519 })
520​
521 describe(`empty where clause`, () => {
522 it(`should add true = true when no where clause`, () => {
523 const result = compileSQL({})
524 expect(result.where).toBe(`true = true`)
525 expect(result.params).toEqual({})
526 })
527 })
528​
529 describe(`limit`, () => {
530 it(`should include limit in result`, () => {
531 const result = compileSQL({ limit: 10 })
532 expect(result.limit).toBe(10)
533 })
534 })
535​
536 describe(`column name encoding (camelCase to snake_case)`, () => {
537 // Helper to simulate snakeCamelMapper's encode function
538 const camelToSnake = (str: string): string =>
539 str.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`)
540​
541 it(`should encode column names in where clause when encoder is provided`, () => {
542 const result = compileSQL(
543 {
544 where: func(`eq`, [ref(`programTemplateId`), val(`uuid-123`)]),
545 },
546 { encodeColumnName: camelToSnake },
547 )
548 expect(result.where).toBe(`"program_template_id" = $1`)
549 expect(result.params).toEqual({ '1': `uuid-123` })
550 })
551​
552 it(`escapes quotes introduced by a column encoder`, () => {
553 const result = compileSQL(
554 { where: func(`eq`, [ref(`payload`), val(`gold`)]) },
555 { encodeColumnName: (name) => `mapped"${name}` },
556 )
557​
558 expect(result.where).toBe(`"mapped""payload" = $1`)
559 })
560​
561 it(`should encode column names in compound where clauses`, () => {
562 const result = compileSQL(
563 {
564 where: func(`and`, [
565 func(`eq`, [ref(`programTemplateId`), val(`uuid-123`)]),
566 func(`gt`, [ref(`createdAt`), val(`2024-01-01`)]),
567 ]),
568 },
569 { encodeColumnName: camelToSnake },
570 )
571 expect(result.where).toBe(
572 `"program_template_id" = $1 AND "created_at" > $2`,
573 )
574 expect(result.params).toEqual({ '1': `uuid-123`, '2': `2024-01-01` })
575 })
576​
577 it(`should encode column names in orderBy clause`, () => {
578 const result = compileSQL(
579 {
580 orderBy: [
581 {
582 expression: ref(`createdAt`),
583 compareOptions: { direction: `desc`, nulls: `last` },
584 },
585 ],
586 },
587 { encodeColumnName: camelToSnake },
588 )
589 expect(result.orderBy).toBe(`"created_at" DESC NULLS LAST`)
590 })
591​
592 it(`should encode column names in isNull expressions`, () => {
593 const result = compileSQL(
594 {
595 where: func(`isNull`, [ref(`deletedAt`)]),
596 },
597 { encodeColumnName: camelToSnake },
598 )
599 expect(result.where).toBe(`"deleted_at" IS NULL`)
600 })
601​
602 it(`should encode column names in NOT isNull expressions`, () => {
603 const result = compileSQL(
604 {
605 where: func(`not`, [func(`isNull`, [ref(`archivedAt`)])]),
606 },
607 { encodeColumnName: camelToSnake },
608 )
609 expect(result.where).toBe(`"archived_at" IS NOT NULL`)
610 })
611​
612 it(`should not transform column names when no encoder is provided`, () => {
613 const result = compileSQL({
614 where: func(`eq`, [ref(`programTemplateId`), val(`uuid-123`)]),
615 })
616 // Without encoder, camelCase name is preserved
617 expect(result.where).toBe(`"programTemplateId" = $1`)
618 })
619​
620 it(`should handle complex nested expressions with encoding`, () => {
621 const result = compileSQL(
622 {
623 where: func(`and`, [
624 func(`eq`, [ref(`userId`), val(`user-1`)]),
625 func(`or`, [
626 func(`eq`, [ref(`accountType`), val(`premium`)]),
627 func(`gte`, [ref(`totalSpend`), val(1000)]),
628 ]),
629 ]),
630 },
631 { encodeColumnName: camelToSnake },
632 )
633 expect(result.where).toBe(
634 `"user_id" = $1 AND ("account_type" = $2 OR "total_spend" >= $3)`,
635 )
636 })
637​
638 it(`should encode column names in LIKE expressions`, () => {
639 const result = compileSQL(
640 {
641 where: func(`ilike`, [ref(`firstName`), val(`%john%`)]),
642 },
643 { encodeColumnName: camelToSnake },
644 )
645 expect(result.where).toBe(`"first_name" ILIKE $1`)
646 })
647​
648 it(`should work with already snake_case names (identity transform)`, () => {
649 const result = compileSQL(
650 {
651 where: func(`eq`, [ref(`user_id`), val(`123`)]),
652 },
653 { encodeColumnName: camelToSnake },
654 )
655 // snake_case input remains snake_case
656 expect(result.where).toBe(`"user_id" = $1`)
657 })
658 })
659 })
660})