-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtoSql.ts
More file actions
1815 lines (1621 loc) · 52.1 KB
/
toSql.ts
File metadata and controls
1815 lines (1621 loc) · 52.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// =============================================================================
// AST to SQL Serializer
// =============================================================================
import * as AST from "./ast"
import { keywords } from "../grammar/keywords"
import { constants } from "../grammar/constants"
import { IDENTIFIER_KEYWORD_NAMES } from "./tokens"
function toPascalCase(str: string): string {
if (str.includes("_")) {
return str
.split("_")
.map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase())
.join("")
}
return str.charAt(0).toUpperCase() + str.slice(1)
}
const RESERVED_KEYWORDS = new Set(
[...keywords, ...constants]
.filter((k) => !IDENTIFIER_KEYWORD_NAMES.has(toPascalCase(k)))
.map((k) => k.toLowerCase()),
)
export function toSql(node: AST.Statement | AST.Statement[]): string {
if (Array.isArray(node)) {
return node.map((s) => statementToSql(s)).join(";\n")
}
return statementToSql(node)
}
function statementToSql(stmt: AST.Statement): string {
switch (stmt.type) {
case "select":
return selectToSql(stmt)
case "insert":
return insertToSql(stmt)
case "update":
return updateToSql(stmt)
case "createTable":
return createTableToSql(stmt)
case "createView":
return createViewToSql(stmt)
case "alterTable":
return alterTableToSql(stmt)
case "alterView":
return alterViewToSql(stmt)
case "dropTable":
return dropTableToSql(stmt)
case "dropView":
return dropViewToSql(stmt)
case "truncateTable":
return truncateTableToSql(stmt)
case "renameTable":
return renameTableToSql(stmt)
case "show":
return showToSql(stmt)
case "explain":
return explainToSql(stmt)
case "pivot":
return pivotToSql(stmt)
case "createMaterializedView":
return createMaterializedViewToSql(stmt)
case "alterMaterializedView":
return alterMaterializedViewToSql(stmt)
case "dropMaterializedView":
return dropMaterializedViewToSql(stmt)
case "refreshMaterializedView":
return refreshMaterializedViewToSql(stmt)
// DeclareStatement removed - DECLARE is now a clause within SelectStatement
case "createUser":
return createUserToSql(stmt)
case "createGroup":
return createGroupToSql(stmt)
case "createServiceAccount":
return createServiceAccountToSql(stmt)
case "alterUser":
return alterUserToSql(stmt)
case "alterServiceAccount":
return alterServiceAccountToSql(stmt)
case "dropUser":
return dropUserToSql(stmt)
case "dropGroup":
return dropGroupToSql(stmt)
case "dropServiceAccount":
return dropServiceAccountToSql(stmt)
case "addUser":
return addUserToSql(stmt)
case "removeUser":
return removeUserToSql(stmt)
case "assumeServiceAccount":
return `ASSUME SERVICE ACCOUNT ${qualifiedNameToSql(stmt.account)}`
case "exitServiceAccount":
return stmt.account
? `EXIT SERVICE ACCOUNT ${qualifiedNameToSql(stmt.account)}`
: "EXIT SERVICE ACCOUNT"
case "grant":
return grantToSql(stmt)
case "revoke":
return revokeToSql(stmt)
case "grantAssumeServiceAccount":
return grantAssumeToSql(stmt)
case "revokeAssumeServiceAccount":
return revokeAssumeToSql(stmt)
case "cancelQuery":
return `CANCEL QUERY ${escapeString(stmt.queryId)}`
case "checkpoint":
return `CHECKPOINT ${stmt.action === "create" ? "CREATE" : "RELEASE"}`
case "snapshot":
return `SNAPSHOT ${stmt.action === "prepare" ? "PREPARE" : "COMPLETE"}`
case "vacuumTable":
return vacuumTableToSql(stmt)
case "resumeWal":
return resumeWalToSql(stmt)
case "setType":
return setTypeToSql(stmt)
case "reindexTable":
return reindexTableToSql(stmt)
case "copyCancel":
return `COPY ${escapeString(stmt.id)} CANCEL`
case "copyFrom":
return copyFromToSql(stmt)
case "copyTo":
return copyToToSql(stmt)
case "backup":
return backupToSql(stmt)
case "alterGroup":
return alterGroupToSql(stmt)
case "compileView":
return `COMPILE VIEW ${qualifiedNameToSql(stmt.view)}`
default:
throw new Error(
`Unknown statement type: ${(stmt as { type: string }).type}`,
)
}
}
// =============================================================================
// SELECT
// =============================================================================
function selectToSql(stmt: AST.SelectStatement): string {
const parts: string[] = []
// DECLARE clause
if (stmt.declare) {
parts.push(declareClauseToSql(stmt.declare))
}
// WITH clause (CTEs)
if (stmt.with && stmt.with.length > 0) {
parts.push("WITH")
const ctes = stmt.with.map(
(cte) => `${escapeIdentifier(cte.name)} AS (${selectToSql(cte.query)})`,
)
parts.push(ctes.join(", "))
}
// Implicit SELECT: emit only the FROM table and clauses, no SELECT * FROM
if (stmt.implicit && stmt.from && stmt.from.length > 0) {
parts.push(stmt.from.map(tableRefToSql).join(", "))
} else {
parts.push("SELECT")
if (stmt.distinct) {
parts.push("DISTINCT")
}
// Columns
parts.push(selectListToSql(stmt.columns))
// FROM
if (stmt.from && stmt.from.length > 0) {
parts.push("FROM")
parts.push(stmt.from.map(tableRefToSql).join(", "))
}
}
// WHERE
if (stmt.where) {
parts.push("WHERE")
parts.push(expressionToSql(stmt.where))
}
// SAMPLE BY (QuestDB)
if (stmt.sampleBy) {
parts.push("SAMPLE BY")
parts.push(stmt.sampleBy.duration)
// FROM/TO (must come before FILL and ALIGN TO per Java order)
if (stmt.sampleBy.from) {
parts.push("FROM")
parts.push(expressionToSql(stmt.sampleBy.from))
}
if (stmt.sampleBy.to) {
parts.push("TO")
parts.push(expressionToSql(stmt.sampleBy.to))
}
// FILL
if (stmt.sampleBy.fill && stmt.sampleBy.fill.length > 0) {
parts.push(`FILL(${stmt.sampleBy.fill.join(", ")})`)
}
// ALIGN TO
if (stmt.sampleBy.alignTo) {
parts.push("ALIGN TO")
if (stmt.sampleBy.alignTo.mode === "firstObservation") {
parts.push("FIRST OBSERVATION")
} else {
parts.push("CALENDAR")
if (stmt.sampleBy.alignTo.timeZone) {
parts.push("TIME ZONE")
parts.push(escapeString(stmt.sampleBy.alignTo.timeZone))
}
if (stmt.sampleBy.alignTo.offset) {
parts.push("WITH OFFSET")
parts.push(escapeString(stmt.sampleBy.alignTo.offset))
}
}
}
}
// LATEST ON / LATEST BY (QuestDB)
if (stmt.latestOn) {
if (stmt.latestOn.timestamp) {
parts.push("LATEST ON")
parts.push(qualifiedNameToSql(stmt.latestOn.timestamp))
parts.push("PARTITION BY")
parts.push(stmt.latestOn.partitionBy.map(qualifiedNameToSql).join(", "))
} else {
parts.push("LATEST BY")
parts.push(stmt.latestOn.partitionBy.map(qualifiedNameToSql).join(", "))
}
}
// GROUP BY
if (stmt.groupBy && stmt.groupBy.length > 0) {
parts.push("GROUP BY")
parts.push(stmt.groupBy.map(expressionToSql).join(", "))
}
// PIVOT (inline pivot clause in SELECT)
if (stmt.pivot) {
parts.push(pivotClauseToSql(stmt.pivot))
}
// ORDER BY
if (stmt.orderBy && stmt.orderBy.length > 0) {
parts.push("ORDER BY")
parts.push(stmt.orderBy.map(orderByItemToSql).join(", "))
}
// LIMIT
if (stmt.limit) {
parts.push("LIMIT")
if (stmt.limit.upperBound) {
parts.push(`${expressionToSql(stmt.limit.lowerBound)},`)
parts.push(expressionToSql(stmt.limit.upperBound))
} else {
parts.push(expressionToSql(stmt.limit.lowerBound))
}
}
// Set operations (UNION, EXCEPT, INTERSECT)
if (stmt.setOperations && stmt.setOperations.length > 0) {
for (const op of stmt.setOperations) {
parts.push(op.operator)
if (op.all) {
parts.push("ALL")
}
parts.push(selectToSql(op.select))
}
}
return parts.join(" ")
}
function selectListToSql(items: AST.SelectItem[]): string {
return items
.map((item) => {
if (item.type === "star") {
return "*"
}
if (item.type === "qualifiedStar") {
let sql = `${qualifiedNameToSql(item.qualifier)}.*`
if (item.alias) {
sql += ` AS ${escapeIdentifier(item.alias)}`
}
return sql
}
const selectItem = item
let sql = expressionToSql(selectItem.expression)
if (selectItem.alias) {
sql += ` AS ${escapeIdentifier(selectItem.alias)}`
}
return sql
})
.join(", ")
}
function tableFunctionCallToSql(fn: AST.TableFunctionCall): string {
const args = fn.args.map((a) => expressionToSql(a)).join(", ")
return `${fn.name}(${args})`
}
function tableRefToSql(ref: AST.TableRef): string {
let sql: string
if (!ref.table) {
sql = ""
} else if ("type" in ref.table && ref.table.type === "select") {
sql = `(${selectToSql(ref.table)})`
} else if ("type" in ref.table && ref.table.type === "tableFunctionCall") {
sql = tableFunctionCallToSql(ref.table)
} else if ("type" in ref.table && ref.table.type === "show") {
sql = `(${showToSql(ref.table)})`
} else {
sql = qualifiedNameToSql(ref.table)
}
if (ref.timestampDesignation) {
sql += ` TIMESTAMP(${escapeIdentifier(ref.timestampDesignation)})`
}
if (ref.alias) {
sql += ` AS ${escapeIdentifier(ref.alias)}`
}
if (ref.joins) {
for (const join of ref.joins) {
sql += " " + joinToSql(join)
}
}
return sql
}
function joinToSql(join: AST.JoinClause): string {
const parts: string[] = []
if (join.joinType) {
parts.push(join.joinType.toUpperCase())
}
if (join.outer) {
parts.push("OUTER")
}
parts.push("JOIN")
parts.push(tableRefToSql(join.table))
if (join.on) {
parts.push("ON")
parts.push(expressionToSql(join.on))
}
if (join.tolerance) {
parts.push("TOLERANCE")
parts.push(join.tolerance)
}
if (join.range) {
parts.push("RANGE BETWEEN")
parts.push(windowJoinBoundToSql(join.range.start))
parts.push("AND")
parts.push(windowJoinBoundToSql(join.range.end))
}
if (join.prevailing) {
parts.push(
join.prevailing === "include"
? "INCLUDE PREVAILING"
: "EXCLUDE PREVAILING",
)
}
if (join.horizonRange) {
parts.push("RANGE FROM")
parts.push(join.horizonRange.from)
parts.push("TO")
parts.push(join.horizonRange.to)
parts.push("STEP")
parts.push(join.horizonRange.step)
}
if (join.horizonList) {
parts.push("LIST (" + join.horizonList.join(", ") + ")")
}
if (join.horizonAlias) {
parts.push("AS")
parts.push(escapeIdentifier(join.horizonAlias))
}
return parts.join(" ")
}
function windowJoinBoundToSql(bound: AST.WindowJoinBound): string {
if (bound.boundType === "currentRow") {
if (bound.direction) {
return `CURRENT ROW ${bound.direction.toUpperCase()}`
}
return "CURRENT ROW"
}
return `${bound.duration} ${bound.direction!.toUpperCase()}`
}
function orderByItemToSql(item: AST.OrderByItem): string {
let sql = expressionToSql(item.expression)
if (item.direction) {
sql += ` ${item.direction.toUpperCase()}`
}
return sql
}
// =============================================================================
// INSERT
// =============================================================================
function insertToSql(stmt: AST.InsertStatement): string {
const parts: string[] = []
// WITH clause (CTEs)
if (stmt.with && stmt.with.length > 0) {
parts.push("WITH")
const ctes = stmt.with.map(
(cte) => `${escapeIdentifier(cte.name)} AS (${selectToSql(cte.query)})`,
)
parts.push(ctes.join(", "))
}
if (stmt.atomic) {
parts.push("INSERT ATOMIC INTO")
} else if (stmt.batch) {
let batchClause = `INSERT BATCH ${stmt.batch.size}`
if (stmt.batch.o3MaxLag) {
batchClause += ` o3MaxLag ${stmt.batch.o3MaxLag}`
}
parts.push(batchClause)
parts.push("INTO")
} else {
parts.push("INSERT INTO")
}
parts.push(qualifiedNameToSql(stmt.table))
if (stmt.columns && stmt.columns.length > 0) {
parts.push(`(${stmt.columns.map(escapeIdentifier).join(", ")})`)
}
if (stmt.values) {
parts.push("VALUES")
const valueRows = stmt.values.map(
(row) => `(${row.map(expressionToSql).join(", ")})`,
)
parts.push(valueRows.join(", "))
}
if (stmt.select) {
parts.push(selectToSql(stmt.select))
}
return parts.join(" ")
}
// =============================================================================
// UPDATE
// =============================================================================
function updateToSql(stmt: AST.UpdateStatement): string {
const parts: string[] = []
if (stmt.with && stmt.with.length > 0) {
parts.push("WITH")
const ctes = stmt.with.map(
(cte) => `${escapeIdentifier(cte.name)} AS (${selectToSql(cte.query)})`,
)
parts.push(ctes.join(", "))
}
parts.push("UPDATE")
parts.push(qualifiedNameToSql(stmt.table))
if (stmt.alias) parts.push(escapeIdentifier(stmt.alias))
parts.push("SET")
const setClauses = stmt.set.map(
(s) => `${escapeIdentifier(s.column)} = ${expressionToSql(s.value)}`,
)
parts.push(setClauses.join(", "))
if (stmt.from) {
parts.push("FROM")
parts.push(tableRefToSql(stmt.from))
}
if (stmt.joins) {
for (const join of stmt.joins) {
parts.push(joinToSql(join))
}
}
if (stmt.where) {
parts.push("WHERE")
parts.push(expressionToSql(stmt.where))
}
return parts.join(" ")
}
// =============================================================================
// CREATE TABLE
// =============================================================================
function columnDefToSql(c: AST.ColumnDefinition): string {
let sql = `${escapeIdentifier(c.name)} ${c.dataType}`
if (c.symbolCapacity != null) {
sql += ` CAPACITY ${c.symbolCapacity}`
}
if (c.cache === true) {
sql += " CACHE"
} else if (c.cache === false) {
sql += " NOCACHE"
}
if (c.indexed) {
sql += " INDEX"
if (c.indexCapacity != null) {
sql += ` CAPACITY ${c.indexCapacity}`
}
}
return sql
}
function createTableToSql(stmt: AST.CreateTableStatement): string {
const parts: string[] = ["CREATE"]
if (stmt.atomic) {
parts.push("ATOMIC")
} else if (stmt.batch) {
parts.push(`BATCH ${stmt.batch.size}`)
if (stmt.batch.o3MaxLag) {
parts.push(`o3MaxLag ${stmt.batch.o3MaxLag}`)
}
}
parts.push("TABLE")
if (stmt.ifNotExists) {
parts.push("IF NOT EXISTS")
}
parts.push(qualifiedNameToSql(stmt.table))
if (stmt.like) {
parts.push(`(LIKE ${qualifiedNameToSql(stmt.like)})`)
} else if (stmt.asSelect) {
let asSql = `AS (${selectToSql(stmt.asSelect)})`
if (stmt.casts && stmt.casts.length > 0) {
for (const cast of stmt.casts) {
asSql += `, CAST(${qualifiedNameToSql(cast.column)} AS ${cast.dataType})`
}
}
if (stmt.indexes && stmt.indexes.length > 0) {
for (const idx of stmt.indexes) {
asSql += `, INDEX(${qualifiedNameToSql(idx.column)}`
if (idx.capacity != null) {
asSql += ` CAPACITY ${idx.capacity}`
}
asSql += ")"
}
}
parts.push(asSql)
} else if (stmt.columns) {
let colSql = `(${stmt.columns.map(columnDefToSql).join(", ")})`
if (stmt.indexes && stmt.indexes.length > 0) {
for (const idx of stmt.indexes) {
colSql += `, INDEX(${qualifiedNameToSql(idx.column)}`
if (idx.capacity != null) {
colSql += ` CAPACITY ${idx.capacity}`
}
colSql += ")"
}
}
parts.push(colSql)
}
if (stmt.timestamp) {
parts.push(`TIMESTAMP(${escapeIdentifier(stmt.timestamp)})`)
}
if (stmt.partitionBy) {
parts.push(`PARTITION BY ${stmt.partitionBy}`)
}
if (stmt.ttl) {
parts.push(`TTL ${stmt.ttl.value} ${stmt.ttl.unit}`)
}
if (stmt.bypassWal) {
parts.push("BYPASS WAL")
} else if (stmt.wal) {
parts.push("WAL")
}
if (stmt.withParams && stmt.withParams.length > 0) {
const paramParts = stmt.withParams.map((p) => {
if (p.value) {
return `${p.name} = ${expressionToSql(p.value)}`
}
return p.name
})
parts.push(`WITH ${paramParts.join(", ")}`)
}
if (stmt.volume) {
parts.push(`IN VOLUME ${escapeString(stmt.volume)}`)
}
if (stmt.dedupKeys && stmt.dedupKeys.length > 0) {
parts.push(
`DEDUP UPSERT KEYS(${stmt.dedupKeys.map(escapeIdentifier).join(", ")})`,
)
}
if (stmt.ownedBy) {
parts.push(`OWNED BY ${escapeIdentifier(stmt.ownedBy)}`)
}
return parts.join(" ")
}
// =============================================================================
// CREATE/ALTER/DROP VIEW
// =============================================================================
function createViewToSql(stmt: AST.CreateViewStatement): string {
const parts: string[] = ["CREATE"]
if (stmt.orReplace) {
parts.push("OR REPLACE")
}
parts.push("VIEW")
if (stmt.ifNotExists) {
parts.push("IF NOT EXISTS")
}
parts.push(qualifiedNameToSql(stmt.view))
if (stmt.asParens) {
parts.push(`AS (${selectToSql(stmt.query)})`)
} else {
parts.push(`AS ${selectToSql(stmt.query)}`)
}
if (stmt.ownedBy) parts.push(`OWNED BY ${escapeIdentifier(stmt.ownedBy)}`)
return parts.join(" ")
}
function alterViewToSql(stmt: AST.AlterViewStatement): string {
return `ALTER VIEW ${qualifiedNameToSql(stmt.view)} AS (${selectToSql(stmt.query)})`
}
function dropViewToSql(stmt: AST.DropViewStatement): string {
const parts: string[] = ["DROP VIEW"]
if (stmt.ifExists) {
parts.push("IF EXISTS")
}
parts.push(qualifiedNameToSql(stmt.view))
return parts.join(" ")
}
// =============================================================================
// ALTER TABLE
// =============================================================================
function alterTableToSql(stmt: AST.AlterTableStatement): string {
const parts: string[] = ["ALTER TABLE", qualifiedNameToSql(stmt.table)]
const action = stmt.action
switch (action.actionType) {
case "addColumn": {
parts.push("ADD COLUMN")
if (action.ifNotExists) {
parts.push("IF NOT EXISTS")
}
parts.push(action.columns.map(columnDefToSql).join(", "))
break
}
case "dropColumn":
parts.push("DROP COLUMN")
parts.push(action.columns.map(escapeIdentifier).join(", "))
break
case "renameColumn":
parts.push("RENAME COLUMN")
parts.push(escapeIdentifier(action.oldName))
parts.push("TO")
parts.push(escapeIdentifier(action.newName))
break
case "alterColumn":
parts.push("ALTER COLUMN")
parts.push(escapeIdentifier(action.column))
if (action.alterType === "type" && action.newType) {
parts.push("TYPE")
parts.push(action.newType)
if (action.capacity !== undefined) {
parts.push("CAPACITY")
parts.push(String(action.capacity))
}
if (action.cache === true) {
parts.push("CACHE")
} else if (action.cache === false) {
parts.push("NOCACHE")
}
} else if (action.alterType === "addIndex") {
parts.push("ADD INDEX")
} else if (action.alterType === "dropIndex") {
parts.push("DROP INDEX")
} else if (
action.alterType === "symbolCapacity" &&
action.capacity !== undefined
) {
parts.push("SYMBOL CAPACITY")
parts.push(String(action.capacity))
} else if (action.alterType === "cache") {
parts.push("CACHE")
} else if (action.alterType === "nocache") {
parts.push("NOCACHE")
}
break
case "dropPartition":
parts.push("DROP PARTITION")
if (action.partitions && action.partitions.length > 0) {
parts.push("LIST")
parts.push(
action.partitions.map((p: string) => escapeString(p)).join(", "),
)
} else if (action.where) {
parts.push("WHERE")
parts.push(expressionToSql(action.where))
}
break
case "attachPartition":
parts.push("ATTACH PARTITION")
if (action.partitions && action.partitions.length > 0) {
parts.push("LIST")
parts.push(
action.partitions.map((p: string) => escapeString(p)).join(", "),
)
}
break
case "detachPartition":
parts.push("DETACH PARTITION")
if (action.partitions && action.partitions.length > 0) {
parts.push("LIST")
parts.push(action.partitions.map((p) => escapeString(p)).join(", "))
} else if (action.where) {
parts.push("WHERE")
parts.push(expressionToSql(action.where))
}
break
case "squashPartitions":
parts.push("SQUASH PARTITIONS")
break
case "setParam":
parts.push("SET PARAM")
parts.push(
action.params
.map((param) =>
param.value
? `${param.name} = ${expressionToSql(param.value)}`
: param.name,
)
.join(", "),
)
break
case "setTtl":
parts.push("SET TTL")
parts.push(`${action.ttl.value} ${action.ttl.unit}`)
break
case "dedupDisable":
parts.push("DEDUP DISABLE")
break
case "dedupEnable":
parts.push("DEDUP ENABLE UPSERT KEYS")
parts.push(`(${action.keys.map(escapeIdentifier).join(", ")})`)
break
case "setTypeWal":
parts.push("SET TYPE")
if (action.bypass) parts.push("BYPASS")
parts.push("WAL")
break
case "suspendWal": {
parts.push("SUSPEND WAL")
if (action.code != null || action.message) {
const withParts: string[] = []
if (action.code != null) {
withParts.push(
typeof action.code === "number"
? String(action.code)
: escapeString(action.code),
)
}
if (action.message) withParts.push(escapeString(action.message))
parts.push(`WITH ${withParts.join(", ")}`)
}
break
}
case "resumeWal": {
parts.push("RESUME WAL")
if (action.fromTxn !== undefined) {
parts.push(`FROM TXN ${action.fromTxn}`)
} else if (action.fromTransaction !== undefined) {
parts.push(`FROM TRANSACTION ${action.fromTransaction}`)
}
break
}
case "convertPartition": {
parts.push("CONVERT PARTITION")
if (action.partitions && action.partitions.length > 0) {
parts.push("LIST")
parts.push(
action.partitions.map((p: string) => escapeString(p)).join(", "),
)
}
parts.push("TO")
parts.push(action.target)
if (action.where) {
parts.push("WHERE")
parts.push(expressionToSql(action.where))
}
break
}
}
return parts.join(" ")
}
// =============================================================================
// DROP TABLE
// =============================================================================
function dropTableToSql(stmt: AST.DropTableStatement): string {
if (stmt.allTables) {
return "DROP ALL TABLES"
}
const parts: string[] = ["DROP TABLE"]
if (stmt.ifExists) {
parts.push("IF EXISTS")
}
if (stmt.table) {
parts.push(qualifiedNameToSql(stmt.table))
}
return parts.join(" ")
}
// =============================================================================
// TRUNCATE TABLE
// =============================================================================
function truncateTableToSql(stmt: AST.TruncateTableStatement): string {
const parts: string[] = ["TRUNCATE TABLE"]
if (stmt.ifExists) {
parts.push("IF EXISTS")
}
if (stmt.only) {
parts.push("ONLY")
}
parts.push(stmt.tables.map(qualifiedNameToSql).join(", "))
if (stmt.keepSymbolMaps) {
parts.push("KEEP SYMBOL MAPS")
}
return parts.join(" ")
}
// =============================================================================
// RENAME TABLE
// =============================================================================
function renameTableToSql(stmt: AST.RenameTableStatement): string {
return `RENAME TABLE ${qualifiedNameToSql(stmt.from)} TO ${qualifiedNameToSql(stmt.to)}`
}
// =============================================================================
// SHOW
// =============================================================================
function showToSql(stmt: AST.ShowStatement): string {
switch (stmt.showType) {
case "tables":
return "SHOW TABLES"
case "columns":
return `SHOW COLUMNS FROM ${qualifiedNameToSql(stmt.table!)}`
case "partitions":
return `SHOW PARTITIONS FROM ${qualifiedNameToSql(stmt.table!)}`
case "createTable":
return `SHOW CREATE TABLE ${qualifiedNameToSql(stmt.table!)}`
case "createView":
return `SHOW CREATE VIEW ${qualifiedNameToSql(stmt.table!)}`
case "createMaterializedView":
return `SHOW CREATE MATERIALIZED VIEW ${qualifiedNameToSql(stmt.table!)}`
case "serverVersion":
return "SHOW SERVER_VERSION"
case "parameters":
return "SHOW PARAMETERS"
case "user":
return stmt.name
? `SHOW USER ${qualifiedNameToSql(stmt.name)}`
: "SHOW USER"
case "users":
return "SHOW USERS"
case "groups":
return stmt.name
? `SHOW GROUPS ${qualifiedNameToSql(stmt.name)}`
: "SHOW GROUPS"
case "serviceAccount":
return stmt.name
? `SHOW SERVICE ACCOUNT ${qualifiedNameToSql(stmt.name)}`
: "SHOW SERVICE ACCOUNT"
case "serviceAccounts":
return stmt.name
? `SHOW SERVICE ACCOUNTS ${qualifiedNameToSql(stmt.name)}`
: "SHOW SERVICE ACCOUNTS"
case "permissions":
return stmt.name
? `SHOW PERMISSIONS ${qualifiedNameToSql(stmt.name)}`
: "SHOW PERMISSIONS"
case "transactionIsolationLevel":
return "SHOW TRANSACTION ISOLATION LEVEL"
case "maxIdentifierLength":
return "SHOW max_identifier_length"
case "standardConformingStrings":
return "SHOW standard_conforming_strings"
case "searchPath":
return "SHOW search_path"
case "dateStyle":
return "SHOW datestyle"
case "timeZone":
return "SHOW TIME ZONE"
case "serverVersionNum":
return "SHOW server_version_num"
case "defaultTransactionReadOnly":
return "SHOW default_transaction_read_only"
default:
throw new Error(
`Unknown show type: ${(stmt as { showType: string }).showType}`,
)
}
}
// =============================================================================
// EXPLAIN
// =============================================================================
function explainToSql(stmt: AST.ExplainStatement): string {
if (stmt.format) {
return `EXPLAIN (FORMAT ${stmt.format}) ${statementToSql(stmt.statement)}`
}
return `EXPLAIN ${statementToSql(stmt.statement)}`
}
// =============================================================================
// MATERIALIZED VIEW
// =============================================================================
function materializedViewRefreshToSql(
refresh: AST.MaterializedViewRefresh,
): string {
const parts: string[] = ["REFRESH"]
if (refresh.mode === "immediate") parts.push("IMMEDIATE")
else if (refresh.mode === "manual") parts.push("MANUAL")
if (refresh.every) parts.push(`EVERY ${refresh.every}`)
if (refresh.deferred) parts.push("DEFERRED")
if (refresh.start) parts.push(`START ${escapeString(refresh.start)}`)
if (refresh.timeZone)
parts.push(`TIME ZONE ${escapeString(refresh.timeZone)}`)
return parts.join(" ")
}
function materializedViewPeriodToSql(
period: AST.MaterializedViewPeriod,
): string {
const inner: string[] = []
if (period.sampleByInterval) {
inner.push("SAMPLE BY INTERVAL")
} else {
if (period.length) inner.push(`LENGTH ${period.length}`)
if (period.timeZone)
inner.push(`TIME ZONE ${escapeString(period.timeZone)}`)
if (period.delay) inner.push(`DELAY ${period.delay}`)
}
return `PERIOD (${inner.join(" ")})`
}
function createMaterializedViewToSql(
stmt: AST.CreateMaterializedViewStatement,
): string {
const parts: string[] = ["CREATE MATERIALIZED VIEW"]
if (stmt.ifNotExists) parts.push("IF NOT EXISTS")
parts.push(qualifiedNameToSql(stmt.view))
if (stmt.baseTable)