Open History to see the last commit
1import { SerializedExpression, SerializedOrderByClause } from './types'
2import { quoteIdentifier } from './column-mapper'
3
4/**
5 * Compiles a serialized expression into a SQL string.
6 * Applies columnMapper transformations to column references.
7 *
8 * @param expr - The serialized expression to compile
9 * @param columnMapper - Optional function to transform column names (e.g., camelCase to snake_case)
10 * @returns The compiled SQL string
11 *
12 * @example
13 * ```typescript
14 * const expr = { type: 'ref', column: 'userId' }
15 * compileExpression(expr, camelToSnake) // '"user_id"'
16 * ```
17 */
18export function compileExpression(
19 expr: SerializedExpression,
20 columnMapper?: (col: string) => string
21): string {
22 switch (expr.type) {
23 case `ref`: {
24 // Apply columnMapper, then quote
25 const mappedColumn = columnMapper
26 ? columnMapper(expr.column)
27 : expr.column
28 return quoteIdentifier(mappedColumn)
29 }
30 case `val`:
31 return `$${expr.paramIndex}`
32 case `func`:
33 return compileFunction(expr, columnMapper)
34 default: {
35 // TypeScript exhaustiveness check
36 const _exhaustive: never = expr
37 throw new Error(`Unknown expression type: ${JSON.stringify(_exhaustive)}`)
38 }
39 }
40}
41
42/**
43 * Compiles a function expression into SQL.
44 */
45function compileFunction(
46 expr: { type: `func`; name: string; args: SerializedExpression[] },
47 columnMapper?: (col: string) => string
48): string {
49 const args = expr.args.map((arg) => compileExpression(arg, columnMapper))
50
51 switch (expr.name) {
52 // Binary comparison operators
53 case `eq`:
54 return `${args[0]} = ${args[1]}`
55 case `gt`:
56 return `${args[0]} > ${args[1]}`
57 case `gte`:
58 return `${args[0]} >= ${args[1]}`
59 case `lt`:
60 return `${args[0]} < ${args[1]}`
61 case `lte`:
62 return `${args[0]} <= ${args[1]}`
63
64 // Logical operators
65 case `and`:
66 return args.map((a) => `(${a})`).join(` AND `)
67 case `or`:
68 return args.map((a) => `(${a})`).join(` OR `)
69 case `not`:
70 return `NOT (${args[0]})`
71
72 // Special operators
73 case `in`:
74 return `${args[0]} = ANY(${args[1]})`
75 case `like`:
76 return `${args[0]} LIKE ${args[1]}`
77 case `ilike`:
78 return `${args[0]} ILIKE ${args[1]}`
79 case `isNull`:
80 case `isUndefined`:
81 return `${args[0]} IS NULL`
82
83 // String functions
84 case `upper`:
85 return `UPPER(${args[0]})`
86 case `lower`:
87 return `LOWER(${args[0]})`
88 case `length`:
89 return `LENGTH(${args[0]})`
90 case `concat`:
91 return `CONCAT(${args.join(`, `)})`
92
93 // Other functions
94 case `coalesce`:
95 return `COALESCE(${args.join(`, `)})`
96
97 default:
98 throw new Error(`Unknown function: ${expr.name}`)
99 }
100}
101
102/**
103 * Compiles serialized ORDER BY clauses into a SQL string.
104 * Applies columnMapper transformations to column references.
105 *
106 * @param clauses - The serialized ORDER BY clauses to compile
107 * @param columnMapper - Optional function to transform column names
108 * @returns The compiled SQL ORDER BY string
109 *
110 * @example
111 * ```typescript
112 * const clauses = [{ column: 'createdAt', direction: 'desc', nulls: 'first' }]
113 * compileOrderBy(clauses, camelToSnake) // '"created_at" DESC NULLS FIRST'
114 * ```
115 */
116export function compileOrderBy(
117 clauses: SerializedOrderByClause[],
118 columnMapper?: (col: string) => string
119): string {
120 return clauses
121 .map((clause) => {
122 const mappedColumn = columnMapper
123 ? columnMapper(clause.column)
124 : clause.column
125 let sql = quoteIdentifier(mappedColumn)
126 if (clause.direction === `desc`) sql += ` DESC`
127 if (clause.nulls === `first`) sql += ` NULLS FIRST`
128 if (clause.nulls === `last`) sql += ` NULLS LAST`
129 return sql
130 })
131 .join(`, `)
132}