-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathprinter.ts
More file actions
3058 lines (2711 loc) · 103 KB
/
printer.ts
File metadata and controls
3058 lines (2711 loc) · 103 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
// TypeScript port of posthog/hogql/printer.py
// ClickHouse SQL printer with tenant isolation and schema validation
import {
And,
Alias,
ArithmeticOperation,
ArithmeticOperationOp,
Array as ASTArray,
ArrayAccess,
AST,
BetweenExpr,
Call,
CompareOperation,
CompareOperationOp,
Constant,
CTE,
Dict,
Expression,
Field,
JoinConstraint,
JoinExpr,
Lambda,
LimitByExpr,
Not,
Or,
OrderExpr,
Placeholder,
RatioExpr,
SampleExpr,
SelectQuery,
SelectSetQuery,
Tuple,
TupleAccess,
WindowExpr,
WindowFrameExpr,
WindowFunction,
} from "./ast";
import { escapeClickHouseIdentifier, escapeTSQLIdentifier, escapeClickHouseString } from "./escape";
import { ImpossibleASTError, NotImplementedError, QueryError } from "./errors";
import {
TSQL_CLICKHOUSE_FUNCTIONS,
TSQL_AGGREGATIONS,
TSQL_COMPARISON_MAPPING,
findTSQLAggregation,
findTSQLFunction,
validateFunctionArgs,
} from "./functions";
import { PrinterContext, WhereClauseCondition } from "./printer_context";
import { calculateTimeBucketInterval } from "./time_buckets";
import {
findTable,
validateTable,
TableSchema,
ColumnSchema,
getInternalValue,
isVirtualColumn,
OutputColumnMetadata,
ClickHouseType,
hasFieldMapping,
getInternalValueFromMappingCaseInsensitive,
} from "./schema";
/**
* Result of printing an AST to ClickHouse SQL
*/
export interface PrintResult {
/** The generated ClickHouse SQL query */
sql: string;
/** Parameter values for parameterized query execution */
params: Record<string, unknown>;
/** Metadata for each column in the SELECT clause, in order */
columns: OutputColumnMetadata[];
/**
* Columns that were hidden when SELECT * was used.
* Only populated when SELECT * is transformed to core columns only.
*/
hiddenColumns?: string[];
}
/**
* Response from visiting a JoinExpr node
*/
interface JoinExprResponse {
/** The printed SQL for the JOIN */
printedSql: string;
/** Additional WHERE clause to add (e.g., tenant isolation guards) */
where: Expression | null;
}
/**
* ClickHouse SQL Printer
*
* Converts a TSQL AST to a parameterized ClickHouse SQL query with:
* - Automatic tenant isolation (organization_id, project_id, environment_id)
* - Schema-based table/column validation
* - SQL injection protection via parameterized queries
* - Table and column name mapping (user-friendly → internal ClickHouse names)
*/
export class ClickHousePrinter {
/** Stack of AST nodes being visited (for context) */
private stack: AST[] = [];
/** Indent level for pretty printing */
private indentLevel = -1;
/** Tab size for pretty printing */
private tabSize = 4;
/** Whether to pretty print output */
private pretty: boolean;
/**
* Map of table aliases to their schemas (for column name resolution)
* Key is the alias/name used in the query, value is the TableSchema
*/
private tableContexts: Map<string, TableSchema> = new Map();
/** Column metadata collected during SELECT processing */
private outputColumns: OutputColumnMetadata[] = [];
/** Whether we're currently processing GROUP BY expressions */
private inGroupByContext = false;
/** Whether the current query has a GROUP BY clause (used for JSON subfield type hints) */
private queryHasGroupBy = false;
/** Columns hidden when SELECT * is expanded to core columns only */
private hiddenColumns: string[] = [];
/**
* Map of column aliases defined in the current SELECT clause.
* Key is the lowercase alias (for case-insensitive lookup),
* value is the canonical form (as it appears in the generated SQL).
* Used to allow ORDER BY/HAVING to reference aliased columns.
*/
private selectAliases: Map<string, string> = new Map();
/**
* Set of internal ClickHouse column names that are allowed (e.g., tenant columns).
* These are populated from tableSchema.tenantColumns when processing joins.
*/
private allowedInternalColumns: Set<string> = new Set();
/**
* Set of internal-only column names that are NOT user-queryable.
* These are tenant columns and required filter columns that are not exposed in tableSchema.columns.
* Used to block user queries from accessing internal columns in SELECT, ORDER BY, GROUP BY, HAVING.
*/
private internalOnlyColumns: Set<string> = new Set();
/**
* Whether we're currently processing user projection clauses (SELECT, ORDER BY, GROUP BY, HAVING).
* When true, internal-only columns will be rejected.
*/
private inProjectionContext = false;
constructor(
private context: PrinterContext,
options: { pretty?: boolean } = {}
) {
this.pretty = options.pretty ?? false;
}
/**
* Print an AST node to ClickHouse SQL
*/
print(node: SelectQuery | SelectSetQuery): PrintResult {
this.outputColumns = [];
this.hiddenColumns = [];
const sql = this.visit(node);
const result: PrintResult = {
sql,
params: this.context.getParams(),
columns: this.outputColumns,
};
if (this.hiddenColumns.length > 0) {
result.hiddenColumns = this.hiddenColumns;
}
return result;
}
/**
* Get current indentation string
*/
private indent(extra = 0): string {
return " ".repeat(this.tabSize * (this.indentLevel + extra));
}
/**
* Visit an AST node and return its SQL representation
*/
private visit(node: AST | null | undefined): string {
if (node === null || node === undefined) {
return "";
}
this.stack.push(node);
this.indentLevel++;
let response: string;
// Type-based dispatch
const nodeType = (node as Expression).expression_type;
switch (nodeType) {
case "select_set_query":
response = this.visitSelectSetQuery(node as SelectSetQuery);
break;
case "select_query":
response = this.visitSelectQuery(node as SelectQuery);
break;
case "cte":
response = this.visitCTE(node as CTE);
break;
case "alias":
response = this.visitAlias(node as Alias);
break;
case "arithmetic_operation":
response = this.visitArithmeticOperation(node as ArithmeticOperation);
break;
case "and":
response = this.visitAnd(node as And);
break;
case "or":
response = this.visitOr(node as Or);
break;
case "compare_operation":
response = this.visitCompareOperation(node as CompareOperation);
break;
case "not":
response = this.visitNot(node as Not);
break;
case "between_expr":
response = this.visitBetweenExpr(node as BetweenExpr);
break;
case "order_expr":
response = this.visitOrderExpr(node as OrderExpr);
break;
case "array_access":
response = this.visitArrayAccess(node as ArrayAccess);
break;
case "array":
response = this.visitArray(node as ASTArray);
break;
case "dict":
response = this.visitDict(node as Dict);
break;
case "tuple_access":
response = this.visitTupleAccess(node as TupleAccess);
break;
case "tuple":
response = this.visitTuple(node as Tuple);
break;
case "lambda":
response = this.visitLambda(node as Lambda);
break;
case "constant":
response = this.visitConstant(node as Constant);
break;
case "field":
response = this.visitField(node as Field);
break;
case "placeholder":
response = this.visitPlaceholder(node as Placeholder);
break;
case "call":
response = this.visitCall(node as Call);
break;
case "join_expr":
// JoinExpr is handled specially since it returns more than just SQL
throw new ImpossibleASTError("JoinExpr should be handled via visitJoinExpr");
case "join_constraint":
response = this.visitJoinConstraint(node as JoinConstraint);
break;
case "window_frame_expr":
response = this.visitWindowFrameExpr(node as WindowFrameExpr);
break;
case "window_expr":
response = this.visitWindowExpr(node as WindowExpr);
break;
case "window_function":
response = this.visitWindowFunction(node as WindowFunction);
break;
case "limit_by_expr":
response = this.visitLimitByExpr(node as LimitByExpr);
break;
case "ratio_expr":
response = this.visitRatioExpr(node as RatioExpr);
break;
case "sample_expr":
response = this.visitSampleExpr(node as SampleExpr);
break;
default:
throw new NotImplementedError(
`Unknown expression type: ${nodeType}. Node: ${JSON.stringify(node, null, 2).slice(
0,
200
)}`
);
}
this.indentLevel--;
this.stack.pop();
return response;
}
// ============================================================
// SELECT Query Visitors
// ============================================================
private visitSelectSetQuery(node: SelectSetQuery): string {
this.indentLevel--;
let ret = this.visit(node.initial_select_query);
if (this.pretty) {
ret = ret.trim();
}
for (const expr of node.subsequent_select_queries) {
let query = this.visit(expr.select_query);
if (this.pretty) {
query = query.trim();
}
if (expr.set_operator !== undefined) {
if (this.pretty) {
ret += `\n${this.indent(1)}${expr.set_operator}\n${this.indent(1)}`;
} else {
ret += ` ${expr.set_operator} `;
}
}
ret += query;
}
this.indentLevel++;
// Wrap in parentheses if not top level
if (this.stack.length > 1) {
return `(${ret.trim()})`;
}
return ret;
}
private visitSelectQuery(node: SelectQuery): string {
// Determine if this is a top-level query
const partOfSelectUnion =
this.stack.length >= 2 && this.isSelectSetQuery(this.stack[this.stack.length - 2]);
const isTopLevelQuery =
this.stack.length <= 1 || (this.stack.length === 2 && partOfSelectUnion);
// Save and clear table contexts
// Top-level queries clear contexts; subqueries save parent context and create fresh context
const savedTableContexts = new Map(this.tableContexts);
const savedInternalColumns = new Set(this.allowedInternalColumns);
const savedInternalOnlyColumns = new Set(this.internalOnlyColumns);
if (isTopLevelQuery) {
this.tableContexts.clear();
this.allowedInternalColumns.clear();
this.internalOnlyColumns.clear();
} else {
// Subqueries get fresh contexts - they don't inherit parent tables
// (the parent will restore its context after the subquery is processed)
this.tableContexts = new Map();
this.allowedInternalColumns = new Set();
this.internalOnlyColumns = new Set();
}
// Build WHERE clause starting with any existing where
let where: Expression | undefined = node.where;
// Process CTEs
const cteStrings: string[] = [];
if (node.ctes) {
for (const [name, cte] of Object.entries(node.ctes)) {
cteStrings.push(`${this.printIdentifier(name)} AS (${this.visit(cte.expr)})`);
}
}
// Process joins and collect tenant guards
const joinedTables: string[] = [];
let nextJoin: JoinExpr | undefined = node.select_from;
while (nextJoin) {
const visitedJoin = this.visitJoinExpr(nextJoin);
joinedTables.push(visitedJoin.printedSql);
// Add tenant guard to WHERE clause
const extraWhere = visitedJoin.where;
if (extraWhere !== null) {
if (where === undefined) {
where = extraWhere;
} else if ((where as And).expression_type === "and") {
where = { expression_type: "and", exprs: [extraWhere, ...(where as And).exprs] } as And;
} else {
where = { expression_type: "and", exprs: [extraWhere, where] } as And;
}
}
nextJoin = nextJoin.next_join;
}
// Extract SELECT column aliases BEFORE visiting columns
// This allows ORDER BY/HAVING to reference aliased columns
const savedAliases = this.selectAliases;
this.selectAliases = new Map();
if (node.select) {
for (const col of node.select) {
this.extractSelectAlias(col);
}
}
// Track if query has GROUP BY for JSON subfield type hint decisions
// (ClickHouse requires .:String for Dynamic types in GROUP BY, and SELECT must match)
const savedQueryHasGroupBy = this.queryHasGroupBy;
this.queryHasGroupBy = !!node.group_by;
// Process SELECT columns and collect metadata
// Using flatMap because asterisk expansion can return multiple columns
// Set inProjectionContext to block internal-only columns in user projections
let columns: string[];
if (node.select && node.select.length > 0) {
// Only collect metadata for top-level queries (not subqueries)
if (isTopLevelQuery) {
this.outputColumns = [];
}
this.inProjectionContext = true;
columns = node.select.flatMap((col) =>
this.visitSelectColumnWithMetadata(col, isTopLevelQuery)
);
this.inProjectionContext = false;
} else {
columns = ["1"];
}
// Process WINDOW definitions
let windowClause: string | null = null;
if (node.window_exprs && Object.keys(node.window_exprs).length > 0) {
const windowDefs = Object.entries(node.window_exprs).map(
([name, expr]) => `${this.printIdentifier(name)} AS (${this.visit(expr)})`
);
windowClause = windowDefs.join(", ");
}
// Process other clauses
const prewhere = node.prewhere ? this.visit(node.prewhere) : null;
const whereStr = where ? this.visit(where) : null;
// Process GROUP BY with context flags:
// - inGroupByContext: use raw columns for whereTransform columns
// - inProjectionContext: block internal-only columns
let groupBy: string[] | null = null;
if (node.group_by) {
this.inGroupByContext = true;
this.inProjectionContext = true;
groupBy = node.group_by.map((col) => this.visit(col));
this.inProjectionContext = false;
this.inGroupByContext = false;
}
// Process HAVING with inProjectionContext to block internal-only columns
let having: string | null = null;
if (node.having) {
this.inProjectionContext = true;
having = this.visit(node.having);
this.inProjectionContext = false;
}
// Process ORDER BY with inProjectionContext to block internal-only columns
let orderBy: string[] | null = null;
if (node.order_by) {
this.inProjectionContext = true;
orderBy = node.order_by.map((col) => this.visit(col));
this.inProjectionContext = false;
}
// Process ARRAY JOIN
let arrayJoin = "";
if (node.array_join_op) {
if (!["ARRAY JOIN", "LEFT ARRAY JOIN", "INNER ARRAY JOIN"].includes(node.array_join_op)) {
throw new ImpossibleASTError(`Invalid ARRAY JOIN operation: ${node.array_join_op}`);
}
arrayJoin = node.array_join_op;
if (!node.array_join_list || node.array_join_list.length === 0) {
throw new ImpossibleASTError("Invalid ARRAY JOIN without an array");
}
arrayJoin += ` ${node.array_join_list.map((expr) => this.visit(expr)).join(", ")}`;
}
// Format spacing
const space = this.pretty ? `\n${this.indent(1)}` : " ";
const comma = this.pretty ? `,\n${this.indent(1)}` : ", ";
// Build SQL clauses
const clauses: (string | null)[] = [
`SELECT${space}${node.distinct ? "DISTINCT " : ""}${columns.join(comma)}`,
joinedTables.length > 0 ? `FROM${space}${joinedTables.join(space)}` : null,
arrayJoin || null,
prewhere ? `PREWHERE${space}${prewhere}` : null,
whereStr ? `WHERE${space}${whereStr}` : null,
groupBy && groupBy.length > 0 ? `GROUP BY${space}${groupBy.join(comma)}` : null,
having ? `HAVING${space}${having}` : null,
windowClause ? `WINDOW${space}${windowClause}` : null,
orderBy && orderBy.length > 0 ? `ORDER BY${space}${orderBy.join(comma)}` : null,
];
// Process LIMIT
let limit = node.limit;
if (isTopLevelQuery && this.context.maxRows) {
const maxLimit = this.context.maxRows;
if (limit !== undefined) {
// Cap the limit to maxRows
if ((limit as Constant).expression_type === "constant") {
const constLimit = limit as Constant;
if (typeof constLimit.value === "number") {
constLimit.value = Math.min(constLimit.value, maxLimit);
}
}
} else {
// Add default limit
limit = { expression_type: "constant", value: maxLimit } as Constant;
}
}
// Add LIMIT BY
if (node.limit_by) {
const limitByExprs = node.limit_by.exprs.map((e) => this.visit(e)).join(", ");
const offsetPart = node.limit_by.offset_value
? ` OFFSET ${this.visit(node.limit_by.offset_value)}`
: "";
clauses.push(`LIMIT ${this.visit(node.limit_by.n)}${offsetPart} BY ${limitByExprs}`);
}
// Add LIMIT/OFFSET
if (limit !== undefined) {
clauses.push(`LIMIT ${this.visit(limit)}`);
if (node.limit_with_ties) {
clauses.push("WITH TIES");
}
if (node.offset !== undefined) {
clauses.push(`OFFSET ${this.visit(node.offset)}`);
}
}
// Add CTEs
let response: string;
if (this.pretty) {
response = clauses
.filter((c) => c !== null)
.map((c) => `${this.indent()}${c}`)
.join("\n");
} else {
response = clauses.filter((c) => c !== null).join(" ");
}
// Add WITH clause for CTEs
if (cteStrings.length > 0) {
const ctePrefix = `WITH ${cteStrings.join(", ")}`;
response = `${ctePrefix} ${response}`;
}
// Wrap subqueries in parentheses
if (!partOfSelectUnion && !isTopLevelQuery) {
response = this.pretty ? `(${response.trim()})` : `(${response})`;
}
// Restore saved contexts (for nested queries)
this.selectAliases = savedAliases;
this.queryHasGroupBy = savedQueryHasGroupBy;
this.tableContexts = savedTableContexts;
this.allowedInternalColumns = savedInternalColumns;
this.internalOnlyColumns = savedInternalOnlyColumns;
return response;
}
/**
* Extract column aliases from a SELECT expression.
* Handles explicit aliases (AS name) and implicit names from aggregations/functions.
*
* NOTE: We intentionally do NOT add field names as aliases here.
* Field names (e.g., SELECT status) are columns from the table, not aliases.
* Only explicit aliases (SELECT x AS name) and implicit function names
* (SELECT COUNT() → 'count') should be added.
*/
private extractSelectAlias(expr: Expression): void {
// Handle explicit Alias: SELECT ... AS name
// Key is lowercase for case-insensitive lookup, value is the original casing
// so that ORDER BY/GROUP BY output matches the alias in the generated SQL.
if ((expr as Alias).expression_type === "alias") {
const alias = (expr as Alias).alias;
this.selectAliases.set(alias.toLowerCase(), alias);
return;
}
// Handle implicit names from function calls (e.g., COUNT() → 'count')
// ClickHouse generates implicit aliases as lowercase
if ((expr as Call).expression_type === "call") {
const call = expr as Call;
const canonicalName = call.name.toLowerCase();
this.selectAliases.set(canonicalName, canonicalName);
return;
}
// Handle implicit names from arithmetic operations (e.g., a + b → 'plus')
// ClickHouse generates these as lowercase
if ((expr as ArithmeticOperation).expression_type === "arithmetic_operation") {
const op = expr as ArithmeticOperation;
const opNames: Record<ArithmeticOperationOp, string> = {
[ArithmeticOperationOp.Add]: "plus",
[ArithmeticOperationOp.Sub]: "minus",
[ArithmeticOperationOp.Mult]: "multiply",
[ArithmeticOperationOp.Div]: "divide",
[ArithmeticOperationOp.Mod]: "modulo",
};
const canonicalName = opNames[op.op];
this.selectAliases.set(canonicalName, canonicalName);
return;
}
// Field references (e.g., SELECT status) are NOT aliases - they're columns
// that will be validated against the table schema. Don't add them here.
}
/**
* Visit a SELECT column expression with metadata collection
*
* For bare Field expressions that reference virtual columns, we need to add
* an AS alias to preserve the column name in the result set.
*
* Examples:
* - `SELECT execution_duration` → `SELECT (expr) AS execution_duration`
* - `SELECT execution_duration AS dur` → `SELECT (expr) AS dur` (Alias handles it)
* - `SELECT run_id` → `SELECT run_id` (not a virtual column)
* - `SELECT *` → Expands to all selectable columns from the table(s)
*
* @param col - The column expression
* @param collectMetadata - Whether to collect column metadata (only for top-level queries)
* @returns Array of SQL column strings (usually one, but multiple for asterisk expansion)
*/
private visitSelectColumnWithMetadata(col: Expression, collectMetadata: boolean): string[] {
// Check for asterisk expansion first
if ((col as Field).expression_type === "field") {
const field = col as Field;
const asteriskExpansion = this.expandAsterisk(field.chain, collectMetadata);
if (asteriskExpansion !== null) {
return asteriskExpansion;
}
}
// Extract output name and source column before visiting
const { outputName, sourceColumn, inferredType } = this.analyzeSelectColumn(col);
// effectiveOutputName may be overridden for JSON subfields
let effectiveOutputName = outputName;
// Check if this is a bare Field (not wrapped in Alias)
let sqlResult: string;
if ((col as Field).expression_type === "field") {
const field = col as Field;
// Check if this is a bare JSON field that should use a text column
const textColumn = this.getTextColumnForField(field.chain);
if (textColumn !== null && outputName) {
// Use the text column instead of the JSON column, with alias to preserve name
sqlResult = `${this.printIdentifier(textColumn)} AS ${this.printIdentifier(outputName)}`;
} else {
const virtualColumnName = this.getVirtualColumnNameForField(field.chain);
if (virtualColumnName !== null) {
// Visit the field (which will return the expression)
const visited = this.visit(col);
// Add the alias to preserve the column name
sqlResult = `${visited} AS ${this.printIdentifier(virtualColumnName)}`;
} else {
// Visit the field to get the ClickHouse SQL
const visited = this.visit(col);
// Check if this is a JSON subfield access (will have .:String type hint)
// If so, add an alias to preserve the nice column name (dots → underscores)
const isJsonSubfield = this.isJsonSubfieldAccess(field.chain);
if (isJsonSubfield) {
// Build the alias using underscores, excluding any dataPrefix
// e.g., output.message -> "output_message" (not "output_data_message")
const dataPrefix = this.getDataPrefixForField(field.chain);
const aliasName = this.buildAliasWithoutDataPrefix(field.chain, dataPrefix);
sqlResult = `${visited} AS ${this.printIdentifier(aliasName)}`;
// Override output name for metadata
effectiveOutputName = aliasName;
}
// Check if the column has a different clickhouseName - if so, add an alias
// to ensure results come back with the user-facing name
else if (
outputName &&
sourceColumn?.clickhouseName &&
sourceColumn.clickhouseName !== outputName
) {
sqlResult = `${visited} AS ${this.printIdentifier(outputName)}`;
} else {
sqlResult = visited;
}
}
}
} else if (
// Handle expressions that need implicit aliases (Call, ArithmeticOperation, Constant)
// These expressions get implicit names and need AS clauses so results match metadata
(col as Alias).expression_type !== "alias" &&
((col as Call).expression_type === "call" ||
(col as ArithmeticOperation).expression_type === "arithmetic_operation" ||
(col as Constant).expression_type === "constant")
) {
const visited = this.visit(col);
// Add explicit AS clause with the implicit name so ClickHouse results match our metadata
if (outputName) {
sqlResult = `${visited} AS ${this.printIdentifier(outputName)}`;
} else {
sqlResult = visited;
}
} else if ((col as Alias).expression_type === "alias") {
// Handle Alias expressions - check if inner expression is a bare JSON field with textColumn
const alias = col as Alias;
if ((alias.expr as Field).expression_type === "field") {
const innerField = alias.expr as Field;
const textColumn = this.getTextColumnForField(innerField.chain);
if (textColumn !== null) {
// Use the text column with the user's explicit alias
sqlResult = `${this.printIdentifier(textColumn)} AS ${this.printIdentifier(alias.alias)}`;
} else {
sqlResult = this.visit(col);
}
} else {
sqlResult = this.visit(col);
}
} else {
// For other types, visit normally
sqlResult = this.visit(col);
}
// Collect metadata for top-level queries
if (collectMetadata && effectiveOutputName) {
const metadata: OutputColumnMetadata = {
name: effectiveOutputName,
type: sourceColumn?.type ?? inferredType ?? "String",
};
// Only add customRenderType if specified in schema
if (sourceColumn?.customRenderType) {
metadata.customRenderType = sourceColumn.customRenderType;
}
// Only add description if specified in schema (columns and virtual columns)
if (sourceColumn?.description) {
metadata.description = sourceColumn.description;
}
this.outputColumns.push(metadata);
}
return [sqlResult];
}
/**
* Expand an asterisk field to all selectable columns from the table(s)
*
* @param chain - The field chain (["*"] for SELECT *, [tableName, "*"] for table.*)
* @param collectMetadata - Whether to collect column metadata
* @returns Array of SQL column strings, or null if not an asterisk
*/
private expandAsterisk(chain: Array<string | number>, collectMetadata: boolean): string[] | null {
// Check for SELECT * (chain: ["*"])
if (chain.length === 1 && chain[0] === "*") {
return this.expandAllTableColumns(collectMetadata);
}
// Check for table.* (chain: [tableName, "*"])
if (chain.length === 2 && chain[1] === "*") {
const tableAlias = chain[0];
if (typeof tableAlias === "string") {
return this.expandTableColumns(tableAlias, collectMetadata);
}
}
return null;
}
/**
* Expand SELECT * to core columns only from all tables in context.
* Non-core columns are tracked in hiddenColumns for user notification.
*/
private expandAllTableColumns(collectMetadata: boolean): string[] {
const results: string[] = [];
// Iterate through all tables in the context
for (const [tableAlias, tableSchema] of this.tableContexts.entries()) {
const tableColumns = this.getSelectableColumnsFromSchema(
tableSchema,
tableAlias,
collectMetadata,
true // onlyCoreColumns - SELECT * only returns core columns
);
results.push(...tableColumns);
}
// If no tables in context, fall back to literal *
if (results.length === 0) {
return ["*"];
}
return results;
}
/**
* Expand table.* to core columns only from a specific table.
* Non-core columns are tracked in hiddenColumns for user notification.
*/
private expandTableColumns(tableAlias: string, collectMetadata: boolean): string[] {
const tableSchema = this.tableContexts.get(tableAlias);
if (!tableSchema) {
// Table not found in context, fall back to literal table.*
return [`${this.printIdentifier(tableAlias)}.*`];
}
return this.getSelectableColumnsFromSchema(
tableSchema,
tableAlias,
collectMetadata,
true // onlyCoreColumns - table.* only returns core columns
);
}
/**
* Get selectable columns from a table schema as SQL strings
*
* @param tableSchema - The table schema
* @param tableAlias - The alias used for the table in the query (for table-qualified columns)
* @param collectMetadata - Whether to collect column metadata
* @param onlyCoreColumns - If true, only return core columns and track hidden columns (but falls back to all columns if no core columns are defined)
* @returns Array of SQL column strings
*/
private getSelectableColumnsFromSchema(
tableSchema: TableSchema,
tableAlias: string,
collectMetadata: boolean,
onlyCoreColumns = false
): string[] {
const results: string[] = [];
// Check if any core columns exist - if not, we'll return all columns as a fallback
const hasCoreColumns = Object.values(tableSchema.columns).some(
(col) => col.coreColumn === true && col.selectable !== false
);
// Only filter to core columns if the schema defines some core columns
const shouldFilterToCoreOnly = onlyCoreColumns && hasCoreColumns;
for (const [columnName, columnSchema] of Object.entries(tableSchema.columns)) {
// Skip non-selectable columns
if (columnSchema.selectable === false) {
continue;
}
// If filtering to core columns only, skip non-core and track them
if (shouldFilterToCoreOnly && !columnSchema.coreColumn) {
this.hiddenColumns.push(columnName);
continue;
}
// Build the SQL for this column
let sqlResult: string;
// Check if this is a virtual column (has expression)
if (isVirtualColumn(columnSchema)) {
// Virtual column: use the expression with an alias
sqlResult = `(${columnSchema.expression}) AS ${this.printIdentifier(columnName)}`;
} else if (columnSchema.textColumn) {
// JSON column with text column optimization: use the text column with alias
sqlResult = `${this.printIdentifier(columnSchema.textColumn)} AS ${this.printIdentifier(
columnName
)}`;
} else {
// Regular column: use the actual ClickHouse column name
const clickhouseName = columnSchema.clickhouseName ?? columnName;
// If the column has a different internal name, add an alias
if (clickhouseName !== columnName) {
sqlResult = `${this.printIdentifier(clickhouseName)} AS ${this.printIdentifier(
columnName
)}`;
} else {
sqlResult = this.printIdentifier(columnName);
}
}
results.push(sqlResult);
// Collect metadata if requested
if (collectMetadata) {
const metadata: OutputColumnMetadata = {
name: columnName,
type: columnSchema.type,
};
if (columnSchema.customRenderType) {
metadata.customRenderType = columnSchema.customRenderType;
}
if (columnSchema.description) {
metadata.description = columnSchema.description;
}
this.outputColumns.push(metadata);
}
}
return results;
}
/**
* Analyze a SELECT column expression to extract output name, source column, and type
*/
private analyzeSelectColumn(col: Expression): {
outputName: string | null;
sourceColumn: Partial<ColumnSchema> | null;
inferredType: ClickHouseType | null;
} {
// Handle Alias - the output name is the alias
if ((col as Alias).expression_type === "alias") {
const alias = col as Alias;
const innerAnalysis = this.analyzeSelectColumn(alias.expr);
return {
outputName: alias.alias,
sourceColumn: innerAnalysis.sourceColumn,
inferredType: innerAnalysis.inferredType,
};
}
// Handle Field - the output name is the column name
if ((col as Field).expression_type === "field") {
const field = col as Field;
const columnInfo = this.resolveFieldToColumn(field.chain);
return {
outputName: columnInfo.outputName,
sourceColumn: columnInfo.column,
inferredType: columnInfo.column?.type ?? null,
};
}
// Handle Call (function/aggregation) - infer type from function
if ((col as Call).expression_type === "call") {
const call = col as Call;
const inferredType = this.inferCallType(call);
// For value-preserving aggregates (SUM, AVG, MIN, MAX), propagate customRenderType
// from the source column. COUNT and other aggregates return counts, not values,
// so they shouldn't inherit the source column's render type.
const valuePreservingAggregates = [
"sum",
"sumif",
"avg",
"avgif",
"min",
"minif",
"max",
"maxif",
"quantile",
];
const funcName = call.name.toLowerCase();
let sourceColumn: Partial<ColumnSchema> | null = null;
if (valuePreservingAggregates.includes(funcName) && call.args.length > 0) {
const firstArg = call.args[0];
if ((firstArg as Field).expression_type === "field") {
const field = firstArg as Field;
const columnInfo = this.resolveFieldToColumn(field.chain);
// Only propagate customRenderType, not the full column schema
if (columnInfo.column?.customRenderType) {
sourceColumn = {
type: inferredType,
customRenderType: columnInfo.column.customRenderType,
};
}
}
}
return {
outputName: this.generateImplicitName(call),
sourceColumn,
inferredType,
};
}
// Handle ArithmeticOperation - infer type
if ((col as ArithmeticOperation).expression_type === "arithmetic_operation") {
const arith = col as ArithmeticOperation;
const inferredType = this.inferArithmeticType(arith);
return {
outputName: this.generateImplicitName(arith),
sourceColumn: null,
inferredType,
};
}
// Handle Constant
if ((col as Constant).expression_type === "constant") {
const constant = col as Constant;
const inferredType = this.inferConstantType(constant);
return {
outputName: this.generateImplicitName(constant),
sourceColumn: null,
inferredType,
};
}