0
# Expression Processing
1
2
Specialized functionality for handling SQL expressions, column references, and complex query components. This includes converting expression ASTs to SQL strings and processing column definitions.
3
4
## Capabilities
5
6
### Expression to SQL Conversion
7
8
Convert individual expression AST nodes back to SQL strings.
9
10
```javascript { .api }
11
/**
12
* Convert expression AST to SQL string
13
* @param expr - Expression AST to convert
14
* @param opt - Optional configuration object
15
* @returns SQL string representation of the expression
16
*/
17
exprToSQL(expr: any, opt?: Option): string;
18
```
19
20
**Usage Examples:**
21
22
```javascript
23
const { Parser } = require('node-sql-parser');
24
const parser = new Parser();
25
26
// Parse a query to get expression ASTs
27
const ast = parser.astify('SELECT name, age + 10 FROM users WHERE active = true');
28
29
// Convert individual expressions
30
const columnExpr = ast.columns[1].expr; // age + 10 expression
31
const exprSql = parser.exprToSQL(columnExpr);
32
console.log(exprSql); // "(`age` + 10)"
33
34
const whereExpr = ast.where; // active = true expression
35
const whereSql = parser.exprToSQL(whereExpr);
36
console.log(whereSql); // "(`active` = TRUE)"
37
38
// Database-specific expression conversion
39
const pgExprSql = parser.exprToSQL(columnExpr, { database: 'PostgreSQL' });
40
console.log(pgExprSql); // "(\"age\" + 10)"
41
```
42
43
### Column Processing
44
45
Convert column AST objects to SQL strings with table context awareness.
46
47
```javascript { .api }
48
/**
49
* Convert column AST objects to SQL strings
50
* @param columns - Column objects to convert
51
* @param tables - Table context for column resolution
52
* @param opt - Optional configuration object
53
* @returns Array of SQL column strings
54
*/
55
columnsToSQL(columns: any, tables: any, opt?: Option): string[];
56
```
57
58
**Usage Examples:**
59
60
```javascript
61
// Parse query to get column and table information
62
const ast = parser.astify('SELECT u.name, u.email, p.title FROM users u JOIN posts p ON u.id = p.user_id');
63
64
// Convert columns with table context
65
const columns = ast.columns;
66
const tables = ast.from;
67
const columnSqls = parser.columnsToSQL(columns, tables);
68
console.log(columnSqls);
69
// ["u.name", "u.email", "p.title"]
70
71
// Handle wildcard columns
72
const wildcardAst = parser.astify('SELECT * FROM users');
73
const wildcardColumns = parser.columnsToSQL(wildcardAst.columns, wildcardAst.from);
74
console.log(wildcardColumns); // [] (wildcard returns empty array)
75
76
// Handle computed columns
77
const computedAst = parser.astify('SELECT name, age * 2 as double_age FROM users');
78
const computedColumns = parser.columnsToSQL(computedAst.columns, computedAst.from);
79
console.log(computedColumns); // Returns array of SQL column strings
80
```
81
82
## Expression Types
83
84
### Binary Expressions
85
86
Represent operators between two operands (arithmetic, comparison, logical).
87
88
```javascript { .api }
89
interface Binary {
90
type: "binary_expr";
91
operator: string;
92
left: ExpressionValue | ExprList;
93
right: ExpressionValue | ExprList;
94
loc?: LocationRange;
95
parentheses?: boolean;
96
}
97
```
98
99
**Usage Examples:**
100
101
```javascript
102
// Parse binary expressions
103
const ast = parser.astify('SELECT * FROM users WHERE age >= 18 AND status = "active"');
104
const whereExpr = ast.where; // Binary expression with AND operator
105
106
console.log(whereExpr.type); // "binary_expr"
107
console.log(whereExpr.operator); // "AND"
108
console.log(whereExpr.left); // Binary expression for "age >= 18"
109
console.log(whereExpr.right); // Binary expression for 'status = "active"'
110
111
// Convert back to SQL
112
const sql = parser.exprToSQL(whereExpr);
113
console.log(sql); // "((`age` >= 18) AND (`status` = 'active'))"
114
```
115
116
### Function Expressions
117
118
Represent function calls in SQL expressions.
119
120
```javascript { .api }
121
interface Function {
122
type: "function";
123
name: FunctionName;
124
args?: ExprList;
125
suffix?: any;
126
loc?: LocationRange;
127
}
128
129
type FunctionName = {
130
schema?: { value: string; type: string };
131
name: ValueExpr<string>[];
132
};
133
```
134
135
**Usage Examples:**
136
137
```javascript
138
// Parse function expressions
139
const ast = parser.astify('SELECT UPPER(name), COUNT(*) FROM users GROUP BY name');
140
141
const upperFunc = ast.columns[0].expr; // UPPER(name) function
142
console.log(upperFunc.type); // "function"
143
console.log(upperFunc.name); // Function name details
144
145
const countFunc = ast.columns[1].expr; // COUNT(*) function
146
console.log(countFunc.name); // COUNT function details
147
console.log(countFunc.args); // Arguments list
148
149
// Convert function expression to SQL
150
const funcSql = parser.exprToSQL(upperFunc);
151
console.log(funcSql); // "UPPER(`name`)"
152
```
153
154
### Aggregate Functions
155
156
Specialized function expressions for SQL aggregate operations.
157
158
```javascript { .api }
159
interface AggrFunc {
160
type: "aggr_func";
161
name: string;
162
args: {
163
expr: ExpressionValue;
164
distinct: "DISTINCT" | null;
165
orderby: OrderBy[] | null;
166
parentheses?: boolean;
167
};
168
loc?: LocationRange;
169
}
170
```
171
172
**Usage Examples:**
173
174
```javascript
175
// Parse aggregate functions
176
const ast = parser.astify('SELECT COUNT(DISTINCT user_id), SUM(amount) FROM orders');
177
178
const countDistinct = ast.columns[0].expr;
179
console.log(countDistinct.type); // "aggr_func"
180
console.log(countDistinct.name); // "COUNT"
181
console.log(countDistinct.args.distinct); // "DISTINCT"
182
183
const sumFunc = ast.columns[1].expr;
184
console.log(sumFunc.name); // "SUM"
185
console.log(sumFunc.args.expr); // Expression for 'amount'
186
187
// Convert aggregate to SQL
188
const aggrSql = parser.exprToSQL(countDistinct);
189
console.log(aggrSql); // "COUNT(DISTINCT `user_id`)"
190
```
191
192
### Case Expressions
193
194
Represent CASE WHEN conditional expressions.
195
196
```javascript { .api }
197
interface Case {
198
type: "case";
199
expr: null;
200
args: Array<
201
| {
202
cond: Binary;
203
result: ExpressionValue;
204
type: "when";
205
}
206
| {
207
result: ExpressionValue;
208
type: "else";
209
}
210
>;
211
}
212
```
213
214
**Usage Examples:**
215
216
```javascript
217
// Parse CASE expressions
218
const ast = parser.astify(`
219
SELECT
220
name,
221
CASE
222
WHEN age < 18 THEN 'Minor'
223
WHEN age >= 65 THEN 'Senior'
224
ELSE 'Adult'
225
END as category
226
FROM users
227
`);
228
229
const caseExpr = ast.columns[1].expr;
230
console.log(caseExpr.type); // "case"
231
console.log(caseExpr.args.length); // 3 (two WHEN conditions + ELSE)
232
console.log(caseExpr.args[0].type); // "when"
233
console.log(caseExpr.args[2].type); // "else"
234
235
// Convert CASE to SQL
236
const caseSql = parser.exprToSQL(caseExpr);
237
console.log(caseSql); // Full CASE expression SQL
238
```
239
240
### Cast Expressions
241
242
Represent type casting operations.
243
244
```javascript { .api }
245
interface Cast {
246
type: "cast";
247
keyword: "cast";
248
expr: ExpressionValue;
249
symbol: "as";
250
target: {
251
dataType: string;
252
quoted?: string;
253
}[];
254
}
255
```
256
257
**Usage Examples:**
258
259
```javascript
260
// Parse CAST expressions
261
const ast = parser.astify('SELECT CAST(price AS DECIMAL(10,2)) FROM products');
262
263
const castExpr = ast.columns[0].expr;
264
console.log(castExpr.type); // "cast"
265
console.log(castExpr.keyword); // "cast"
266
console.log(castExpr.expr); // Expression being cast (price)
267
console.log(castExpr.target); // Target data type info
268
269
// Convert CAST to SQL
270
const castSql = parser.exprToSQL(castExpr);
271
console.log(castSql); // "CAST(`price` AS DECIMAL(10, 2))"
272
```
273
274
### Column References
275
276
Represent references to table columns with optional table qualification.
277
278
```javascript { .api }
279
interface ColumnRefItem {
280
type: "column_ref";
281
table: string | null;
282
column: string | { expr: ValueExpr };
283
options?: ExprList;
284
loc?: LocationRange;
285
collate?: { collate: CollateExpr } | null;
286
order_by?: SortDirection | null;
287
}
288
289
interface ColumnRefExpr {
290
type: "expr";
291
expr: ColumnRefItem;
292
as: string | null;
293
}
294
295
type ColumnRef = ColumnRefItem | ColumnRefExpr;
296
```
297
298
**Usage Examples:**
299
300
```javascript
301
// Parse column references
302
const ast = parser.astify('SELECT u.name, email FROM users u');
303
304
const qualifiedCol = ast.columns[0].expr; // u.name
305
console.log(qualifiedCol.type); // "column_ref"
306
console.log(qualifiedCol.table); // "u"
307
console.log(qualifiedCol.column); // "name"
308
309
const unqualifiedCol = ast.columns[1].expr; // email
310
console.log(unqualifiedCol.table); // null
311
console.log(unqualifiedCol.column); // "email"
312
313
// Convert column reference to SQL
314
const colSql = parser.exprToSQL(qualifiedCol);
315
console.log(colSql); // "`u`.`name`"
316
```
317
318
### Value Expressions
319
320
Represent literal values in SQL expressions.
321
322
```javascript { .api }
323
interface ValueExpr<T = string | number | boolean> {
324
type: "backticks_quote_string" | "string" | "regex_string" | "hex_string" |
325
"full_hex_string" | "natural_string" | "bit_string" | "double_quote_string" |
326
"single_quote_string" | "boolean" | "bool" | "null" | "star" | "param" |
327
"origin" | "date" | "datetime" | "default" | "time" | "timestamp" | "var_string";
328
value: T;
329
}
330
```
331
332
**Usage Examples:**
333
334
```javascript
335
// Parse various value types
336
const ast = parser.astify("SELECT 'hello', 42, true, null FROM dual");
337
338
const stringVal = ast.columns[0].expr;
339
console.log(stringVal.type); // "single_quote_string"
340
console.log(stringVal.value); // "hello"
341
342
const numberVal = ast.columns[1].expr;
343
console.log(numberVal.type); // "number"
344
console.log(numberVal.value); // 42
345
346
const boolVal = ast.columns[2].expr;
347
console.log(boolVal.type); // "bool"
348
console.log(boolVal.value); // true
349
350
const nullVal = ast.columns[3].expr;
351
console.log(nullVal.type); // "null"
352
console.log(nullVal.value); // null
353
```
354
355
## Expression Lists
356
357
Handle arrays of expressions in contexts like function arguments or IN clauses.
358
359
```javascript { .api }
360
interface ExprList {
361
type: "expr_list";
362
value: ExpressionValue[];
363
loc?: LocationRange;
364
parentheses?: boolean;
365
separator?: string;
366
}
367
```
368
369
**Usage Examples:**
370
371
```javascript
372
// Parse expression lists
373
const ast = parser.astify('SELECT * FROM users WHERE id IN (1, 2, 3)');
374
375
const inExpr = ast.where.right; // Expression list for IN clause
376
console.log(inExpr.type); // "expr_list"
377
console.log(inExpr.value.length); // 3
378
console.log(inExpr.parentheses); // true
379
380
// Function with multiple arguments
381
const funcAst = parser.astify('SELECT SUBSTRING(name, 1, 5) FROM users');
382
const funcArgs = funcAst.columns[0].expr.args;
383
console.log(funcArgs.type); // "expr_list"
384
console.log(funcArgs.value.length); // 3 arguments
385
```