Open History to see the last commit
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
13}
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>
19}
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 // Regression test for https://github.com/TanStack/db/issues/1147
73 it(`should compile eq with empty string value`, () => {
74 const result = compileSQL({
75 where: func(`eq`, [ref(`status`), val(``)]),
76 })
77 expect(result.where).toBe(`"status" = $1`)
78 expect(result.params).toEqual({ '1': `` })
79 })
80
81 it(`should compile eq with empty string in AND clause`, () => {
82 const result = compileSQL({
83 where: func(`and`, [
84 func(`eq`, [ref(`projectId`), val(`uuid-123`)]),
85 func(`eq`, [ref(`status`), val(``)]),
86 ]),
87 })
88 expect(result.where).toBe(`"projectId" = $1 AND "status" = $2`)
89 expect(result.params).toEqual({ '1': `uuid-123`, '2': `` })
90 })
91
92 it(`should handle multiple empty strings with correct param indices`, () => {
93 const result = compileSQL({
94 where: func(`and`, [
95 func(`eq`, [ref(`field1`), val(``)]),
96 func(`eq`, [ref(`field2`), val(``)]),
97 ]),
98 })
99 expect(result.where).toBe(`"field1" = $1 AND "field2" = $2`)
100 // Both empty strings should be present with correct indices
101 expect(result.params).toEqual({ '1': ``, '2': `` })
102 })
103
104 it(`should compile like with empty string pattern`, () => {
105 const result = compileSQL({
106 where: func(`like`, [ref(`description`), val(``)]),
107 })
108 expect(result.where).toBe(`"description" LIKE $1`)
109 expect(result.params).toEqual({ '1': `` })
110 })
111
112 it(`should compile ilike with empty string pattern`, () => {
113 const result = compileSQL({
114 where: func(`ilike`, [ref(`title`), val(``)]),
115 })
116 expect(result.where).toBe(`"title" ILIKE $1`)
117 expect(result.params).toEqual({ '1': `` })
118 })
119 })
120
121 describe(`compound where clauses`, () => {
122 it(`should compile AND with two conditions`, () => {
123 const result = compileSQL({
124 where: func(`and`, [
125 func(`eq`, [ref(`projectId`), val(`uuid-123`)]),
126 func(`gt`, [ref(`name`), val(`cursor-value`)]),
127 ]),
128 })
129 // Note: 2-arg AND doesn't add parentheses around the operands
130 expect(result.where).toBe(`"projectId" = $1 AND "name" > $2`)
131 expect(result.params).toEqual({ '1': `uuid-123`, '2': `cursor-value` })
132 })
133
134 it(`should compile AND with more than two conditions`, () => {
135 const result = compileSQL({
136 where: func(`and`, [
137 func(`eq`, [ref(`a`), val(`1`)]),
138 func(`eq`, [ref(`b`), val(`2`)]),
139 func(`eq`, [ref(`c`), val(`3`)]),
140 ]),
141 })
142 // >2 args adds parentheses
143 expect(result.where).toBe(`("a" = $1) AND ("b" = $2) AND ("c" = $3)`)
144 expect(result.params).toEqual({ '1': `1`, '2': `2`, '3': `3` })
145 })
146
147 it(`should compile OR with two conditions`, () => {
148 const result = compileSQL({
149 where: func(`or`, [
150 func(`eq`, [ref(`status`), val(`active`)]),
151 func(`eq`, [ref(`status`), val(`pending`)]),
152 ]),
153 })
154 expect(result.where).toBe(`"status" = $1 OR "status" = $2`)
155 expect(result.params).toEqual({ '1': `active`, '2': `pending` })
156 })
157 })
158
159 describe(`null/undefined value handling`, () => {
160 it(`should throw error for eq(col, null)`, () => {
161 // Users should use isNull() instead of eq(col, null)
162 expect(() =>
163 compileSQL({
164 where: func(`eq`, [ref(`deletedAt`), val(null)]),
165 }),
166 ).toThrow(`Cannot use null/undefined value with 'eq' operator`)
167 })
168
169 it(`should throw error for eq(col, undefined)`, () => {
170 expect(() =>
171 compileSQL({
172 where: func(`eq`, [ref(`deletedAt`), val(undefined)]),
173 }),
174 ).toThrow(`Cannot use null/undefined value with 'eq' operator`)
175 })
176
177 it(`should throw error for eq(null, col) (reversed order)`, () => {
178 expect(() =>
179 compileSQL({
180 where: func(`eq`, [val(null), ref(`name`)]),
181 }),
182 ).toThrow(`Cannot use null/undefined value with 'eq' operator`)
183 })
184
185 it(`should throw error for gt with null value`, () => {
186 expect(() =>
187 compileSQL({
188 where: func(`gt`, [ref(`age`), val(null)]),
189 }),
190 ).toThrow(`Cannot use null/undefined value with 'gt' operator`)
191 })
192
193 it(`should throw error for lt with undefined value`, () => {
194 expect(() =>
195 compileSQL({
196 where: func(`lt`, [ref(`age`), val(undefined)]),
197 }),
198 ).toThrow(`Cannot use null/undefined value with 'lt' operator`)
199 })
200
201 it(`should throw error for gte with null value`, () => {
202 expect(() =>
203 compileSQL({
204 where: func(`gte`, [ref(`price`), val(null)]),
205 }),
206 ).toThrow(`Cannot use null/undefined value with 'gte' operator`)
207 })
208
209 it(`should throw error for lte with null value`, () => {
210 expect(() =>
211 compileSQL({
212 where: func(`lte`, [ref(`rating`), val(null)]),
213 }),
214 ).toThrow(`Cannot use null/undefined value with 'lte' operator`)
215 })
216
217 it(`should throw error for like with null value`, () => {
218 expect(() =>
219 compileSQL({
220 where: func(`like`, [ref(`name`), val(null)]),
221 }),
222 ).toThrow(`Cannot use null/undefined value with 'like' operator`)
223 })
224
225 it(`should throw error for ilike with null value`, () => {
226 expect(() =>
227 compileSQL({
228 where: func(`ilike`, [ref(`name`), val(null)]),
229 }),
230 ).toThrow(`Cannot use null/undefined value with 'ilike' operator`)
231 })
232
233 it(`should throw error for eq(col, null) in AND clause`, () => {
234 expect(() =>
235 compileSQL({
236 where: func(`and`, [
237 func(`eq`, [ref(`projectId`), val(`uuid-123`)]),
238 func(`eq`, [ref(`deletedAt`), val(null)]),
239 ]),
240 }),
241 ).toThrow(`Cannot use null/undefined value with 'eq' operator`)
242 })
243
244 it(`should throw error for eq(col, null) in mixed conditions`, () => {
245 expect(() =>
246 compileSQL({
247 where: func(`and`, [
248 func(`eq`, [ref(`status`), val(`active`)]),
249 func(`eq`, [ref(`archivedAt`), val(null)]),
250 func(`gt`, [ref(`createdAt`), val(`2024-01-01`)]),
251 ]),
252 }),
253 ).toThrow(`Cannot use null/undefined value with 'eq' operator`)
254 })
255
256 it(`should not include params for null values in complex queries`, () => {
257 // This test simulates the bug scenario: a query with both valid params and null
258 // Before the fix, this would generate:
259 // where: "projectId" = $1 AND "name" > $2
260 // params: { "1": "uuid" } // missing $2!
261 // After the fix, gt(name, null) throws an error
262 expect(() =>
263 compileSQL({
264 where: func(`and`, [
265 func(`eq`, [ref(`projectId`), val(`uuid`)]),
266 func(`gt`, [ref(`name`), val(null)]),
267 ]),
268 }),
269 ).toThrow(`Cannot use null/undefined value with 'gt' operator`)
270 })
271
272 it(`should throw error for eq(null, null)`, () => {
273 // Both args are null - this is nonsensical and would cause missing params
274 expect(() =>
275 compileSQL({
276 where: func(`eq`, [val(null), val(null)]),
277 }),
278 ).toThrow(`Cannot use null/undefined value with 'eq' operator`)
279 })
280
281 it(`should throw error for eq(null, literal)`, () => {
282 // Comparing null to a literal is nonsensical (always evaluates to UNKNOWN)
283 expect(() =>
284 compileSQL({
285 where: func(`eq`, [val(null), val(42)]),
286 }),
287 ).toThrow(`Cannot use null/undefined value with 'eq' operator`)
288 })
289
290 it(`should throw error for eq(col, null) - use isNull(col) instead`, () => {
291 // eq(col, null) should throw an error
292 // Users should use isNull(col) which works correctly
293 expect(() =>
294 compileSQL({
295 where: func(`eq`, [ref(`email`), val(null)]),
296 }),
297 ).toThrow(`Cannot use null/undefined value with 'eq' operator`)
298
299 // isNull(col) should work correctly
300 const isNullResult = compileSQL({
301 where: func(`isNull`, [ref(`email`)]),
302 })
303 expect(isNullResult.where).toBe(`"email" IS NULL`)
304 expect(isNullResult.params).toEqual({})
305 })
306
307 it(`should throw error for eq(col, null) in OR clause`, () => {
308 expect(() =>
309 compileSQL({
310 where: func(`or`, [
311 func(`eq`, [ref(`deletedAt`), val(null)]),
312 func(`eq`, [ref(`status`), val(`active`)]),
313 ]),
314 }),
315 ).toThrow(`Cannot use null/undefined value with 'eq' operator`)
316 })
317 })
318
319 describe(`isNull/isUndefined operators`, () => {
320 it(`should compile isNull correctly`, () => {
321 const result = compileSQL({
322 where: func(`isNull`, [ref(`deletedAt`)]),
323 })
324 expect(result.where).toBe(`"deletedAt" IS NULL`)
325 expect(result.params).toEqual({})
326 })
327
328 it(`should compile isUndefined correctly`, () => {
329 const result = compileSQL({
330 where: func(`isUndefined`, [ref(`field`)]),
331 })
332 expect(result.where).toBe(`"field" IS NULL`)
333 expect(result.params).toEqual({})
334 })
335
336 it(`should compile NOT isNull correctly`, () => {
337 const result = compileSQL({
338 where: func(`not`, [func(`isNull`, [ref(`name`)])]),
339 })
340 expect(result.where).toBe(`"name" IS NOT NULL`)
341 expect(result.params).toEqual({})
342 })
343 })
344
345 describe(`empty where clause`, () => {
346 it(`should add true = true when no where clause`, () => {
347 const result = compileSQL({})
348 expect(result.where).toBe(`true = true`)
349 expect(result.params).toEqual({})
350 })
351 })
352
353 describe(`limit`, () => {
354 it(`should include limit in result`, () => {
355 const result = compileSQL({ limit: 10 })
356 expect(result.limit).toBe(10)
357 })
358 })
359
360 describe(`column name encoding (camelCase to snake_case)`, () => {
361 // Helper to simulate snakeCamelMapper's encode function
362 const camelToSnake = (str: string): string =>
363 str.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`)
364
365 it(`should encode column names in where clause when encoder is provided`, () => {
366 const result = compileSQL(
367 {
368 where: func(`eq`, [ref(`programTemplateId`), val(`uuid-123`)]),
369 },
370 { encodeColumnName: camelToSnake },
371 )
372 expect(result.where).toBe(`"program_template_id" = $1`)
373 expect(result.params).toEqual({ '1': `uuid-123` })
374 })
375
376 it(`should encode column names in compound where clauses`, () => {
377 const result = compileSQL(
378 {
379 where: func(`and`, [
380 func(`eq`, [ref(`programTemplateId`), val(`uuid-123`)]),
381 func(`gt`, [ref(`createdAt`), val(`2024-01-01`)]),
382 ]),
383 },
384 { encodeColumnName: camelToSnake },
385 )
386 expect(result.where).toBe(
387 `"program_template_id" = $1 AND "created_at" > $2`,
388 )
389 expect(result.params).toEqual({ '1': `uuid-123`, '2': `2024-01-01` })
390 })
391
392 it(`should encode column names in orderBy clause`, () => {
393 const result = compileSQL(
394 {
395 orderBy: [
396 {
397 expression: ref(`createdAt`),
398 compareOptions: { direction: `desc`, nulls: `last` },
399 },
400 ],
401 },
402 { encodeColumnName: camelToSnake },
403 )
404 expect(result.orderBy).toBe(`"created_at" DESC NULLS LAST`)
405 })
406
407 it(`should encode column names in isNull expressions`, () => {
408 const result = compileSQL(
409 {
410 where: func(`isNull`, [ref(`deletedAt`)]),
411 },
412 { encodeColumnName: camelToSnake },
413 )
414 expect(result.where).toBe(`"deleted_at" IS NULL`)
415 })
416
417 it(`should encode column names in NOT isNull expressions`, () => {
418 const result = compileSQL(
419 {
420 where: func(`not`, [func(`isNull`, [ref(`archivedAt`)])]),
421 },
422 { encodeColumnName: camelToSnake },
423 )
424 expect(result.where).toBe(`"archived_at" IS NOT NULL`)
425 })
426
427 it(`should not transform column names when no encoder is provided`, () => {
428 const result = compileSQL({
429 where: func(`eq`, [ref(`programTemplateId`), val(`uuid-123`)]),
430 })
431 // Without encoder, camelCase name is preserved
432 expect(result.where).toBe(`"programTemplateId" = $1`)
433 })
434
435 it(`should handle complex nested expressions with encoding`, () => {
436 const result = compileSQL(
437 {
438 where: func(`and`, [
439 func(`eq`, [ref(`userId`), val(`user-1`)]),
440 func(`or`, [
441 func(`eq`, [ref(`accountType`), val(`premium`)]),
442 func(`gte`, [ref(`totalSpend`), val(1000)]),
443 ]),
444 ]),
445 },
446 { encodeColumnName: camelToSnake },
447 )
448 expect(result.where).toBe(
449 `"user_id" = $1 AND "account_type" = $2 OR "total_spend" >= $3`,
450 )
451 })
452
453 it(`should encode column names in LIKE expressions`, () => {
454 const result = compileSQL(
455 {
456 where: func(`ilike`, [ref(`firstName`), val(`%john%`)]),
457 },
458 { encodeColumnName: camelToSnake },
459 )
460 expect(result.where).toBe(`"first_name" ILIKE $1`)
461 })
462
463 it(`should work with already snake_case names (identity transform)`, () => {
464 const result = compileSQL(
465 {
466 where: func(`eq`, [ref(`user_id`), val(`123`)]),
467 },
468 { encodeColumnName: camelToSnake },
469 )
470 // snake_case input remains snake_case
471 expect(result.where).toBe(`"user_id" = $1`)
472 })
473 })
474 })
475})