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

sql-compiler.ts

370 lines11.1 KB

1import { serialize } from './pg-serializer'
2import type { SubsetParams } from '@electric-sql/client'
3import type { IR, LoadSubsetOptions } from '@tanstack/db'
4​
5export type CompiledSqlRecord = Omit<SubsetParams, `params`> & {
6 params?: Array<unknown>
7}
8​
9/**
10 * Optional function to encode column names (e.g., camelCase to snake_case)
11 * This is typically the `encode` function from a columnMapper
12 */
13export type ColumnEncoder = (columnName: string) => string
14​
15/**
16 * Options for SQL compilation
17 */
18export interface CompileSQLOptions {
19 /**
20 * Optional function to encode column names before quoting.
21 * Used to transform property names (e.g., camelCase) to database column names (e.g., snake_case).
22 * This should be the `encode` function from shapeOptions.columnMapper.
23 */
24 encodeColumnName?: ColumnEncoder
26​
27export function compileSQL<T>(
28 options: LoadSubsetOptions,
29 compileOptions?: CompileSQLOptions,
30): SubsetParams {
31 const { where, orderBy, limit } = options
32 const encodeColumnName = compileOptions?.encodeColumnName
33​
34 const params: Array<T> = []
35 const compiledSQL: CompiledSqlRecord = { params }
36​
37 if (where) {
38 // TODO: this only works when the where expression's PropRefs directly reference a column of the collection
39 // doesn't work if it goes through aliases because then we need to know the entire query to be able to follow the reference until the base collection (cf. followRef function)
40 compiledSQL.where = compileBasicExpression(where, params, encodeColumnName)
41 }
42​
43 if (orderBy) {
44 compiledSQL.orderBy = compileOrderBy(orderBy, params, encodeColumnName)
45 }
46​
47 if (limit) {
48 compiledSQL.limit = limit
49 }
50​
51 // WORKAROUND for Electric bug: Empty subset requests don't load data
52 // Add dummy "true = true" predicate when there's no where clause
53 // This is always true so doesn't filter data, just tricks Electric into loading
54 if (!where) {
55 compiledSQL.where = `true = true`
56 }
57​
58 // Serialize the values in the params array into PG formatted strings
59 // and transform the array into a Record<string, string>
60 const paramsRecord = params.reduce(
61 (acc, param, index) => {
62 const serialized = serialize(param)
63 // Empty strings are valid query values (e.g., WHERE column = '')
64 // Only omit null/undefined values from params
65 if (param != null) {
66 acc[`${index + 1}`] = serialized
67 }
68 return acc
69 },
70 {} as Record<string, string>,
71 )
72​
73 return {
74 ...compiledSQL,
75 params: paramsRecord,
76 }
78​
79/**
80 * Quote PostgreSQL identifiers to handle mixed case column names correctly.
81 * Electric/Postgres requires quotes for case-sensitive identifiers.
82 * @param name - The identifier to quote
83 * @param encodeColumnName - Optional function to encode the column name before quoting (e.g., camelCase to snake_case)
84 * @returns The quoted identifier
85 */
86function quoteIdentifier(
87 name: string,
88 encodeColumnName?: ColumnEncoder,
89): string {
90 const columnName = encodeColumnName ? encodeColumnName(name) : name
91 return `"${columnName.replace(/"/g, `""`)}"`
93​
94/**
95 * Compiles the expression to a SQL string and mutates the params array with the values.
96 * @param exp - The expression to compile
97 * @param params - The params array
98 * @param encodeColumnName - Optional function to encode column names (e.g., camelCase to snake_case)
99 * @returns The compiled SQL string
100 */
101function compileBasicExpression(
102 exp: IR.BasicExpression<unknown>,
103 params: Array<unknown>,
104 encodeColumnName?: ColumnEncoder,
105): string {
106 switch (exp.type) {
107 case `val`:
108 params.push(exp.value)
109 return `$${params.length}`
110 case `ref`:
111 if (exp.path.length !== 1) {
112 throw new Error(
113 `Compiler can't handle nested properties: ${exp.path.join(`.`)}`,
114 )
115 }
116 return quoteIdentifier(exp.path[0]!, encodeColumnName)
117 case `func`:
118 return compileFunction(exp, params, encodeColumnName)
119 default:
120 throw new Error(`Unknown expression type`)
121 }
123​
124function compileOrderBy(
125 orderBy: IR.OrderBy,
126 params: Array<unknown>,
127 encodeColumnName?: ColumnEncoder,
128): string {
129 const compiledOrderByClauses = orderBy.map((clause: IR.OrderByClause) =>
130 compileOrderByClause(clause, params, encodeColumnName),
131 )
132 return compiledOrderByClauses.join(`,`)
134​
135function compileOrderByClause(
136 clause: IR.OrderByClause,
137 params: Array<unknown>,
138 encodeColumnName?: ColumnEncoder,
139): string {
140 // FIXME: We should handle stringSort and locale.
141 // Correctly supporting them is tricky as it depends on Postgres' collation
142 const { expression, compareOptions } = clause
143 let sql = compileBasicExpression(expression, params, encodeColumnName)
144​
145 if (compareOptions.direction === `desc`) {
146 sql = `${sql} DESC`
147 }
148​
149 if (compareOptions.nulls === `first`) {
150 sql = `${sql} NULLS FIRST`
151 }
152​
153 if (compareOptions.nulls === `last`) {
154 sql = `${sql} NULLS LAST`
155 }
156​
157 return sql
159​
160/**
161 * Check if a BasicExpression represents a null/undefined value
162 */
163function isNullValue(exp: IR.BasicExpression<unknown>): boolean {
164 return exp.type === `val` && (exp.value === null || exp.value === undefined)
166​
167function compileFunction(
168 exp: IR.Func<unknown>,
169 params: Array<unknown> = [],
170 encodeColumnName?: ColumnEncoder,
171): string {
172 const { name, args } = exp
173​
174 const opName = getOpName(name)
175​
176 // Handle comparison operators with null/undefined values
177 // These would create invalid queries with missing params (e.g., "col = $1" with empty params)
178 // In SQL, all comparisons with NULL return UNKNOWN, so these are almost always mistakes
179 if (isComparisonOp(name)) {
180 const nullArgIndex = args.findIndex((arg: IR.BasicExpression) =>
181 isNullValue(arg),
182 )
183​
184 if (nullArgIndex !== -1) {
185 // All comparison operators (including eq) throw an error for null values
186 // Users should use isNull() or isUndefined() to check for null values
187 throw new Error(
188 `Cannot use null/undefined value with '${name}' operator. ` +
189 `Comparisons with null always evaluate to UNKNOWN in SQL. ` +
190 `Use isNull() or isUndefined() to check for null values, ` +
191 `or filter out null values before building the query.`,
192 )
193 }
194 }
195​
196 if (name === `not`) {
197 if (args.length !== 1) throw new Error(`NOT expects 1 argument`)
198 const arg = args[0]
199 if (
200 arg?.type === `func` &&
201 (arg.name === `isNull` || arg.name === `isUndefined`)
202 ) {
203 if (arg.args.length !== 1) {
204 throw new Error(`${arg.name} expects 1 argument`)
205 }
206 const innerArg = arg.args[0]!
207 const compiled = compileBasicExpression(
208 innerArg,
209 params,
210 encodeColumnName,
211 )
212 return `${innerArg.type === `func` ? `(${compiled})` : compiled} IS NOT NULL`
213 }
214 }
215​
216 const booleanLiteralIndex = args.findIndex(
217 (arg) => arg.type === `val` && typeof arg.value === `boolean`,
218 )
219 if (
220 args.length === 2 &&
221 isBooleanComparisonOp(name) &&
222 booleanLiteralIndex !== -1
223 ) {
224 const literalValue = (args[booleanLiteralIndex] as IR.Value<boolean>).value
225 const valueArg = args[booleanLiteralIndex === 0 ? 1 : 0]!
226 const compiled = compileBasicExpression(valueArg, params, encodeColumnName)
227 const value = `(${compiled})`
228 const lessThan =
229 (name === `lt` || name === `lte`) === (booleanLiteralIndex === 1)
230 const inclusive = name === `lte` || name === `gte`
231​
232 if (inclusive && literalValue === lessThan) {
233 return `${value} = ${value}`
234 }
235 if (!inclusive && literalValue !== lessThan) {
236 return `${value} <> ${value}`
237 }
238 return `${value} = ${lessThan ? `FALSE` : `TRUE`}`
239 }
240​
241 const compiledArgs = args.map((arg: IR.BasicExpression) => {
242 const compiled = compileBasicExpression(arg, params, encodeColumnName)
243 // AND/OR group their children by precedence; NOT already wraps its operand.
244 // In value positions, preserve any nested operator as a single expression.
245 return arg.type === `func` &&
246 (arg.name === `and` ||
247 arg.name === `or` ||
248 (name !== `and` &&
249 name !== `or` &&
250 name !== `not` &&
251 (isBinaryOp(arg.name) ||
252 arg.name === `not` ||
253 arg.name === `isNull` ||
254 arg.name === `isUndefined`)))
255 ? `(${compiled})`
256 : compiled
257 })
258​
259 // Special case for IS NULL / IS NOT NULL - these are postfix operators
260 if (name === `isNull` || name === `isUndefined`) {
261 if (compiledArgs.length !== 1) {
262 throw new Error(`${name} expects 1 argument`)
263 }
264 return `${compiledArgs[0]} ${opName}`
265 }
266​
267 // Special case for NOT - unary prefix operator
268 if (name === `not`) {
269 return `${opName} (${compiledArgs[0]})`
270 }
271​
272 if (isBinaryOp(name)) {
273 // Special handling for AND/OR which can be variadic
274 if ((name === `and` || name === `or`) && compiledArgs.length > 2) {
275 // Chain multiple arguments: (a AND b AND c) or (a OR b OR c)
276 return compiledArgs.join(` ${opName} `)
277 }
278​
279 if (compiledArgs.length !== 2) {
280 throw new Error(`Binary operator ${name} expects 2 arguments`)
281 }
282 const [lhs, rhs] = compiledArgs
283​
284 if (name === `in`) {
285 const valueArg = args[0]!
286 const arrayArg = args[1]!
287​
288 if (valueArg.type === `val` && Array.isArray(valueArg.value)) {
289 throw new Error(`Array-valued 'in' left operand; expected a scalar`)
290 }
291​
292 if (arrayArg.type === `ref` && valueArg.type === `val`) {
293 // Resolve literal parameters from the array element type before containment.
294 return `${lhs} = ANY(${rhs}) AND ${rhs} @> ARRAY[${lhs}] AND ${rhs} IS NOT NULL`
295 }
296​
297 // Literal value lists and ref/ref membership retain the original = ANY form.
298 return `${lhs} ${opName}(${rhs})`
299 }
300 return `${lhs} ${opName} ${rhs}`
301 }
302​
303 return `${opName}(${compiledArgs.join(`,`)})`
305​
306function isBinaryOp(name: string): boolean {
307 const binaryOps = [
308 `eq`,
309 `gt`,
310 `gte`,
311 `lt`,
312 `lte`,
313 `and`,
314 `or`,
315 `in`,
316 `like`,
317 `ilike`,
318 ]
319 return binaryOps.includes(name)
321​
322/**
323 * Check if operator is a comparison operator that takes two values
324 * These operators cannot accept null/undefined as values
325 * (null comparisons in SQL always evaluate to UNKNOWN)
326 */
327function isComparisonOp(name: string): boolean {
328 const comparisonOps = [`eq`, `gt`, `gte`, `lt`, `lte`, `like`, `ilike`, `in`]
329 return comparisonOps.includes(name)
331​
332/**
333 * Checks if the operator is a comparison operator (excluding eq)
334 * These operators don't work on booleans in PostgreSQL without casting
335 */
336function isBooleanComparisonOp(name: string): boolean {
337 return [`gt`, `gte`, `lt`, `lte`].includes(name)
339​
340function getOpName(name: string): string {
341 const opNames = {
342 eq: `=`,
343 gt: `>`,
344 gte: `>=`,
345 lt: `<`,
346 lte: `<=`,
347 add: `+`,
348 and: `AND`,
349 or: `OR`,
350 not: `NOT`,
351 isUndefined: `IS NULL`,
352 isNull: `IS NULL`,
353 in: `= ANY`, // Use = ANY syntax for array parameters
354 like: `LIKE`,
355 ilike: `ILIKE`,
356 upper: `UPPER`,
357 lower: `LOWER`,
358 length: `LENGTH`,
359 concat: `CONCAT`,
360 coalesce: `COALESCE`,
361 }
362​
363 const opName = opNames[name as keyof typeof opNames]
364​
365 if (!opName) {
366 throw new Error(`Unknown operator/function: ${name}`)
367 }
368​
369 return opName