@quereus/quereus 0.6.2 → 0.6.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,864 +1,864 @@
1
- /**
2
- * Functions to convert DDL AST nodes back into SQL strings.
3
- *
4
- * Formatting Notes:
5
- * - Emits lowercase SQL keywords.
6
- * - Quotes identifiers (table/column names) using double quotes.
7
- * - String literals are escaped.
8
- * - Omits clauses that represent the default SQLite behavior:
9
- * - `ON CONFLICT ABORT`
10
- * - `ASC` direction for primary keys
11
- * - `VIRTUAL` storage for generated columns
12
- * - (TODO: `FOREIGN KEY` default actions and deferrability)
13
- */
14
- import type * as AST from '../parser/ast.js';
15
- import { ConflictResolution } from '../common/constants.js';
16
- import { KEYWORDS } from '../parser/lexer.js';
17
-
18
- // --- Identifier Quoting Logic ---
19
-
20
- // Basic check for valid SQL identifiers (adjust regex as needed)
21
- const isValidIdentifier = (name: string): boolean => {
22
- return /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(name);
23
- };
24
-
25
- /**
26
- * Quotes an identifier (table, column, etc.) with double quotes if necessary.
27
- * Quoting is needed if the identifier:
28
- * - Is a reserved keyword (case-insensitive).
29
- * - Does not match the valid identifier pattern (starts with letter/_, contains letters/numbers/_).
30
- */
31
- function quoteIdentifierIfNeeded(name: string): string {
32
- if (Object.hasOwn(KEYWORDS, name.toLowerCase()) || !isValidIdentifier(name)) {
33
- return `"${name.replace(/"/g, '""')}"`; // Escape internal quotes
34
- }
35
- return name;
36
- }
37
-
38
- // Main function to convert any AST node to SQL string
39
- export function astToString(node: AST.AstNode): string {
40
- switch (node.type) {
41
- // Expression types
42
- case 'literal':
43
- case 'identifier':
44
- case 'column':
45
- case 'binary':
46
- case 'unary':
47
- case 'function':
48
- case 'cast':
49
- case 'parameter':
50
- case 'subquery':
51
- case 'collate':
52
- case 'case':
53
- case 'windowFunction':
54
- return expressionToString(node as AST.Expression);
55
-
56
- // Statement types
57
- case 'select':
58
- return selectToString(node as AST.SelectStmt);
59
- case 'insert':
60
- return insertToString(node as AST.InsertStmt);
61
- case 'update':
62
- return updateToString(node as AST.UpdateStmt);
63
- case 'delete':
64
- return deleteToString(node as AST.DeleteStmt);
65
- case 'values':
66
- return valuesToString(node as AST.ValuesStmt);
67
- case 'createTable':
68
- return createTableToString(node as AST.CreateTableStmt);
69
- case 'createIndex':
70
- return createIndexToString(node as AST.CreateIndexStmt);
71
- case 'createView':
72
- return createViewToString(node as AST.CreateViewStmt);
73
- case 'drop':
74
- return dropToString(node as AST.DropStmt);
75
- case 'begin':
76
- return beginToString(node as AST.BeginStmt);
77
- case 'commit':
78
- return 'commit';
79
- case 'rollback':
80
- return rollbackToString(node as AST.RollbackStmt);
81
- case 'savepoint':
82
- return savepointToString(node as AST.SavepointStmt);
83
- case 'release':
84
- return releaseToString(node as AST.ReleaseStmt);
85
- case 'pragma':
86
- return pragmaToString(node as AST.PragmaStmt);
87
- case 'declareSchema':
88
- return declareSchemaToString(node as unknown as AST.DeclareSchemaStmt);
89
- case 'diffSchema':
90
- return `diff schema ${(node as unknown as AST.DiffSchemaStmt).schemaName || 'main'}`;
91
- case 'applySchema': {
92
- const n = node as unknown as AST.ApplySchemaStmt;
93
- let s = `apply schema ${n.schemaName || 'main'}`;
94
- if (n.toVersion) s += ` to version '${n.toVersion}'`;
95
- if (n.withSeed) s += ' with seed';
96
- if (n.options) {
97
- s += ' options (';
98
- const parts: string[] = [];
99
- if (n.options.dryRun !== undefined) parts.push(`dry_run = ${n.options.dryRun ? 'true' : 'false'}`);
100
- if (n.options.validateOnly !== undefined) parts.push(`validate_only = ${n.options.validateOnly ? 'true' : 'false'}`);
101
- if (n.options.allowDestructive !== undefined) parts.push(`allow_destructive = ${n.options.allowDestructive ? 'true' : 'false'}`);
102
- if (n.options.renamePolicy) parts.push(`rename_policy = '${n.options.renamePolicy}'`);
103
- s += parts.join(', ') + ')';
104
- }
105
- return s;
106
- }
107
- case 'explainSchema':
108
- return `explain schema ${(node as unknown as AST.ExplainSchemaStmt).schemaName || 'main'}`;
109
-
110
- default:
111
- return `[${node.type}]`; // Fallback for unknown node types
112
- }
113
- }
114
-
115
- // Helper to stringify expressions (extended from original)
116
- export function expressionToString(expr: AST.Expression): string {
117
- switch (expr.type) {
118
- case 'literal': {
119
- // Prefer original lexeme for numbers if available and different
120
- if ((typeof expr.value === 'number' || typeof expr.value === 'bigint') && expr.lexeme && expr.lexeme !== String(expr.value)) {
121
- return expr.lexeme;
122
- }
123
- // Prefer original lexeme for NULL if available
124
- if (expr.value === null) return expr.lexeme?.toLowerCase() || 'null';
125
- if (typeof expr.value === 'string') return `'${expr.value.replace(/'/g, "''")}'`; // Escape single quotes
126
- if (typeof expr.value === 'number') return expr.value.toString();
127
- if (expr.value instanceof Uint8Array) {
128
- const hex = Buffer.from(expr.value).toString('hex');
129
- return `x'${hex}'`;
130
- }
131
- return String(expr.value);
132
- }
133
-
134
- case 'identifier': {
135
- let identStr = quoteIdentifierIfNeeded(expr.name);
136
- if (expr.schema) {
137
- identStr = `${quoteIdentifierIfNeeded(expr.schema)}.${identStr}`;
138
- }
139
- return identStr;
140
- }
141
-
142
- case 'column': {
143
- let colStr = quoteIdentifierIfNeeded(expr.name);
144
- if (expr.table) {
145
- colStr = `${quoteIdentifierIfNeeded(expr.table)}.${colStr}`;
146
- if (expr.schema) {
147
- colStr = `${quoteIdentifierIfNeeded(expr.schema)}.${colStr}`;
148
- }
149
- }
150
- return colStr;
151
- }
152
-
153
- case 'binary': {
154
- const leftStr = needsParens(expr.left, expr.operator, 'left')
155
- ? `(${expressionToString(expr.left)})`
156
- : expressionToString(expr.left);
157
- const rightStr = needsParens(expr.right, expr.operator, 'right')
158
- ? `(${expressionToString(expr.right)})`
159
- : expressionToString(expr.right);
160
- return `${leftStr} ${expr.operator.toLowerCase()} ${rightStr}`;
161
- }
162
-
163
- case 'unary': {
164
- const exprStr = expr.expr.type === 'binary'
165
- ? `(${expressionToString(expr.expr)})`
166
- : expressionToString(expr.expr);
167
- // Handle postfix operators like IS NULL, IS NOT NULL
168
- if (expr.operator === 'IS NULL' || expr.operator === 'IS NOT NULL') {
169
- return `${exprStr} ${expr.operator.toLowerCase()}`;
170
- } else if (expr.operator.toUpperCase() === 'NOT') {
171
- return `${expr.operator.toLowerCase()} ${exprStr}`;
172
- }
173
- return `${expr.operator.toLowerCase()}${exprStr}`;
174
- }
175
-
176
- case 'function': {
177
- if (expr.name.toLowerCase() === 'count' && expr.args.length === 0) {
178
- return 'count(*)';
179
- }
180
- const argsStr = expr.args.map(arg => expressionToString(arg)).join(', ');
181
- const distinctStr = expr.distinct ? 'distinct ' : '';
182
- return `${expr.name.toLowerCase()}(${distinctStr}${argsStr})`;
183
- }
184
-
185
- case 'cast':
186
- return `cast(${expressionToString(expr.expr)} as ${expr.targetType.toLowerCase()})`;
187
-
188
- case 'parameter': {
189
- if (expr.index !== undefined) {
190
- return '?';
191
- } else if (expr.name) {
192
- return expr.name.startsWith(':') || expr.name.startsWith('$')
193
- ? expr.name
194
- : `:${expr.name}`;
195
- }
196
- return '?';
197
- }
198
-
199
- case 'subquery':
200
- return `(${selectToString(expr.query)})`;
201
-
202
- case 'exists':
203
- return `exists (${selectToString((expr as AST.ExistsExpr).subquery)})`;
204
-
205
- case 'in': {
206
- const inExpr = expr as AST.InExpr;
207
- let result = expressionToString(inExpr.expr) + ' in ';
208
- if (inExpr.values) {
209
- result += `(${inExpr.values.map(expressionToString).join(', ')})`;
210
- } else if (inExpr.subquery) {
211
- result += `(${selectToString(inExpr.subquery)})`;
212
- }
213
- return result;
214
- }
215
-
216
- case 'between': {
217
- const betweenExpr = expr as AST.BetweenExpr;
218
- const exprStr = expressionToString(betweenExpr.expr);
219
- const lowerStr = expressionToString(betweenExpr.lower);
220
- const upperStr = expressionToString(betweenExpr.upper);
221
- const notStr = betweenExpr.not ? 'not ' : '';
222
- return `${exprStr} ${notStr}between ${lowerStr} and ${upperStr}`;
223
- }
224
-
225
- case 'collate':
226
- return `${expressionToString(expr.expr)} collate ${expr.collation.toLowerCase()}`;
227
-
228
- case 'case': {
229
- // TODO: preserve and emit with original case
230
- let caseStr = 'case';
231
- if (expr.baseExpr) {
232
- caseStr += ` ${expressionToString(expr.baseExpr)}`;
233
- }
234
- for (const clause of expr.whenThenClauses) {
235
- caseStr += ` when ${expressionToString(clause.when)} then ${expressionToString(clause.then)}`;
236
- }
237
- if (expr.elseExpr) {
238
- caseStr += ` else ${expressionToString(expr.elseExpr)}`;
239
- }
240
- caseStr += ' end';
241
- return caseStr;
242
- }
243
-
244
- case 'windowFunction': {
245
- let winStr = expressionToString(expr.function);
246
- if (expr.window) {
247
- winStr += ` over (${windowDefinitionToString(expr.window)})`;
248
- }
249
- return winStr;
250
- }
251
-
252
- default:
253
- return '[unknown_expr]';
254
- }
255
- }
256
-
257
- // Helper to determine if parentheses are needed for binary operations
258
- function needsParens(expr: AST.Expression, parentOp: string, side: 'left' | 'right'): boolean {
259
- if (expr.type !== 'binary') return false;
260
-
261
- const precedence: Record<string, number> = {
262
- 'OR': 1, 'AND': 2, 'NOT': 3, '=': 4, '!=': 4, '<': 4, '<=': 4, '>': 4, '>=': 4,
263
- 'LIKE': 4, 'IN': 4, 'IS': 4, '+': 5, '-': 5, '*': 6, '/': 6, '%': 6
264
- };
265
-
266
- const parentPrec = precedence[parentOp.toUpperCase()] || 0;
267
- const childPrec = precedence[expr.operator.toUpperCase()] || 0;
268
-
269
- if (childPrec < parentPrec) return true;
270
- if (childPrec === parentPrec && side === 'right' && !isAssociative(parentOp)) return true;
271
-
272
- return false;
273
- }
274
-
275
- function isAssociative(op: string): boolean {
276
- const associativeOps = ['AND', 'OR', '+', '*'];
277
- return associativeOps.includes(op.toUpperCase());
278
- }
279
-
280
- // Helper for window definitions
281
- function windowDefinitionToString(win: AST.WindowDefinition): string {
282
- const parts: string[] = [];
283
-
284
- if (win.partitionBy && win.partitionBy.length > 0) {
285
- parts.push(`partition by ${win.partitionBy.map(expressionToString).join(', ')}`);
286
- }
287
-
288
- if (win.orderBy && win.orderBy.length > 0) {
289
- const orderParts = win.orderBy.map(clause => {
290
- let orderStr = expressionToString(clause.expr);
291
- if (clause.direction === 'desc') orderStr += ' desc';
292
- if (clause.nulls) orderStr += ` nulls ${clause.nulls.toLowerCase()}`;
293
- return orderStr;
294
- });
295
- parts.push(`order by ${orderParts.join(', ')}`);
296
- }
297
-
298
- if (win.frame) {
299
- parts.push(windowFrameToString(win.frame));
300
- }
301
-
302
- return parts.join(' ');
303
- }
304
-
305
- function windowFrameToString(frame: AST.WindowFrame): string {
306
- let frameStr = frame.type.toLowerCase(); // 'rows' or 'range'
307
-
308
- if (frame.end) {
309
- frameStr += ` between ${windowFrameBoundToString(frame.start)} and ${windowFrameBoundToString(frame.end)}`;
310
- } else {
311
- frameStr += ` ${windowFrameBoundToString(frame.start)}`;
312
- }
313
-
314
- if (frame.exclusion) {
315
- frameStr += ` exclude ${frame.exclusion.toLowerCase()}`;
316
- }
317
-
318
- return frameStr;
319
- }
320
-
321
- function windowFrameBoundToString(bound: AST.WindowFrameBound): string {
322
- switch (bound.type) {
323
- case 'currentRow': return 'current row';
324
- case 'unboundedPreceding': return 'unbounded preceding';
325
- case 'unboundedFollowing': return 'unbounded following';
326
- case 'preceding': return `${expressionToString(bound.value)} preceding`;
327
- case 'following': return `${expressionToString(bound.value)} following`;
328
- default: return '[unknown_bound]';
329
- }
330
- }
331
-
332
- // Statement stringify functions
333
- export function selectToString(stmt: AST.SelectStmt): string {
334
- const parts: string[] = [];
335
-
336
- if (stmt.withClause) {
337
- parts.push(withClauseToString(stmt.withClause));
338
- }
339
-
340
- parts.push('select');
341
-
342
- if (stmt.distinct) parts.push('distinct');
343
- if (stmt.all) parts.push('all');
344
-
345
- const columns = stmt.columns.map(col => {
346
- if (col.type === 'all') {
347
- return col.table ? `${quoteIdentifierIfNeeded(col.table)}.*` : '*';
348
- } else {
349
- let colStr = expressionToString(col.expr);
350
- if (col.alias) colStr += ` as ${quoteIdentifierIfNeeded(col.alias)}`;
351
- return colStr;
352
- }
353
- });
354
- parts.push(columns.join(', '));
355
-
356
- if (stmt.from && stmt.from.length > 0) {
357
- parts.push('from', stmt.from.map(fromClauseToString).join(', '));
358
- }
359
-
360
- if (stmt.where) {
361
- parts.push('where', expressionToString(stmt.where));
362
- }
363
-
364
- if (stmt.groupBy && stmt.groupBy.length > 0) {
365
- parts.push('group by', stmt.groupBy.map(expressionToString).join(', '));
366
- }
367
-
368
- if (stmt.having) {
369
- parts.push('having', expressionToString(stmt.having));
370
- }
371
-
372
- if (stmt.orderBy && stmt.orderBy.length > 0) {
373
- const orderParts = stmt.orderBy.map(clause => {
374
- let orderStr = expressionToString(clause.expr);
375
- if (clause.direction === 'desc') orderStr += ' desc';
376
- if (clause.nulls) orderStr += ` nulls ${clause.nulls.toLowerCase()}`;
377
- return orderStr;
378
- });
379
- parts.push('order by', orderParts.join(', '));
380
- }
381
-
382
- if (stmt.limit) {
383
- parts.push('limit', expressionToString(stmt.limit));
384
- }
385
-
386
- if (stmt.offset) {
387
- parts.push('offset', expressionToString(stmt.offset));
388
- }
389
-
390
- let result = parts.join(' ');
391
-
392
- if (stmt.union) {
393
- result += stmt.unionAll ? ' union all ' : ' union ';
394
- result += selectToString(stmt.union);
395
- }
396
-
397
- return result;
398
- }
399
-
400
- function withClauseToString(withClause: AST.WithClause): string {
401
- let result = 'with';
402
- if (withClause.recursive) result += ' recursive';
403
-
404
- const ctes = withClause.ctes.map(cte => {
405
- let cteStr = quoteIdentifierIfNeeded(cte.name);
406
- if (cte.columns && cte.columns.length > 0) {
407
- cteStr += ` (${cte.columns.map(quoteIdentifierIfNeeded).join(', ')})`;
408
- }
409
- cteStr += ` as (${astToString(cte.query)})`;
410
- return cteStr;
411
- });
412
-
413
- result += ` ${ctes.join(', ')}`;
414
-
415
- // Add OPTION clause if present
416
- if (withClause.options?.maxRecursion !== undefined) {
417
- result += ` option (maxrecursion ${withClause.options.maxRecursion})`;
418
- }
419
-
420
- return result;
421
- }
422
-
423
- function fromClauseToString(from: AST.FromClause): string {
424
- switch (from.type) {
425
- case 'table': {
426
- let tableStr = quoteIdentifierIfNeeded(from.table.name);
427
- if (from.table.schema) {
428
- tableStr = `${quoteIdentifierIfNeeded(from.table.schema)}.${tableStr}`;
429
- }
430
- if (from.alias) tableStr += ` as ${quoteIdentifierIfNeeded(from.alias)}`;
431
- return tableStr;
432
- }
433
-
434
- case 'subquerySource': {
435
- let subqueryStr: string;
436
- if (from.subquery.type === 'select') {
437
- subqueryStr = selectToString(from.subquery);
438
- } else if (from.subquery.type === 'values') {
439
- subqueryStr = valuesToString(from.subquery);
440
- } else {
441
- // Handle the case where subquery type is not recognized
442
- const exhaustiveCheck: never = from.subquery;
443
- subqueryStr = astToString(exhaustiveCheck);
444
- }
445
-
446
- let aliasStr = `as ${quoteIdentifierIfNeeded(from.alias)}`;
447
- if (from.columns && from.columns.length > 0) {
448
- aliasStr += ` (${from.columns.map(quoteIdentifierIfNeeded).join(', ')})`;
449
- }
450
-
451
- return `(${subqueryStr}) ${aliasStr}`;
452
- }
453
-
454
- case 'functionSource': {
455
- const args = from.args.map(expressionToString).join(', ');
456
- // Check if from.name is a function expression or identifier expression
457
- let funcName: string;
458
- if (from.name.type === 'identifier') {
459
- funcName = from.name.name.toLowerCase();
460
- } else if (from.name.type === 'function') {
461
- funcName = expressionToString(from.name);
462
- } else {
463
- funcName = expressionToString(from.name);
464
- }
465
- let funcStr = `${funcName}(${args})`;
466
- if (from.alias) funcStr += ` as ${quoteIdentifierIfNeeded(from.alias)}`;
467
- return funcStr;
468
- }
469
-
470
- case 'join': {
471
- const leftStr = fromClauseToString(from.left);
472
- const rightStr = fromClauseToString(from.right);
473
- let joinStr = `${leftStr} ${from.joinType.toLowerCase()} join ${rightStr}`;
474
- if (from.condition) {
475
- joinStr += ` on ${expressionToString(from.condition)}`;
476
- } else if (from.columns) {
477
- joinStr += ` using (${from.columns.map(quoteIdentifierIfNeeded).join(', ')})`;
478
- }
479
- return joinStr;
480
- }
481
-
482
- default:
483
- return '[unknown_from]';
484
- }
485
- }
486
-
487
- export function insertToString(stmt: AST.InsertStmt): string {
488
- const parts: string[] = [];
489
-
490
- if (stmt.withClause) {
491
- parts.push(withClauseToString(stmt.withClause));
492
- }
493
-
494
- parts.push('insert into', expressionToString(stmt.table));
495
-
496
- if (stmt.columns && stmt.columns.length > 0) {
497
- parts.push(`(${stmt.columns.map(quoteIdentifierIfNeeded).join(', ')})`);
498
- }
499
-
500
- if (stmt.values) {
501
- const valueRows = stmt.values.map(row =>
502
- `(${row.map(expressionToString).join(', ')})`
503
- );
504
- parts.push('values', valueRows.join(', '));
505
- } else if (stmt.select) {
506
- parts.push(selectToString(stmt.select));
507
- }
508
-
509
- if (stmt.onConflict && stmt.onConflict !== ConflictResolution.ABORT) {
510
- parts.push(`on conflict ${ConflictResolution[stmt.onConflict].toLowerCase()}`);
511
- }
512
-
513
- if (stmt.returning && stmt.returning.length > 0) {
514
- const returning = stmt.returning.map(col => {
515
- if (col.type === 'all') {
516
- return col.table ? `${quoteIdentifierIfNeeded(col.table)}.*` : '*';
517
- } else {
518
- let colStr = expressionToString(col.expr);
519
- if (col.alias) colStr += ` as ${quoteIdentifierIfNeeded(col.alias)}`;
520
- return colStr;
521
- }
522
- });
523
- parts.push('returning', returning.join(', '));
524
- }
525
-
526
- return parts.join(' ');
527
- }
528
-
529
- export function updateToString(stmt: AST.UpdateStmt): string {
530
- const parts: string[] = [];
531
-
532
- if (stmt.withClause) {
533
- parts.push(withClauseToString(stmt.withClause));
534
- }
535
-
536
- parts.push('update', expressionToString(stmt.table), 'set');
537
-
538
- const assignments = stmt.assignments.map(assign =>
539
- `${quoteIdentifierIfNeeded(assign.column)} = ${expressionToString(assign.value)}`
540
- );
541
- parts.push(assignments.join(', '));
542
-
543
- if (stmt.where) {
544
- parts.push('where', expressionToString(stmt.where));
545
- }
546
-
547
- if (stmt.onConflict && stmt.onConflict !== ConflictResolution.ABORT) {
548
- parts.push(`on conflict ${ConflictResolution[stmt.onConflict].toLowerCase()}`);
549
- }
550
-
551
- if (stmt.returning && stmt.returning.length > 0) {
552
- const returning = stmt.returning.map(col => {
553
- if (col.type === 'all') {
554
- return col.table ? `${quoteIdentifierIfNeeded(col.table)}.*` : '*';
555
- } else {
556
- let colStr = expressionToString(col.expr);
557
- if (col.alias) colStr += ` as ${quoteIdentifierIfNeeded(col.alias)}`;
558
- return colStr;
559
- }
560
- });
561
- parts.push('returning', returning.join(', '));
562
- }
563
-
564
- return parts.join(' ');
565
- }
566
-
567
- export function deleteToString(stmt: AST.DeleteStmt): string {
568
- const parts: string[] = [];
569
-
570
- if (stmt.withClause) {
571
- parts.push(withClauseToString(stmt.withClause));
572
- }
573
-
574
- parts.push('delete from', expressionToString(stmt.table));
575
-
576
- if (stmt.where) {
577
- parts.push('where', expressionToString(stmt.where));
578
- }
579
-
580
- if (stmt.returning && stmt.returning.length > 0) {
581
- const returning = stmt.returning.map(col => {
582
- if (col.type === 'all') {
583
- return col.table ? `${quoteIdentifierIfNeeded(col.table)}.*` : '*';
584
- } else {
585
- let colStr = expressionToString(col.expr);
586
- if (col.alias) colStr += ` as ${quoteIdentifierIfNeeded(col.alias)}`;
587
- return colStr;
588
- }
589
- });
590
- parts.push('returning', returning.join(', '));
591
- }
592
-
593
- return parts.join(' ');
594
- }
595
-
596
- export function valuesToString(stmt: AST.ValuesStmt): string {
597
- const valueRows = stmt.values.map(row =>
598
- `(${row.map(expressionToString).join(', ')})`
599
- );
600
- return `values ${valueRows.join(', ')}`;
601
- }
602
-
603
- export function createIndexToString(stmt: AST.CreateIndexStmt): string {
604
- const parts: string[] = ['create'];
605
- if (stmt.isUnique) parts.push('unique');
606
- parts.push('index');
607
- if (stmt.ifNotExists) parts.push('if not exists');
608
-
609
- parts.push(expressionToString(stmt.index), 'on', expressionToString(stmt.table));
610
-
611
- const columns = stmt.columns.map(col => {
612
- if (col.name) {
613
- let colStr = quoteIdentifierIfNeeded(col.name);
614
- if (col.collation) colStr += ` collate ${col.collation.toLowerCase()}`;
615
- if (col.direction === 'desc') colStr += ' desc';
616
- return colStr;
617
- } else if (col.expr) {
618
- return expressionToString(col.expr);
619
- }
620
- return '';
621
- }).filter(s => s);
622
-
623
- parts.push(`(${columns.join(', ')})`);
624
-
625
- if (stmt.where) {
626
- parts.push('where', expressionToString(stmt.where));
627
- }
628
-
629
- return parts.join(' ');
630
- }
631
-
632
- export function createViewToString(stmt: AST.CreateViewStmt): string {
633
- const parts: string[] = ['create'];
634
- if (stmt.isTemporary) parts.push('temp');
635
- parts.push('view');
636
- if (stmt.ifNotExists) parts.push('if not exists');
637
-
638
- parts.push(expressionToString(stmt.view));
639
-
640
- if (stmt.columns && stmt.columns.length > 0) {
641
- parts.push(`(${stmt.columns.map(quoteIdentifierIfNeeded).join(', ')})`);
642
- }
643
-
644
- parts.push('as', selectToString(stmt.select));
645
-
646
- return parts.join(' ');
647
- }
648
-
649
- function dropToString(stmt: AST.DropStmt): string {
650
- const parts: string[] = ['drop', stmt.objectType.toLowerCase()];
651
- if (stmt.ifExists) parts.push('if exists');
652
- parts.push(expressionToString(stmt.name));
653
- return parts.join(' ');
654
- }
655
-
656
- function beginToString(stmt: AST.BeginStmt): string {
657
- return 'begin transaction';
658
- }
659
-
660
- function rollbackToString(stmt: AST.RollbackStmt): string {
661
- let result = 'rollback';
662
- if (stmt.savepoint) {
663
- result += ` to ${stmt.savepoint}`;
664
- }
665
- return result;
666
- }
667
-
668
- function savepointToString(stmt: AST.SavepointStmt): string {
669
- return `savepoint ${stmt.name}`;
670
- }
671
-
672
- function releaseToString(stmt: AST.ReleaseStmt): string {
673
- let result = 'release';
674
- if (stmt.savepoint) {
675
- result += ` ${stmt.savepoint}`;
676
- }
677
- return result;
678
- }
679
-
680
- function pragmaToString(stmt: AST.PragmaStmt): string {
681
- let result = `pragma ${stmt.name.toLowerCase()}`;
682
- if (stmt.value) {
683
- result += ` = ${expressionToString(stmt.value)}`;
684
- }
685
- return result;
686
- }
687
-
688
- function declareSchemaToString(stmt: AST.DeclareSchemaStmt): string {
689
- let s = `declare schema ${quoteIdentifierIfNeeded(stmt.schemaName || 'main')}`;
690
- if (stmt.version) s += ` version '${stmt.version}'`;
691
- if (stmt.using && (stmt.using.defaultVtabModule || stmt.using.defaultVtabArgs)) {
692
- const opts: string[] = [];
693
- if (stmt.using.defaultVtabModule) opts.push(`default_vtab_module = '${stmt.using.defaultVtabModule}'`);
694
- if (stmt.using.defaultVtabArgs) opts.push(`default_vtab_args = '${stmt.using.defaultVtabArgs}'`);
695
- s += ` using (${opts.join(', ')})`;
696
- }
697
- s += ' {';
698
- for (const it of stmt.items) {
699
- s += ' ' + declareItemToString(it) + ';';
700
- }
701
- s += ' }';
702
- return s;
703
- }
704
-
705
- function declareItemToString(it: AST.DeclareItem): string {
706
- if (it.type === 'declaredTable') {
707
- return `table ${it.tableStmt.table.name} { ... }`;
708
- }
709
- if (it.type === 'declaredIndex') {
710
- return `index ${it.indexStmt.index.name} on ${it.indexStmt.table.name} (...)`;
711
- }
712
- if (it.type === 'declaredView') {
713
- return `view ${it.viewStmt.view.name} as ...`;
714
- }
715
- if (it.type === 'declaredSeed') {
716
- const rowsStr = it.seedData?.map(r => `(${r.map(v => JSON.stringify(v)).join(', ')})`).join(', ') || '';
717
- return `seed ${it.tableName} (${rowsStr})`;
718
- }
719
- return (it as unknown as AST.DeclareIgnoredItem).text || '-- ignored';
720
- }
721
-
722
- // Helper to stringify conflict clauses
723
- function conflictToString(res: ConflictResolution | undefined): string {
724
- // ABORT is the default, so don't emit it
725
- if (!res || res === ConflictResolution.ABORT) return '';
726
- // Assuming ConflictResolution enum values are uppercase, convert them to lowercase
727
- return ` on conflict ${ConflictResolution[res].toLowerCase()}`;
728
- }
729
-
730
- // Helper to stringify column constraints
731
- function columnConstraintsToString(constraints: AST.ColumnConstraint[]): string {
732
- return constraints.map(c => {
733
- let s = '';
734
- if (c.name) s += `constraint ${quoteIdentifierIfNeeded(c.name)} `;
735
- switch (c.type) {
736
- case 'primaryKey':
737
- s += 'primary key';
738
- // ASC is default, only specify DESC
739
- if (c.direction === 'desc') s += ` desc`;
740
- s += conflictToString(c.onConflict);
741
- if (c.autoincrement) s += ' autoincrement';
742
- break;
743
- case 'notNull':
744
- s += 'not null';
745
- s += conflictToString(c.onConflict);
746
- break;
747
- case 'null':
748
- s += 'null';
749
- s += conflictToString(c.onConflict);
750
- break;
751
- case 'unique':
752
- s += 'unique';
753
- s += conflictToString(c.onConflict);
754
- break;
755
- case 'check':
756
- s += `check (${expressionToString(c.expr!)})`;
757
- break;
758
- case 'default':
759
- s += `default ${expressionToString(c.expr!)}`;
760
- break;
761
- case 'collate':
762
- s += `collate ${c.collation!.toLowerCase()}`;
763
- break;
764
- case 'foreignKey':
765
- if (c.foreignKey) {
766
- const fk = c.foreignKey;
767
- s += `references ${quoteIdentifierIfNeeded(fk.table)}`;
768
- if (fk.columns && fk.columns.length > 0) {
769
- s += `(${fk.columns.map(quoteIdentifierIfNeeded).join(', ')})`;
770
- }
771
- if (fk.onDelete) s += ` on delete ${foreignKeyActionToString(fk.onDelete)}`;
772
- if (fk.onUpdate) s += ` on update ${foreignKeyActionToString(fk.onUpdate)}`;
773
- }
774
- break;
775
- case 'generated':
776
- s += `generated always as (${expressionToString(c.generated!.expr)})`;
777
- // VIRTUAL is default, only specify STORED
778
- if (c.generated!.stored) s += ' stored';
779
- break;
780
- }
781
- return s;
782
- }).filter(s => s.length > 0).join(' ');
783
- }
784
-
785
- // Helper to stringify table constraints
786
- function tableConstraintsToString(constraints: AST.TableConstraint[]): string {
787
- return constraints.map(c => {
788
- let s = '';
789
- if (c.name) s += `constraint ${quoteIdentifierIfNeeded(c.name)} `;
790
- switch (c.type) {
791
- case 'primaryKey':
792
- // ASC is default, only specify DESC
793
- s += `primary key (${c.columns!.map(col => `${quoteIdentifierIfNeeded(col.name)}${col.direction === 'desc' ? ' desc' : ''}`).join(', ')})`;
794
- s += conflictToString(c.onConflict);
795
- break;
796
- case 'unique':
797
- s += `unique (${c.columns!.map(col => quoteIdentifierIfNeeded(col.name)).join(', ')})`;
798
- s += conflictToString(c.onConflict);
799
- break;
800
- case 'check':
801
- s += `check (${expressionToString(c.expr!)})`;
802
- break;
803
- case 'foreignKey':
804
- if (c.foreignKey) {
805
- const fk = c.foreignKey;
806
- s += `foreign key (${c.columns!.map(col => quoteIdentifierIfNeeded(col.name)).join(', ')}) references ${quoteIdentifierIfNeeded(fk.table)}`;
807
- if (fk.columns && fk.columns.length > 0) {
808
- s += `(${fk.columns.map(quoteIdentifierIfNeeded).join(', ')})`;
809
- }
810
- if (fk.onDelete) s += ` on delete ${foreignKeyActionToString(fk.onDelete)}`;
811
- if (fk.onUpdate) s += ` on update ${foreignKeyActionToString(fk.onUpdate)}`;
812
- }
813
- break;
814
- }
815
- return s;
816
- }).filter(s => s.length > 0).join(', ');
817
- }
818
-
819
- function foreignKeyActionToString(action: AST.ForeignKeyAction): string {
820
- switch (action) {
821
- case 'setNull': return 'set null';
822
- case 'setDefault': return 'set default';
823
- case 'cascade': return 'cascade';
824
- case 'restrict': return 'restrict';
825
- case 'noAction': return 'no action';
826
- }
827
- }
828
-
829
- export function createTableToString(stmt: AST.CreateTableStmt): string {
830
- const parts: string[] = ['create'];
831
- if (stmt.isTemporary) parts.push('temp');
832
- parts.push('table');
833
- if (stmt.ifNotExists) parts.push('if not exists');
834
- // Handle schema.table quoting
835
- const tableName = quoteIdentifierIfNeeded(stmt.table.name);
836
- const schemaName = stmt.table.schema ? quoteIdentifierIfNeeded(stmt.table.schema) : undefined;
837
- parts.push(schemaName ? `${schemaName}.${tableName}` : tableName);
838
-
839
- const definitions: string[] = [];
840
- stmt.columns.forEach(col => {
841
- let colDef = quoteIdentifierIfNeeded(col.name);
842
- if (col.dataType) colDef += ` ${col.dataType}`; // Keep data type casing as is
843
- const constraints = columnConstraintsToString(col.constraints);
844
- if (constraints) colDef += ` ${constraints}`;
845
- definitions.push(colDef);
846
- });
847
-
848
- const tableConstraints = tableConstraintsToString(stmt.constraints);
849
- if (tableConstraints) definitions.push(tableConstraints);
850
-
851
- parts.push(`(${definitions.join(', ')})`);
852
-
853
- if (stmt.moduleName) {
854
- parts.push('using', stmt.moduleName);
855
- if (stmt.moduleArgs && Object.keys(stmt.moduleArgs).length > 0) {
856
- const args = Object.entries(stmt.moduleArgs).map(([key, value]) =>
857
- `${quoteIdentifierIfNeeded(key)} = ${JSON.stringify(value)}`
858
- ).join(', ');
859
- parts.push(`(${args})`);
860
- }
861
- }
862
-
863
- return parts.join(' ');
864
- }
1
+ /**
2
+ * Functions to convert DDL AST nodes back into SQL strings.
3
+ *
4
+ * Formatting Notes:
5
+ * - Emits lowercase SQL keywords.
6
+ * - Quotes identifiers (table/column names) using double quotes.
7
+ * - String literals are escaped.
8
+ * - Omits clauses that represent the default SQLite behavior:
9
+ * - `ON CONFLICT ABORT`
10
+ * - `ASC` direction for primary keys
11
+ * - `VIRTUAL` storage for generated columns
12
+ * - (TODO: `FOREIGN KEY` default actions and deferrability)
13
+ */
14
+ import type * as AST from '../parser/ast.js';
15
+ import { ConflictResolution } from '../common/constants.js';
16
+ import { KEYWORDS } from '../parser/lexer.js';
17
+
18
+ // --- Identifier Quoting Logic ---
19
+
20
+ // Basic check for valid SQL identifiers (adjust regex as needed)
21
+ const isValidIdentifier = (name: string): boolean => {
22
+ return /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(name);
23
+ };
24
+
25
+ /**
26
+ * Quotes an identifier (table, column, etc.) with double quotes if necessary.
27
+ * Quoting is needed if the identifier:
28
+ * - Is a reserved keyword (case-insensitive).
29
+ * - Does not match the valid identifier pattern (starts with letter/_, contains letters/numbers/_).
30
+ */
31
+ function quoteIdentifierIfNeeded(name: string): string {
32
+ if (Object.hasOwn(KEYWORDS, name.toLowerCase()) || !isValidIdentifier(name)) {
33
+ return `"${name.replace(/"/g, '""')}"`; // Escape internal quotes
34
+ }
35
+ return name;
36
+ }
37
+
38
+ // Main function to convert any AST node to SQL string
39
+ export function astToString(node: AST.AstNode): string {
40
+ switch (node.type) {
41
+ // Expression types
42
+ case 'literal':
43
+ case 'identifier':
44
+ case 'column':
45
+ case 'binary':
46
+ case 'unary':
47
+ case 'function':
48
+ case 'cast':
49
+ case 'parameter':
50
+ case 'subquery':
51
+ case 'collate':
52
+ case 'case':
53
+ case 'windowFunction':
54
+ return expressionToString(node as AST.Expression);
55
+
56
+ // Statement types
57
+ case 'select':
58
+ return selectToString(node as AST.SelectStmt);
59
+ case 'insert':
60
+ return insertToString(node as AST.InsertStmt);
61
+ case 'update':
62
+ return updateToString(node as AST.UpdateStmt);
63
+ case 'delete':
64
+ return deleteToString(node as AST.DeleteStmt);
65
+ case 'values':
66
+ return valuesToString(node as AST.ValuesStmt);
67
+ case 'createTable':
68
+ return createTableToString(node as AST.CreateTableStmt);
69
+ case 'createIndex':
70
+ return createIndexToString(node as AST.CreateIndexStmt);
71
+ case 'createView':
72
+ return createViewToString(node as AST.CreateViewStmt);
73
+ case 'drop':
74
+ return dropToString(node as AST.DropStmt);
75
+ case 'begin':
76
+ return beginToString(node as AST.BeginStmt);
77
+ case 'commit':
78
+ return 'commit';
79
+ case 'rollback':
80
+ return rollbackToString(node as AST.RollbackStmt);
81
+ case 'savepoint':
82
+ return savepointToString(node as AST.SavepointStmt);
83
+ case 'release':
84
+ return releaseToString(node as AST.ReleaseStmt);
85
+ case 'pragma':
86
+ return pragmaToString(node as AST.PragmaStmt);
87
+ case 'declareSchema':
88
+ return declareSchemaToString(node as unknown as AST.DeclareSchemaStmt);
89
+ case 'diffSchema':
90
+ return `diff schema ${(node as unknown as AST.DiffSchemaStmt).schemaName || 'main'}`;
91
+ case 'applySchema': {
92
+ const n = node as unknown as AST.ApplySchemaStmt;
93
+ let s = `apply schema ${n.schemaName || 'main'}`;
94
+ if (n.toVersion) s += ` to version '${n.toVersion}'`;
95
+ if (n.withSeed) s += ' with seed';
96
+ if (n.options) {
97
+ s += ' options (';
98
+ const parts: string[] = [];
99
+ if (n.options.dryRun !== undefined) parts.push(`dry_run = ${n.options.dryRun ? 'true' : 'false'}`);
100
+ if (n.options.validateOnly !== undefined) parts.push(`validate_only = ${n.options.validateOnly ? 'true' : 'false'}`);
101
+ if (n.options.allowDestructive !== undefined) parts.push(`allow_destructive = ${n.options.allowDestructive ? 'true' : 'false'}`);
102
+ if (n.options.renamePolicy) parts.push(`rename_policy = '${n.options.renamePolicy}'`);
103
+ s += parts.join(', ') + ')';
104
+ }
105
+ return s;
106
+ }
107
+ case 'explainSchema':
108
+ return `explain schema ${(node as unknown as AST.ExplainSchemaStmt).schemaName || 'main'}`;
109
+
110
+ default:
111
+ return `[${node.type}]`; // Fallback for unknown node types
112
+ }
113
+ }
114
+
115
+ // Helper to stringify expressions (extended from original)
116
+ export function expressionToString(expr: AST.Expression): string {
117
+ switch (expr.type) {
118
+ case 'literal': {
119
+ // Prefer original lexeme for numbers if available and different
120
+ if ((typeof expr.value === 'number' || typeof expr.value === 'bigint') && expr.lexeme && expr.lexeme !== String(expr.value)) {
121
+ return expr.lexeme;
122
+ }
123
+ // Prefer original lexeme for NULL if available
124
+ if (expr.value === null) return expr.lexeme?.toLowerCase() || 'null';
125
+ if (typeof expr.value === 'string') return `'${expr.value.replace(/'/g, "''")}'`; // Escape single quotes
126
+ if (typeof expr.value === 'number') return expr.value.toString();
127
+ if (expr.value instanceof Uint8Array) {
128
+ const hex = Buffer.from(expr.value).toString('hex');
129
+ return `x'${hex}'`;
130
+ }
131
+ return String(expr.value);
132
+ }
133
+
134
+ case 'identifier': {
135
+ let identStr = quoteIdentifierIfNeeded(expr.name);
136
+ if (expr.schema) {
137
+ identStr = `${quoteIdentifierIfNeeded(expr.schema)}.${identStr}`;
138
+ }
139
+ return identStr;
140
+ }
141
+
142
+ case 'column': {
143
+ let colStr = quoteIdentifierIfNeeded(expr.name);
144
+ if (expr.table) {
145
+ colStr = `${quoteIdentifierIfNeeded(expr.table)}.${colStr}`;
146
+ if (expr.schema) {
147
+ colStr = `${quoteIdentifierIfNeeded(expr.schema)}.${colStr}`;
148
+ }
149
+ }
150
+ return colStr;
151
+ }
152
+
153
+ case 'binary': {
154
+ const leftStr = needsParens(expr.left, expr.operator, 'left')
155
+ ? `(${expressionToString(expr.left)})`
156
+ : expressionToString(expr.left);
157
+ const rightStr = needsParens(expr.right, expr.operator, 'right')
158
+ ? `(${expressionToString(expr.right)})`
159
+ : expressionToString(expr.right);
160
+ return `${leftStr} ${expr.operator.toLowerCase()} ${rightStr}`;
161
+ }
162
+
163
+ case 'unary': {
164
+ const exprStr = expr.expr.type === 'binary'
165
+ ? `(${expressionToString(expr.expr)})`
166
+ : expressionToString(expr.expr);
167
+ // Handle postfix operators like IS NULL, IS NOT NULL
168
+ if (expr.operator === 'IS NULL' || expr.operator === 'IS NOT NULL') {
169
+ return `${exprStr} ${expr.operator.toLowerCase()}`;
170
+ } else if (expr.operator.toUpperCase() === 'NOT') {
171
+ return `${expr.operator.toLowerCase()} ${exprStr}`;
172
+ }
173
+ return `${expr.operator.toLowerCase()}${exprStr}`;
174
+ }
175
+
176
+ case 'function': {
177
+ if (expr.name.toLowerCase() === 'count' && expr.args.length === 0) {
178
+ return 'count(*)';
179
+ }
180
+ const argsStr = expr.args.map(arg => expressionToString(arg)).join(', ');
181
+ const distinctStr = expr.distinct ? 'distinct ' : '';
182
+ return `${expr.name.toLowerCase()}(${distinctStr}${argsStr})`;
183
+ }
184
+
185
+ case 'cast':
186
+ return `cast(${expressionToString(expr.expr)} as ${expr.targetType.toLowerCase()})`;
187
+
188
+ case 'parameter': {
189
+ if (expr.index !== undefined) {
190
+ return '?';
191
+ } else if (expr.name) {
192
+ return expr.name.startsWith(':') || expr.name.startsWith('$')
193
+ ? expr.name
194
+ : `:${expr.name}`;
195
+ }
196
+ return '?';
197
+ }
198
+
199
+ case 'subquery':
200
+ return `(${selectToString(expr.query)})`;
201
+
202
+ case 'exists':
203
+ return `exists (${selectToString((expr as AST.ExistsExpr).subquery)})`;
204
+
205
+ case 'in': {
206
+ const inExpr = expr as AST.InExpr;
207
+ let result = expressionToString(inExpr.expr) + ' in ';
208
+ if (inExpr.values) {
209
+ result += `(${inExpr.values.map(expressionToString).join(', ')})`;
210
+ } else if (inExpr.subquery) {
211
+ result += `(${selectToString(inExpr.subquery)})`;
212
+ }
213
+ return result;
214
+ }
215
+
216
+ case 'between': {
217
+ const betweenExpr = expr as AST.BetweenExpr;
218
+ const exprStr = expressionToString(betweenExpr.expr);
219
+ const lowerStr = expressionToString(betweenExpr.lower);
220
+ const upperStr = expressionToString(betweenExpr.upper);
221
+ const notStr = betweenExpr.not ? 'not ' : '';
222
+ return `${exprStr} ${notStr}between ${lowerStr} and ${upperStr}`;
223
+ }
224
+
225
+ case 'collate':
226
+ return `${expressionToString(expr.expr)} collate ${expr.collation.toLowerCase()}`;
227
+
228
+ case 'case': {
229
+ // TODO: preserve and emit with original case
230
+ let caseStr = 'case';
231
+ if (expr.baseExpr) {
232
+ caseStr += ` ${expressionToString(expr.baseExpr)}`;
233
+ }
234
+ for (const clause of expr.whenThenClauses) {
235
+ caseStr += ` when ${expressionToString(clause.when)} then ${expressionToString(clause.then)}`;
236
+ }
237
+ if (expr.elseExpr) {
238
+ caseStr += ` else ${expressionToString(expr.elseExpr)}`;
239
+ }
240
+ caseStr += ' end';
241
+ return caseStr;
242
+ }
243
+
244
+ case 'windowFunction': {
245
+ let winStr = expressionToString(expr.function);
246
+ if (expr.window) {
247
+ winStr += ` over (${windowDefinitionToString(expr.window)})`;
248
+ }
249
+ return winStr;
250
+ }
251
+
252
+ default:
253
+ return '[unknown_expr]';
254
+ }
255
+ }
256
+
257
+ // Helper to determine if parentheses are needed for binary operations
258
+ function needsParens(expr: AST.Expression, parentOp: string, side: 'left' | 'right'): boolean {
259
+ if (expr.type !== 'binary') return false;
260
+
261
+ const precedence: Record<string, number> = {
262
+ 'OR': 1, 'AND': 2, 'NOT': 3, '=': 4, '!=': 4, '<': 4, '<=': 4, '>': 4, '>=': 4,
263
+ 'LIKE': 4, 'IN': 4, 'IS': 4, '+': 5, '-': 5, '*': 6, '/': 6, '%': 6
264
+ };
265
+
266
+ const parentPrec = precedence[parentOp.toUpperCase()] || 0;
267
+ const childPrec = precedence[expr.operator.toUpperCase()] || 0;
268
+
269
+ if (childPrec < parentPrec) return true;
270
+ if (childPrec === parentPrec && side === 'right' && !isAssociative(parentOp)) return true;
271
+
272
+ return false;
273
+ }
274
+
275
+ function isAssociative(op: string): boolean {
276
+ const associativeOps = ['AND', 'OR', '+', '*'];
277
+ return associativeOps.includes(op.toUpperCase());
278
+ }
279
+
280
+ // Helper for window definitions
281
+ function windowDefinitionToString(win: AST.WindowDefinition): string {
282
+ const parts: string[] = [];
283
+
284
+ if (win.partitionBy && win.partitionBy.length > 0) {
285
+ parts.push(`partition by ${win.partitionBy.map(expressionToString).join(', ')}`);
286
+ }
287
+
288
+ if (win.orderBy && win.orderBy.length > 0) {
289
+ const orderParts = win.orderBy.map(clause => {
290
+ let orderStr = expressionToString(clause.expr);
291
+ if (clause.direction === 'desc') orderStr += ' desc';
292
+ if (clause.nulls) orderStr += ` nulls ${clause.nulls.toLowerCase()}`;
293
+ return orderStr;
294
+ });
295
+ parts.push(`order by ${orderParts.join(', ')}`);
296
+ }
297
+
298
+ if (win.frame) {
299
+ parts.push(windowFrameToString(win.frame));
300
+ }
301
+
302
+ return parts.join(' ');
303
+ }
304
+
305
+ function windowFrameToString(frame: AST.WindowFrame): string {
306
+ let frameStr = frame.type.toLowerCase(); // 'rows' or 'range'
307
+
308
+ if (frame.end) {
309
+ frameStr += ` between ${windowFrameBoundToString(frame.start)} and ${windowFrameBoundToString(frame.end)}`;
310
+ } else {
311
+ frameStr += ` ${windowFrameBoundToString(frame.start)}`;
312
+ }
313
+
314
+ if (frame.exclusion) {
315
+ frameStr += ` exclude ${frame.exclusion.toLowerCase()}`;
316
+ }
317
+
318
+ return frameStr;
319
+ }
320
+
321
+ function windowFrameBoundToString(bound: AST.WindowFrameBound): string {
322
+ switch (bound.type) {
323
+ case 'currentRow': return 'current row';
324
+ case 'unboundedPreceding': return 'unbounded preceding';
325
+ case 'unboundedFollowing': return 'unbounded following';
326
+ case 'preceding': return `${expressionToString(bound.value)} preceding`;
327
+ case 'following': return `${expressionToString(bound.value)} following`;
328
+ default: return '[unknown_bound]';
329
+ }
330
+ }
331
+
332
+ // Statement stringify functions
333
+ export function selectToString(stmt: AST.SelectStmt): string {
334
+ const parts: string[] = [];
335
+
336
+ if (stmt.withClause) {
337
+ parts.push(withClauseToString(stmt.withClause));
338
+ }
339
+
340
+ parts.push('select');
341
+
342
+ if (stmt.distinct) parts.push('distinct');
343
+ if (stmt.all) parts.push('all');
344
+
345
+ const columns = stmt.columns.map(col => {
346
+ if (col.type === 'all') {
347
+ return col.table ? `${quoteIdentifierIfNeeded(col.table)}.*` : '*';
348
+ } else {
349
+ let colStr = expressionToString(col.expr);
350
+ if (col.alias) colStr += ` as ${quoteIdentifierIfNeeded(col.alias)}`;
351
+ return colStr;
352
+ }
353
+ });
354
+ parts.push(columns.join(', '));
355
+
356
+ if (stmt.from && stmt.from.length > 0) {
357
+ parts.push('from', stmt.from.map(fromClauseToString).join(', '));
358
+ }
359
+
360
+ if (stmt.where) {
361
+ parts.push('where', expressionToString(stmt.where));
362
+ }
363
+
364
+ if (stmt.groupBy && stmt.groupBy.length > 0) {
365
+ parts.push('group by', stmt.groupBy.map(expressionToString).join(', '));
366
+ }
367
+
368
+ if (stmt.having) {
369
+ parts.push('having', expressionToString(stmt.having));
370
+ }
371
+
372
+ if (stmt.orderBy && stmt.orderBy.length > 0) {
373
+ const orderParts = stmt.orderBy.map(clause => {
374
+ let orderStr = expressionToString(clause.expr);
375
+ if (clause.direction === 'desc') orderStr += ' desc';
376
+ if (clause.nulls) orderStr += ` nulls ${clause.nulls.toLowerCase()}`;
377
+ return orderStr;
378
+ });
379
+ parts.push('order by', orderParts.join(', '));
380
+ }
381
+
382
+ if (stmt.limit) {
383
+ parts.push('limit', expressionToString(stmt.limit));
384
+ }
385
+
386
+ if (stmt.offset) {
387
+ parts.push('offset', expressionToString(stmt.offset));
388
+ }
389
+
390
+ let result = parts.join(' ');
391
+
392
+ if (stmt.union) {
393
+ result += stmt.unionAll ? ' union all ' : ' union ';
394
+ result += selectToString(stmt.union);
395
+ }
396
+
397
+ return result;
398
+ }
399
+
400
+ function withClauseToString(withClause: AST.WithClause): string {
401
+ let result = 'with';
402
+ if (withClause.recursive) result += ' recursive';
403
+
404
+ const ctes = withClause.ctes.map(cte => {
405
+ let cteStr = quoteIdentifierIfNeeded(cte.name);
406
+ if (cte.columns && cte.columns.length > 0) {
407
+ cteStr += ` (${cte.columns.map(quoteIdentifierIfNeeded).join(', ')})`;
408
+ }
409
+ cteStr += ` as (${astToString(cte.query)})`;
410
+ return cteStr;
411
+ });
412
+
413
+ result += ` ${ctes.join(', ')}`;
414
+
415
+ // Add OPTION clause if present
416
+ if (withClause.options?.maxRecursion !== undefined) {
417
+ result += ` option (maxrecursion ${withClause.options.maxRecursion})`;
418
+ }
419
+
420
+ return result;
421
+ }
422
+
423
+ function fromClauseToString(from: AST.FromClause): string {
424
+ switch (from.type) {
425
+ case 'table': {
426
+ let tableStr = quoteIdentifierIfNeeded(from.table.name);
427
+ if (from.table.schema) {
428
+ tableStr = `${quoteIdentifierIfNeeded(from.table.schema)}.${tableStr}`;
429
+ }
430
+ if (from.alias) tableStr += ` as ${quoteIdentifierIfNeeded(from.alias)}`;
431
+ return tableStr;
432
+ }
433
+
434
+ case 'subquerySource': {
435
+ let subqueryStr: string;
436
+ if (from.subquery.type === 'select') {
437
+ subqueryStr = selectToString(from.subquery);
438
+ } else if (from.subquery.type === 'values') {
439
+ subqueryStr = valuesToString(from.subquery);
440
+ } else {
441
+ // Handle the case where subquery type is not recognized
442
+ const exhaustiveCheck: never = from.subquery;
443
+ subqueryStr = astToString(exhaustiveCheck);
444
+ }
445
+
446
+ let aliasStr = `as ${quoteIdentifierIfNeeded(from.alias)}`;
447
+ if (from.columns && from.columns.length > 0) {
448
+ aliasStr += ` (${from.columns.map(quoteIdentifierIfNeeded).join(', ')})`;
449
+ }
450
+
451
+ return `(${subqueryStr}) ${aliasStr}`;
452
+ }
453
+
454
+ case 'functionSource': {
455
+ const args = from.args.map(expressionToString).join(', ');
456
+ // Check if from.name is a function expression or identifier expression
457
+ let funcName: string;
458
+ if (from.name.type === 'identifier') {
459
+ funcName = from.name.name.toLowerCase();
460
+ } else if (from.name.type === 'function') {
461
+ funcName = expressionToString(from.name);
462
+ } else {
463
+ funcName = expressionToString(from.name);
464
+ }
465
+ let funcStr = `${funcName}(${args})`;
466
+ if (from.alias) funcStr += ` as ${quoteIdentifierIfNeeded(from.alias)}`;
467
+ return funcStr;
468
+ }
469
+
470
+ case 'join': {
471
+ const leftStr = fromClauseToString(from.left);
472
+ const rightStr = fromClauseToString(from.right);
473
+ let joinStr = `${leftStr} ${from.joinType.toLowerCase()} join ${rightStr}`;
474
+ if (from.condition) {
475
+ joinStr += ` on ${expressionToString(from.condition)}`;
476
+ } else if (from.columns) {
477
+ joinStr += ` using (${from.columns.map(quoteIdentifierIfNeeded).join(', ')})`;
478
+ }
479
+ return joinStr;
480
+ }
481
+
482
+ default:
483
+ return '[unknown_from]';
484
+ }
485
+ }
486
+
487
+ export function insertToString(stmt: AST.InsertStmt): string {
488
+ const parts: string[] = [];
489
+
490
+ if (stmt.withClause) {
491
+ parts.push(withClauseToString(stmt.withClause));
492
+ }
493
+
494
+ parts.push('insert into', expressionToString(stmt.table));
495
+
496
+ if (stmt.columns && stmt.columns.length > 0) {
497
+ parts.push(`(${stmt.columns.map(quoteIdentifierIfNeeded).join(', ')})`);
498
+ }
499
+
500
+ if (stmt.values) {
501
+ const valueRows = stmt.values.map(row =>
502
+ `(${row.map(expressionToString).join(', ')})`
503
+ );
504
+ parts.push('values', valueRows.join(', '));
505
+ } else if (stmt.select) {
506
+ parts.push(selectToString(stmt.select));
507
+ }
508
+
509
+ if (stmt.onConflict && stmt.onConflict !== ConflictResolution.ABORT) {
510
+ parts.push(`on conflict ${ConflictResolution[stmt.onConflict].toLowerCase()}`);
511
+ }
512
+
513
+ if (stmt.returning && stmt.returning.length > 0) {
514
+ const returning = stmt.returning.map(col => {
515
+ if (col.type === 'all') {
516
+ return col.table ? `${quoteIdentifierIfNeeded(col.table)}.*` : '*';
517
+ } else {
518
+ let colStr = expressionToString(col.expr);
519
+ if (col.alias) colStr += ` as ${quoteIdentifierIfNeeded(col.alias)}`;
520
+ return colStr;
521
+ }
522
+ });
523
+ parts.push('returning', returning.join(', '));
524
+ }
525
+
526
+ return parts.join(' ');
527
+ }
528
+
529
+ export function updateToString(stmt: AST.UpdateStmt): string {
530
+ const parts: string[] = [];
531
+
532
+ if (stmt.withClause) {
533
+ parts.push(withClauseToString(stmt.withClause));
534
+ }
535
+
536
+ parts.push('update', expressionToString(stmt.table), 'set');
537
+
538
+ const assignments = stmt.assignments.map(assign =>
539
+ `${quoteIdentifierIfNeeded(assign.column)} = ${expressionToString(assign.value)}`
540
+ );
541
+ parts.push(assignments.join(', '));
542
+
543
+ if (stmt.where) {
544
+ parts.push('where', expressionToString(stmt.where));
545
+ }
546
+
547
+ if (stmt.onConflict && stmt.onConflict !== ConflictResolution.ABORT) {
548
+ parts.push(`on conflict ${ConflictResolution[stmt.onConflict].toLowerCase()}`);
549
+ }
550
+
551
+ if (stmt.returning && stmt.returning.length > 0) {
552
+ const returning = stmt.returning.map(col => {
553
+ if (col.type === 'all') {
554
+ return col.table ? `${quoteIdentifierIfNeeded(col.table)}.*` : '*';
555
+ } else {
556
+ let colStr = expressionToString(col.expr);
557
+ if (col.alias) colStr += ` as ${quoteIdentifierIfNeeded(col.alias)}`;
558
+ return colStr;
559
+ }
560
+ });
561
+ parts.push('returning', returning.join(', '));
562
+ }
563
+
564
+ return parts.join(' ');
565
+ }
566
+
567
+ export function deleteToString(stmt: AST.DeleteStmt): string {
568
+ const parts: string[] = [];
569
+
570
+ if (stmt.withClause) {
571
+ parts.push(withClauseToString(stmt.withClause));
572
+ }
573
+
574
+ parts.push('delete from', expressionToString(stmt.table));
575
+
576
+ if (stmt.where) {
577
+ parts.push('where', expressionToString(stmt.where));
578
+ }
579
+
580
+ if (stmt.returning && stmt.returning.length > 0) {
581
+ const returning = stmt.returning.map(col => {
582
+ if (col.type === 'all') {
583
+ return col.table ? `${quoteIdentifierIfNeeded(col.table)}.*` : '*';
584
+ } else {
585
+ let colStr = expressionToString(col.expr);
586
+ if (col.alias) colStr += ` as ${quoteIdentifierIfNeeded(col.alias)}`;
587
+ return colStr;
588
+ }
589
+ });
590
+ parts.push('returning', returning.join(', '));
591
+ }
592
+
593
+ return parts.join(' ');
594
+ }
595
+
596
+ export function valuesToString(stmt: AST.ValuesStmt): string {
597
+ const valueRows = stmt.values.map(row =>
598
+ `(${row.map(expressionToString).join(', ')})`
599
+ );
600
+ return `values ${valueRows.join(', ')}`;
601
+ }
602
+
603
+ export function createIndexToString(stmt: AST.CreateIndexStmt): string {
604
+ const parts: string[] = ['create'];
605
+ if (stmt.isUnique) parts.push('unique');
606
+ parts.push('index');
607
+ if (stmt.ifNotExists) parts.push('if not exists');
608
+
609
+ parts.push(expressionToString(stmt.index), 'on', expressionToString(stmt.table));
610
+
611
+ const columns = stmt.columns.map(col => {
612
+ if (col.name) {
613
+ let colStr = quoteIdentifierIfNeeded(col.name);
614
+ if (col.collation) colStr += ` collate ${col.collation.toLowerCase()}`;
615
+ if (col.direction === 'desc') colStr += ' desc';
616
+ return colStr;
617
+ } else if (col.expr) {
618
+ return expressionToString(col.expr);
619
+ }
620
+ return '';
621
+ }).filter(s => s);
622
+
623
+ parts.push(`(${columns.join(', ')})`);
624
+
625
+ if (stmt.where) {
626
+ parts.push('where', expressionToString(stmt.where));
627
+ }
628
+
629
+ return parts.join(' ');
630
+ }
631
+
632
+ export function createViewToString(stmt: AST.CreateViewStmt): string {
633
+ const parts: string[] = ['create'];
634
+ if (stmt.isTemporary) parts.push('temp');
635
+ parts.push('view');
636
+ if (stmt.ifNotExists) parts.push('if not exists');
637
+
638
+ parts.push(expressionToString(stmt.view));
639
+
640
+ if (stmt.columns && stmt.columns.length > 0) {
641
+ parts.push(`(${stmt.columns.map(quoteIdentifierIfNeeded).join(', ')})`);
642
+ }
643
+
644
+ parts.push('as', selectToString(stmt.select));
645
+
646
+ return parts.join(' ');
647
+ }
648
+
649
+ function dropToString(stmt: AST.DropStmt): string {
650
+ const parts: string[] = ['drop', stmt.objectType.toLowerCase()];
651
+ if (stmt.ifExists) parts.push('if exists');
652
+ parts.push(expressionToString(stmt.name));
653
+ return parts.join(' ');
654
+ }
655
+
656
+ function beginToString(stmt: AST.BeginStmt): string {
657
+ return 'begin transaction';
658
+ }
659
+
660
+ function rollbackToString(stmt: AST.RollbackStmt): string {
661
+ let result = 'rollback';
662
+ if (stmt.savepoint) {
663
+ result += ` to ${stmt.savepoint}`;
664
+ }
665
+ return result;
666
+ }
667
+
668
+ function savepointToString(stmt: AST.SavepointStmt): string {
669
+ return `savepoint ${stmt.name}`;
670
+ }
671
+
672
+ function releaseToString(stmt: AST.ReleaseStmt): string {
673
+ let result = 'release';
674
+ if (stmt.savepoint) {
675
+ result += ` ${stmt.savepoint}`;
676
+ }
677
+ return result;
678
+ }
679
+
680
+ function pragmaToString(stmt: AST.PragmaStmt): string {
681
+ let result = `pragma ${stmt.name.toLowerCase()}`;
682
+ if (stmt.value) {
683
+ result += ` = ${expressionToString(stmt.value)}`;
684
+ }
685
+ return result;
686
+ }
687
+
688
+ function declareSchemaToString(stmt: AST.DeclareSchemaStmt): string {
689
+ let s = `declare schema ${quoteIdentifierIfNeeded(stmt.schemaName || 'main')}`;
690
+ if (stmt.version) s += ` version '${stmt.version}'`;
691
+ if (stmt.using && (stmt.using.defaultVtabModule || stmt.using.defaultVtabArgs)) {
692
+ const opts: string[] = [];
693
+ if (stmt.using.defaultVtabModule) opts.push(`default_vtab_module = '${stmt.using.defaultVtabModule}'`);
694
+ if (stmt.using.defaultVtabArgs) opts.push(`default_vtab_args = '${stmt.using.defaultVtabArgs}'`);
695
+ s += ` using (${opts.join(', ')})`;
696
+ }
697
+ s += ' {';
698
+ for (const it of stmt.items) {
699
+ s += ' ' + declareItemToString(it) + ';';
700
+ }
701
+ s += ' }';
702
+ return s;
703
+ }
704
+
705
+ function declareItemToString(it: AST.DeclareItem): string {
706
+ if (it.type === 'declaredTable') {
707
+ return `table ${it.tableStmt.table.name} { ... }`;
708
+ }
709
+ if (it.type === 'declaredIndex') {
710
+ return `index ${it.indexStmt.index.name} on ${it.indexStmt.table.name} (...)`;
711
+ }
712
+ if (it.type === 'declaredView') {
713
+ return `view ${it.viewStmt.view.name} as ...`;
714
+ }
715
+ if (it.type === 'declaredSeed') {
716
+ const rowsStr = it.seedData?.map(r => `(${r.map(v => JSON.stringify(v)).join(', ')})`).join(', ') || '';
717
+ return `seed ${it.tableName} (${rowsStr})`;
718
+ }
719
+ return (it as unknown as AST.DeclareIgnoredItem).text || '-- ignored';
720
+ }
721
+
722
+ // Helper to stringify conflict clauses
723
+ function conflictToString(res: ConflictResolution | undefined): string {
724
+ // ABORT is the default, so don't emit it
725
+ if (!res || res === ConflictResolution.ABORT) return '';
726
+ // Assuming ConflictResolution enum values are uppercase, convert them to lowercase
727
+ return ` on conflict ${ConflictResolution[res].toLowerCase()}`;
728
+ }
729
+
730
+ // Helper to stringify column constraints
731
+ function columnConstraintsToString(constraints: AST.ColumnConstraint[]): string {
732
+ return constraints.map(c => {
733
+ let s = '';
734
+ if (c.name) s += `constraint ${quoteIdentifierIfNeeded(c.name)} `;
735
+ switch (c.type) {
736
+ case 'primaryKey':
737
+ s += 'primary key';
738
+ // ASC is default, only specify DESC
739
+ if (c.direction === 'desc') s += ` desc`;
740
+ s += conflictToString(c.onConflict);
741
+ if (c.autoincrement) s += ' autoincrement';
742
+ break;
743
+ case 'notNull':
744
+ s += 'not null';
745
+ s += conflictToString(c.onConflict);
746
+ break;
747
+ case 'null':
748
+ s += 'null';
749
+ s += conflictToString(c.onConflict);
750
+ break;
751
+ case 'unique':
752
+ s += 'unique';
753
+ s += conflictToString(c.onConflict);
754
+ break;
755
+ case 'check':
756
+ s += `check (${expressionToString(c.expr!)})`;
757
+ break;
758
+ case 'default':
759
+ s += `default ${expressionToString(c.expr!)}`;
760
+ break;
761
+ case 'collate':
762
+ s += `collate ${c.collation!.toLowerCase()}`;
763
+ break;
764
+ case 'foreignKey':
765
+ if (c.foreignKey) {
766
+ const fk = c.foreignKey;
767
+ s += `references ${quoteIdentifierIfNeeded(fk.table)}`;
768
+ if (fk.columns && fk.columns.length > 0) {
769
+ s += `(${fk.columns.map(quoteIdentifierIfNeeded).join(', ')})`;
770
+ }
771
+ if (fk.onDelete) s += ` on delete ${foreignKeyActionToString(fk.onDelete)}`;
772
+ if (fk.onUpdate) s += ` on update ${foreignKeyActionToString(fk.onUpdate)}`;
773
+ }
774
+ break;
775
+ case 'generated':
776
+ s += `generated always as (${expressionToString(c.generated!.expr)})`;
777
+ // VIRTUAL is default, only specify STORED
778
+ if (c.generated!.stored) s += ' stored';
779
+ break;
780
+ }
781
+ return s;
782
+ }).filter(s => s.length > 0).join(' ');
783
+ }
784
+
785
+ // Helper to stringify table constraints
786
+ function tableConstraintsToString(constraints: AST.TableConstraint[]): string {
787
+ return constraints.map(c => {
788
+ let s = '';
789
+ if (c.name) s += `constraint ${quoteIdentifierIfNeeded(c.name)} `;
790
+ switch (c.type) {
791
+ case 'primaryKey':
792
+ // ASC is default, only specify DESC
793
+ s += `primary key (${c.columns!.map(col => `${quoteIdentifierIfNeeded(col.name)}${col.direction === 'desc' ? ' desc' : ''}`).join(', ')})`;
794
+ s += conflictToString(c.onConflict);
795
+ break;
796
+ case 'unique':
797
+ s += `unique (${c.columns!.map(col => quoteIdentifierIfNeeded(col.name)).join(', ')})`;
798
+ s += conflictToString(c.onConflict);
799
+ break;
800
+ case 'check':
801
+ s += `check (${expressionToString(c.expr!)})`;
802
+ break;
803
+ case 'foreignKey':
804
+ if (c.foreignKey) {
805
+ const fk = c.foreignKey;
806
+ s += `foreign key (${c.columns!.map(col => quoteIdentifierIfNeeded(col.name)).join(', ')}) references ${quoteIdentifierIfNeeded(fk.table)}`;
807
+ if (fk.columns && fk.columns.length > 0) {
808
+ s += `(${fk.columns.map(quoteIdentifierIfNeeded).join(', ')})`;
809
+ }
810
+ if (fk.onDelete) s += ` on delete ${foreignKeyActionToString(fk.onDelete)}`;
811
+ if (fk.onUpdate) s += ` on update ${foreignKeyActionToString(fk.onUpdate)}`;
812
+ }
813
+ break;
814
+ }
815
+ return s;
816
+ }).filter(s => s.length > 0).join(', ');
817
+ }
818
+
819
+ function foreignKeyActionToString(action: AST.ForeignKeyAction): string {
820
+ switch (action) {
821
+ case 'setNull': return 'set null';
822
+ case 'setDefault': return 'set default';
823
+ case 'cascade': return 'cascade';
824
+ case 'restrict': return 'restrict';
825
+ case 'noAction': return 'no action';
826
+ }
827
+ }
828
+
829
+ export function createTableToString(stmt: AST.CreateTableStmt): string {
830
+ const parts: string[] = ['create'];
831
+ if (stmt.isTemporary) parts.push('temp');
832
+ parts.push('table');
833
+ if (stmt.ifNotExists) parts.push('if not exists');
834
+ // Handle schema.table quoting
835
+ const tableName = quoteIdentifierIfNeeded(stmt.table.name);
836
+ const schemaName = stmt.table.schema ? quoteIdentifierIfNeeded(stmt.table.schema) : undefined;
837
+ parts.push(schemaName ? `${schemaName}.${tableName}` : tableName);
838
+
839
+ const definitions: string[] = [];
840
+ stmt.columns.forEach(col => {
841
+ let colDef = quoteIdentifierIfNeeded(col.name);
842
+ if (col.dataType) colDef += ` ${col.dataType}`; // Keep data type casing as is
843
+ const constraints = columnConstraintsToString(col.constraints);
844
+ if (constraints) colDef += ` ${constraints}`;
845
+ definitions.push(colDef);
846
+ });
847
+
848
+ const tableConstraints = tableConstraintsToString(stmt.constraints);
849
+ if (tableConstraints) definitions.push(tableConstraints);
850
+
851
+ parts.push(`(${definitions.join(', ')})`);
852
+
853
+ if (stmt.moduleName) {
854
+ parts.push('using', stmt.moduleName);
855
+ if (stmt.moduleArgs && Object.keys(stmt.moduleArgs).length > 0) {
856
+ const args = Object.entries(stmt.moduleArgs).map(([key, value]) =>
857
+ `${quoteIdentifierIfNeeded(key)} = ${JSON.stringify(value)}`
858
+ ).join(', ');
859
+ parts.push(`(${args})`);
860
+ }
861
+ }
862
+
863
+ return parts.join(' ');
864
+ }