-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathprinter.test.ts
More file actions
2614 lines (2181 loc) · 94.6 KB
/
printer.test.ts
File metadata and controls
2614 lines (2181 loc) · 94.6 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
import { describe, it, expect, beforeEach } from "vitest";
import { parseTSQLSelect, parseTSQLExpr } from "../index.js";
import { ClickHousePrinter, printToClickHouse, type PrintResult } from "./printer.js";
import { createPrinterContext, PrinterContext } from "./printer_context.js";
import { createSchemaRegistry, column, type TableSchema, type SchemaRegistry } from "./schema.js";
import { QueryError, SyntaxError } from "./errors.js";
/**
* Test table schemas
*/
const taskRunsSchema: TableSchema = {
name: "task_runs",
clickhouseName: "trigger_dev.task_runs_v2",
columns: {
id: { name: "id", ...column("String") },
status: { name: "status", ...column("String") },
task_identifier: { name: "task_identifier", ...column("String") },
created_at: { name: "created_at", ...column("DateTime64") },
updated_at: { name: "updated_at", ...column("DateTime64") },
started_at: { name: "started_at", ...column("Nullable(DateTime64)") },
completed_at: { name: "completed_at", ...column("Nullable(DateTime64)") },
duration_ms: { name: "duration_ms", ...column("Nullable(UInt64)") },
organization_id: { name: "organization_id", ...column("String") },
project_id: { name: "project_id", ...column("String") },
environment_id: { name: "environment_id", ...column("String") },
queue_name: { name: "queue_name", ...column("String") },
is_test: { name: "is_test", ...column("UInt8") },
},
tenantColumns: {
organizationId: "organization_id",
projectId: "project_id",
environmentId: "environment_id",
},
};
const taskEventsSchema: TableSchema = {
name: "task_events",
clickhouseName: "trigger_dev.task_events_v2",
columns: {
id: { name: "id", ...column("String") },
run_id: { name: "run_id", ...column("String") },
event_type: { name: "event_type", ...column("String") },
timestamp: { name: "timestamp", ...column("DateTime64") },
payload: { name: "payload", ...column("String") },
organization_id: { name: "organization_id", ...column("String") },
project_id: { name: "project_id", ...column("String") },
environment_id: { name: "environment_id", ...column("String") },
},
tenantColumns: {
organizationId: "organization_id",
projectId: "project_id",
environmentId: "environment_id",
},
};
/**
* Schema with user-friendly names that map to internal ClickHouse names
*/
const runsSchema: TableSchema = {
name: "runs", // User writes: FROM runs
clickhouseName: "trigger_dev.task_runs_v2", // ClickHouse sees this
columns: {
id: { name: "id", clickhouseName: "run_id", ...column("String") },
friendly_id: { name: "friendly_id", ...column("String") }, // No mapping
created: { name: "created", clickhouseName: "created_at", ...column("DateTime64") },
updated: { name: "updated", clickhouseName: "updated_at", ...column("DateTime64") },
status: { name: "status", ...column("String") },
task: { name: "task", clickhouseName: "task_identifier", ...column("String") },
org_id: { name: "org_id", clickhouseName: "organization_id", ...column("String") },
proj_id: { name: "proj_id", clickhouseName: "project_id", ...column("String") },
env_id: { name: "env_id", clickhouseName: "environment_id", ...column("String") },
},
tenantColumns: {
organizationId: "organization_id",
projectId: "project_id",
environmentId: "environment_id",
},
};
/**
* Helper to create a test context
*/
function createTestContext(
overrides: Partial<Parameters<typeof createPrinterContext>[0]> = {}
): PrinterContext {
const schema = createSchemaRegistry([taskRunsSchema, taskEventsSchema]);
return createPrinterContext({
organizationId: "org_test123",
projectId: "proj_test456",
environmentId: "env_test789",
schema,
...overrides,
});
}
/**
* Helper to print a query and get SQL + params
*/
function printQuery(query: string, context?: PrinterContext) {
const ast = parseTSQLSelect(query);
const ctx = context ?? createTestContext();
return printToClickHouse(ast, ctx);
}
describe("ClickHousePrinter", () => {
describe("Basic SELECT statements", () => {
it("should expand SELECT * to individual columns", () => {
const { sql, params, columns } = printQuery("SELECT * FROM task_runs");
// SELECT * should be expanded to individual columns
expect(sql).toContain("SELECT ");
expect(sql).not.toContain("SELECT *"); // Should NOT contain literal *
expect(sql).toContain("FROM trigger_dev.task_runs_v2");
// Should include all columns from the schema
expect(sql).toContain("id");
expect(sql).toContain("status");
expect(sql).toContain("task_identifier");
expect(sql).toContain("created_at");
expect(sql).toContain("is_test");
// Should include tenant guards in WHERE
expect(sql).toContain("organization_id");
expect(sql).toContain("project_id");
expect(sql).toContain("environment_id");
// Should return column metadata for all expanded columns
expect(columns.length).toBeGreaterThan(0);
expect(columns.some((c) => c.name === "id")).toBe(true);
expect(columns.some((c) => c.name === "status")).toBe(true);
});
it("should print SELECT with specific columns", () => {
const { sql, params } = printQuery("SELECT id, status, created_at FROM task_runs");
expect(sql).toContain("SELECT id, status, created_at");
expect(sql).toContain("FROM trigger_dev.task_runs_v2");
});
it("should print SELECT DISTINCT", () => {
const { sql } = printQuery("SELECT DISTINCT status FROM task_runs");
expect(sql).toContain("SELECT DISTINCT status");
});
it("should print SELECT with aliases", () => {
const { sql } = printQuery("SELECT id AS run_id, status AS run_status FROM task_runs");
expect(sql).toContain("id AS run_id");
expect(sql).toContain("status AS run_status");
});
it("should expand SELECT * with column name mapping", () => {
const schema = createSchemaRegistry([runsSchema]);
const ctx = createPrinterContext({
organizationId: "org_test",
projectId: "proj_test",
environmentId: "env_test",
schema,
});
const { sql, columns } = printQuery("SELECT * FROM runs", ctx);
// Should expand to all columns from runsSchema with proper aliases
expect(sql).not.toContain("SELECT *");
// Should have AS clauses for columns with different clickhouseName
expect(sql).toContain("run_id AS id"); // id -> run_id with alias back to id
expect(sql).toContain("created_at AS created"); // created -> created_at with alias back
expect(sql).toContain("status"); // status stays as-is
// Should return column metadata with user-facing names
expect(columns.length).toBeGreaterThan(0);
expect(columns.some((c) => c.name === "id")).toBe(true);
expect(columns.some((c) => c.name === "created")).toBe(true);
expect(columns.some((c) => c.name === "status")).toBe(true);
});
it("should expand table.* for specific table", () => {
const { sql, columns } = printQuery("SELECT task_runs.* FROM task_runs");
// Should expand to all columns from task_runs
expect(sql).not.toContain("task_runs.*");
expect(sql).toContain("id");
expect(sql).toContain("status");
// Should return column metadata
expect(columns.length).toBeGreaterThan(0);
});
it("should include virtual columns in SELECT * expansion", () => {
// Schema with virtual columns
const schemaWithVirtual: TableSchema = {
name: "runs",
clickhouseName: "trigger_dev.task_runs_v2",
columns: {
id: { name: "id", ...column("String") },
started_at: { name: "started_at", ...column("Nullable(DateTime64)") },
completed_at: { name: "completed_at", ...column("Nullable(DateTime64)") },
// Virtual column with expression
duration: {
name: "duration",
...column("Nullable(Int64)"),
expression: "dateDiff('millisecond', started_at, completed_at)",
description: "Execution duration in ms",
},
org_id: { name: "org_id", clickhouseName: "organization_id", ...column("String") },
proj_id: { name: "proj_id", clickhouseName: "project_id", ...column("String") },
env_id: { name: "env_id", clickhouseName: "environment_id", ...column("String") },
},
tenantColumns: {
organizationId: "organization_id",
projectId: "project_id",
environmentId: "environment_id",
},
};
const schema = createSchemaRegistry([schemaWithVirtual]);
const ctx = createPrinterContext({
organizationId: "org_test",
projectId: "proj_test",
environmentId: "env_test",
schema,
});
const { sql, columns } = printQuery("SELECT * FROM runs", ctx);
// Should include virtual column with its expression
expect(sql).toContain("dateDiff('millisecond', started_at, completed_at)");
expect(sql).toContain("AS duration");
// Should include regular columns
expect(sql).toContain("id");
// Metadata should include the virtual column
expect(columns.some((c) => c.name === "duration")).toBe(true);
const durationCol = columns.find((c) => c.name === "duration");
expect(durationCol?.description).toBe("Execution duration in ms");
});
});
describe("Table and column name mapping", () => {
function createMappedContext() {
const schema = createSchemaRegistry([runsSchema]);
return createPrinterContext({
organizationId: "org_test",
projectId: "proj_test",
environmentId: "env_test",
schema,
});
}
it("should map user-friendly table name to ClickHouse name", () => {
const ctx = createMappedContext();
const { sql } = printQuery("SELECT * FROM runs", ctx);
// Table name should be mapped
expect(sql).toContain("FROM trigger_dev.task_runs_v2");
expect(sql).not.toContain("FROM runs");
});
it("should map user-friendly column names to ClickHouse names", () => {
const ctx = createMappedContext();
const { sql } = printQuery("SELECT id, created, status FROM runs", ctx);
// id -> run_id, created -> created_at, status stays as status
expect(sql).toContain("run_id");
expect(sql).toContain("created_at");
expect(sql).toContain("status");
});
it("should map column names in WHERE clause", () => {
const ctx = createMappedContext();
const { sql } = printQuery("SELECT * FROM runs WHERE task = 'my-task'", ctx);
// task -> task_identifier
expect(sql).toContain("task_identifier");
expect(sql).not.toMatch(/\btask\b.*=/); // task should not appear as column
});
it("should map column names in ORDER BY", () => {
const ctx = createMappedContext();
const { sql } = printQuery("SELECT * FROM runs ORDER BY created DESC", ctx);
// created -> created_at
expect(sql).toContain("ORDER BY created_at DESC");
});
it("should map column names in GROUP BY", () => {
const ctx = createMappedContext();
const { sql } = printQuery("SELECT task, count(*) FROM runs GROUP BY task", ctx);
// task -> task_identifier in both SELECT and GROUP BY
expect(sql).toContain("task_identifier");
expect(sql).toContain("GROUP BY task_identifier");
});
it("should preserve unmapped column names", () => {
const ctx = createMappedContext();
const { sql } = printQuery("SELECT friendly_id, status FROM runs", ctx);
// friendly_id has no clickhouseName, should stay as-is
expect(sql).toContain("friendly_id");
expect(sql).toContain("status");
});
it("should handle qualified column references (table.column)", () => {
const ctx = createMappedContext();
const { sql } = printQuery("SELECT runs.id, runs.created FROM runs", ctx);
// Should still map the column names
expect(sql).toContain("run_id");
expect(sql).toContain("created_at");
});
it("should add AS alias for columns with different clickhouseName to preserve user-facing name in results", () => {
const ctx = createMappedContext();
const { sql, columns } = printQuery("SELECT id, created, status FROM runs", ctx);
// Columns with clickhouseName should be aliased back to user-facing name
// id -> run_id AS id, created -> created_at AS created
expect(sql).toContain("run_id AS id");
expect(sql).toContain("created_at AS created");
// status has no clickhouseName mapping, should not have alias
expect(sql).not.toContain("status AS");
// Column metadata should use user-facing names
expect(columns.map((c) => c.name)).toEqual(["id", "created", "status"]);
});
it("should add AS alias for qualified column references with different clickhouseName", () => {
const ctx = createMappedContext();
const { sql, columns } = printQuery("SELECT runs.id, runs.task FROM runs", ctx);
// Should add aliases to preserve user-facing names
expect(sql).toContain("run_id AS id");
expect(sql).toContain("task_identifier AS task");
// Column metadata should use user-facing names
expect(columns.map((c) => c.name)).toEqual(["id", "task"]);
});
it("should not add redundant alias when user provides explicit AS", () => {
const ctx = createMappedContext();
const { sql, columns } = printQuery("SELECT id AS my_id FROM runs", ctx);
// Should use the clickhouse name with user's explicit alias
expect(sql).toContain("run_id AS my_id");
// Should NOT have double aliasing
expect(sql).not.toContain("run_id AS id AS my_id");
// Column metadata should use the explicit alias
expect(columns.map((c) => c.name)).toEqual(["my_id"]);
});
});
describe("WHERE clauses", () => {
it("should print WHERE with equality comparison", () => {
const { sql, params } = printQuery("SELECT * FROM task_runs WHERE status = 'completed'");
expect(sql).toContain("WHERE");
expect(sql).toContain("equals(");
// Value should be parameterized
expect(Object.values(params)).toContain("completed");
});
it("should print WHERE with multiple conditions", () => {
const { sql } = printQuery(
"SELECT * FROM task_runs WHERE status = 'completed' AND is_test = 0"
);
expect(sql).toContain("and(");
expect(sql).toContain("equals(");
});
it("should print WHERE with OR conditions", () => {
const { sql } = printQuery(
"SELECT * FROM task_runs WHERE status = 'completed' OR status = 'failed'"
);
expect(sql).toContain("or(");
});
it("should print WHERE with NOT", () => {
const { sql } = printQuery("SELECT * FROM task_runs WHERE NOT status = 'pending'");
expect(sql).toContain("not(");
});
it("should print WHERE with BETWEEN", () => {
const { sql } = printQuery("SELECT * FROM task_runs WHERE duration_ms BETWEEN 100 AND 1000");
expect(sql).toContain("BETWEEN");
});
it("should print WHERE with IN", () => {
const { sql } = printQuery("SELECT * FROM task_runs WHERE status IN ('completed', 'failed')");
expect(sql).toContain("in(");
});
it("should print WHERE with NOT IN", () => {
const { sql } = printQuery("SELECT * FROM task_runs WHERE status NOT IN ('pending')");
expect(sql).toContain("notIn(");
});
it("should print WHERE with LIKE", () => {
const { sql } = printQuery("SELECT * FROM task_runs WHERE task_identifier LIKE 'email%'");
expect(sql).toContain("like(");
});
it("should print WHERE with ILIKE", () => {
const { sql } = printQuery("SELECT * FROM task_runs WHERE task_identifier ILIKE '%Email%'");
expect(sql).toContain("ilike(");
});
it("should handle NULL comparisons", () => {
const { sql } = printQuery("SELECT * FROM task_runs WHERE started_at = NULL");
expect(sql).toContain("isNull(");
});
it("should handle != NULL comparisons", () => {
const { sql } = printQuery("SELECT * FROM task_runs WHERE started_at != NULL");
expect(sql).toContain("isNotNull(");
});
it("should handle IS NULL syntax", () => {
const { sql } = printQuery("SELECT * FROM task_runs WHERE started_at IS NULL");
expect(sql).toContain("isNull(started_at)");
});
it("should handle IS NOT NULL syntax", () => {
const { sql } = printQuery("SELECT * FROM task_runs WHERE started_at IS NOT NULL");
expect(sql).toContain("isNotNull(started_at)");
});
});
describe("nullValue transformation for JSON columns", () => {
// Create a schema with JSON columns that have nullValue set
const jsonSchema: TableSchema = {
name: "runs",
clickhouseName: "trigger_dev.task_runs_v2",
columns: {
id: { name: "id", ...column("String") },
error: {
name: "error",
...column("JSON"),
nullValue: "'{}'", // Empty object represents NULL
},
output: {
name: "output",
...column("JSON"),
nullValue: "'{}'", // Empty object represents NULL
},
status: { name: "status", ...column("String") },
organization_id: { name: "organization_id", ...column("String") },
project_id: { name: "project_id", ...column("String") },
environment_id: { name: "environment_id", ...column("String") },
},
tenantColumns: {
organizationId: "organization_id",
projectId: "project_id",
environmentId: "environment_id",
},
};
function createJsonContext() {
const schema = createSchemaRegistry([jsonSchema]);
return createPrinterContext({
organizationId: "org_test",
projectId: "proj_test",
environmentId: "env_test",
schema,
});
}
it("should transform IS NULL to equals empty object for JSON columns with nullValue", () => {
const ctx = createJsonContext();
const { sql } = printQuery("SELECT * FROM runs WHERE error IS NULL", ctx);
// Should use equals with '{}' instead of isNull
expect(sql).toContain("equals(error, '{}')");
expect(sql).not.toContain("isNull(error)");
});
it("should transform IS NOT NULL to notEquals empty object for JSON columns with nullValue", () => {
const ctx = createJsonContext();
const { sql } = printQuery("SELECT * FROM runs WHERE error IS NOT NULL", ctx);
// Should use notEquals with '{}' instead of isNotNull
expect(sql).toContain("notEquals(error, '{}')");
expect(sql).not.toContain("isNotNull(error)");
});
it("should transform = NULL to equals empty object for JSON columns with nullValue", () => {
const ctx = createJsonContext();
const { sql } = printQuery("SELECT * FROM runs WHERE error = NULL", ctx);
expect(sql).toContain("equals(error, '{}')");
expect(sql).not.toContain("isNull(error)");
});
it("should transform != NULL to notEquals empty object for JSON columns with nullValue", () => {
const ctx = createJsonContext();
const { sql } = printQuery("SELECT * FROM runs WHERE error != NULL", ctx);
expect(sql).toContain("notEquals(error, '{}')");
expect(sql).not.toContain("isNotNull(error)");
});
it("should not affect regular columns without nullValue", () => {
const ctx = createJsonContext();
const { sql } = printQuery("SELECT * FROM runs WHERE status IS NULL", ctx);
// Regular column should still use isNull
expect(sql).toContain("isNull(status)");
});
it("should work with multiple JSON column NULL checks", () => {
const ctx = createJsonContext();
const { sql } = printQuery(
"SELECT * FROM runs WHERE error IS NOT NULL AND output IS NULL",
ctx
);
expect(sql).toContain("notEquals(error, '{}')");
expect(sql).toContain("equals(output, '{}')");
});
it("should allow GROUP BY on JSON columns without error", () => {
const ctx = createJsonContext();
const { sql } = printQuery(
"SELECT error, count() AS error_count FROM runs WHERE error IS NOT NULL GROUP BY error",
ctx
);
// Should filter with notEquals
expect(sql).toContain("notEquals(error, '{}')");
// Should group by the raw column
expect(sql).toContain("GROUP BY error");
});
it("should cast JSON subfield to String with underscore alias in SELECT and GROUP BY", () => {
const ctx = createJsonContext();
const { sql, columns } = printQuery(
"SELECT error.data.name, count() AS error_count FROM runs GROUP BY error.data.name",
ctx
);
// SELECT should use .:String type hint with underscore alias
expect(sql).toContain("error.data.name.:String AS error_data_name");
// GROUP BY should use .:String type hint (no alias needed)
expect(sql).toContain("GROUP BY error.data.name.:String");
// Column metadata should have the underscore alias name
expect(columns).toContainEqual(
expect.objectContaining({ name: "error_data_name", type: "String" })
);
expect(columns).toContainEqual(
expect.objectContaining({ name: "error_count", type: "UInt64" })
);
});
it("should cast JSON subfield to String with multiple fields and underscore aliases", () => {
const ctx = createJsonContext();
const { sql, columns } = printQuery(
"SELECT error.name, error.message, count() AS cnt FROM runs GROUP BY error.name, error.message",
ctx
);
// SELECT should have type hints with underscore aliases
expect(sql).toContain("error.name.:String AS error_name");
expect(sql).toContain("error.message.:String AS error_message");
// GROUP BY should have type hints
expect(sql).toContain("GROUP BY error.name.:String, error.message.:String");
// Column metadata should have correct names
expect(columns).toContainEqual(
expect.objectContaining({ name: "error_name", type: "String" })
);
expect(columns).toContainEqual(
expect.objectContaining({ name: "error_message", type: "String" })
);
});
it("should not cast non-JSON columns in GROUP BY", () => {
const ctx = createJsonContext();
const { sql } = printQuery("SELECT status, count() AS cnt FROM runs GROUP BY status", ctx);
// Regular columns should not have type hints
expect(sql).toContain("GROUP BY status");
expect(sql).not.toContain(".:String");
});
});
describe("ORDER BY clauses", () => {
it("should print ORDER BY ASC", () => {
const { sql } = printQuery("SELECT * FROM task_runs ORDER BY created_at ASC");
expect(sql).toContain("ORDER BY created_at ASC");
});
it("should print ORDER BY DESC", () => {
const { sql } = printQuery("SELECT * FROM task_runs ORDER BY created_at DESC");
expect(sql).toContain("ORDER BY created_at DESC");
});
it("should print ORDER BY with multiple columns", () => {
const { sql } = printQuery("SELECT * FROM task_runs ORDER BY status ASC, created_at DESC");
expect(sql).toContain("ORDER BY status ASC, created_at DESC");
});
});
describe("LIMIT and OFFSET", () => {
it("should print LIMIT", () => {
const { sql } = printQuery("SELECT * FROM task_runs LIMIT 10");
expect(sql).toContain("LIMIT 10");
});
it("should print LIMIT with OFFSET", () => {
const { sql } = printQuery("SELECT * FROM task_runs LIMIT 10 OFFSET 20");
expect(sql).toContain("LIMIT 10");
expect(sql).toContain("OFFSET 20");
});
it("should cap LIMIT to maxRows setting", () => {
const context = createTestContext({ settings: { maxRows: 100 } });
const { sql } = printQuery("SELECT * FROM task_runs LIMIT 1000", context);
expect(sql).toContain("LIMIT 100");
});
it("should add default LIMIT when none specified", () => {
const context = createTestContext({ settings: { maxRows: 10000 } });
const { sql } = printQuery("SELECT * FROM task_runs", context);
expect(sql).toContain("LIMIT 10000");
});
});
describe("GROUP BY clauses", () => {
it("should print GROUP BY", () => {
const { sql } = printQuery("SELECT status, count(*) FROM task_runs GROUP BY status");
expect(sql).toContain("GROUP BY status");
});
it("should print GROUP BY with multiple columns", () => {
const { sql } = printQuery(
"SELECT status, queue_name, count(*) FROM task_runs GROUP BY status, queue_name"
);
expect(sql).toContain("GROUP BY status, queue_name");
});
it("should print GROUP BY with HAVING", () => {
const { sql } = printQuery(
"SELECT status, count(*) as cnt FROM task_runs GROUP BY status HAVING cnt > 10"
);
expect(sql).toContain("GROUP BY status");
expect(sql).toContain("HAVING");
expect(sql).toContain("greater(");
});
});
describe("Aggregate functions", () => {
it("should print COUNT", () => {
const { sql } = printQuery("SELECT count(*) FROM task_runs");
expect(sql).toContain("count(*)");
});
it("should print COUNT DISTINCT", () => {
const { sql } = printQuery("SELECT count(DISTINCT status) FROM task_runs");
expect(sql).toContain("count(DISTINCT status)");
});
it("should print SUM", () => {
const { sql } = printQuery("SELECT sum(duration_ms) FROM task_runs");
expect(sql).toContain("sum(duration_ms)");
});
it("should print AVG", () => {
const { sql } = printQuery("SELECT avg(duration_ms) FROM task_runs");
expect(sql).toContain("avg(duration_ms)");
});
it("should print MIN and MAX", () => {
const { sql } = printQuery("SELECT min(created_at), max(created_at) FROM task_runs");
expect(sql).toContain("min(created_at)");
expect(sql).toContain("max(created_at)");
});
});
describe("Arithmetic operations", () => {
it("should print addition", () => {
const { sql } = printQuery("SELECT duration_ms + 100 FROM task_runs");
expect(sql).toContain("plus(duration_ms, 100)");
});
it("should print subtraction", () => {
const { sql } = printQuery("SELECT duration_ms - 100 FROM task_runs");
expect(sql).toContain("minus(duration_ms, 100)");
});
it("should print multiplication", () => {
const { sql } = printQuery("SELECT duration_ms * 2 FROM task_runs");
expect(sql).toContain("multiply(duration_ms, 2)");
});
it("should print division", () => {
const { sql } = printQuery("SELECT duration_ms / 1000 FROM task_runs");
expect(sql).toContain("divide(duration_ms, 1000)");
});
it("should print modulo", () => {
const { sql } = printQuery("SELECT duration_ms % 60 FROM task_runs");
expect(sql).toContain("modulo(duration_ms, 60)");
});
});
describe("Tenant isolation", () => {
it("should inject tenant guards for single table", () => {
const context = createTestContext({
organizationId: "org_abc",
projectId: "proj_def",
environmentId: "env_ghi",
});
const { sql, params } = printQuery("SELECT * FROM task_runs", context);
// Should have WHERE clause with tenant columns
expect(sql).toContain("WHERE");
expect(sql).toContain("organization_id");
expect(sql).toContain("project_id");
expect(sql).toContain("environment_id");
// Values should be parameterized
expect(Object.values(params)).toContain("org_abc");
expect(Object.values(params)).toContain("proj_def");
expect(Object.values(params)).toContain("env_ghi");
});
it("should combine tenant guards with user WHERE clause", () => {
const { sql } = printQuery("SELECT * FROM task_runs WHERE status = 'completed'");
// Should have both tenant guard AND user condition
expect(sql).toContain("and(");
expect(sql).toContain("organization_id");
expect(sql).toContain("equals(");
});
});
describe("SQL injection prevention", () => {
it("should parameterize string values", () => {
const { sql, params } = printQuery(
"SELECT * FROM task_runs WHERE status = 'DROP TABLE users'"
);
// The malicious string should be in params, not in SQL
expect(sql).not.toContain("DROP TABLE");
expect(Object.values(params)).toContain("DROP TABLE users");
});
it("should safely handle identifiers with special characters", () => {
// This should either escape or reject
expect(() => {
printQuery("SELECT * FROM task_runs WHERE `weird`column` = 'test'");
}).toThrow();
});
it("should only allow tables defined in schema", () => {
// Users cannot query arbitrary tables - only those in the schema
expect(() => {
printQuery("SELECT * FROM system_tables");
}).toThrow();
expect(() => {
printQuery("SELECT * FROM unknown_table");
}).toThrow();
});
it("should parameterize numeric values inline", () => {
const { sql, params } = printQuery("SELECT * FROM task_runs WHERE duration_ms > 1000");
// Numbers can be inlined safely
expect(sql).toContain("1000");
});
it("should handle boolean values safely", () => {
const { sql } = printQuery("SELECT * FROM task_runs WHERE is_test = 1");
expect(sql).toContain("equals(is_test, 1)");
});
});
describe("Subqueries", () => {
it("should print subquery in FROM clause", () => {
const { sql } = printQuery(`
SELECT status, cnt
FROM (
SELECT status, count(*) as cnt
FROM task_runs
GROUP BY status
)
`);
expect(sql).toContain("SELECT status, cnt");
expect(sql).toContain("FROM (");
expect(sql).toContain("count(*)");
});
it("should print subquery in WHERE clause", () => {
const { sql } = printQuery(`
SELECT * FROM task_runs
WHERE id IN (SELECT run_id FROM task_events WHERE event_type = 'completed')
`);
expect(sql).toContain("in(id,");
expect(sql).toContain("SELECT run_id FROM");
});
});
describe("UNION queries", () => {
it("should print UNION ALL", () => {
const { sql } = printQuery(`
SELECT id, status FROM task_runs WHERE status = 'completed'
UNION ALL
SELECT id, status FROM task_runs WHERE status = 'failed'
`);
expect(sql).toContain("UNION ALL");
});
});
describe("Window functions", () => {
it("should print ROW_NUMBER", () => {
const { sql } = printQuery(`
SELECT id, status, row_number() OVER (PARTITION BY status ORDER BY created_at DESC) as rn
FROM task_runs
`);
expect(sql).toContain("row_number()");
expect(sql).toContain("OVER (");
expect(sql).toContain("PARTITION BY status");
expect(sql).toContain("ORDER BY created_at DESC");
});
});
describe("Functions", () => {
it("should print toDateTime with column argument", () => {
const { sql } = printQuery("SELECT toDateTime(created_at) FROM task_runs");
expect(sql).toContain("toDateTime(created_at)");
});
it("should print toDateTime with string and timezone arguments", () => {
const { sql, params } = printQuery(
"SELECT toDateTime('2024-01-15 10:30:00', 'UTC') FROM task_runs"
);
// String values are parameterized for security
expect(sql).toContain("toDateTime(");
expect(sql).toMatch(/toDateTime\(\{tsql_val_\d+: String\}, \{tsql_val_\d+: String\}\)/);
expect(Object.values(params)).toContain("2024-01-15 10:30:00");
expect(Object.values(params)).toContain("UTC");
});
it("should print toDateTime with timezone containing special characters", () => {
const { sql, params } = printQuery(
"SELECT toDateTime('2024-01-15 10:30:00', 'America/New_York') FROM task_runs"
);
// String values are parameterized for security
expect(sql).toContain("toDateTime(");
expect(sql).toMatch(/toDateTime\(\{tsql_val_\d+: String\}, \{tsql_val_\d+: String\}\)/);
expect(Object.values(params)).toContain("2024-01-15 10:30:00");
expect(Object.values(params)).toContain("America/New_York");
});
it("should print toDateTime64 with precision and timezone", () => {
const { sql, params } = printQuery(
"SELECT toDateTime64('2024-01-15 10:30:00.500000', 6, 'Europe/London') FROM task_runs"
);
// String values are parameterized, but numeric precision is inline
expect(sql).toContain("toDateTime64(");
expect(sql).toMatch(/toDateTime64\(\{tsql_val_\d+: String\}, 6, \{tsql_val_\d+: String\}\)/);
expect(Object.values(params)).toContain("2024-01-15 10:30:00.500000");
expect(Object.values(params)).toContain("Europe/London");
});
it("should print now()", () => {
const { sql } = printQuery("SELECT * FROM task_runs WHERE created_at > now()");
expect(sql).toContain("now()");
});
it("should print string functions", () => {
const { sql } = printQuery("SELECT lower(status), upper(queue_name) FROM task_runs");
expect(sql).toContain("lower(status)");
expect(sql).toContain("upper(queue_name)");
});
it("should print conditional functions", () => {
const { sql } = printQuery("SELECT if(is_test = 1, 'test', 'prod') FROM task_runs");
expect(sql).toContain("if(");
});
it("should print coalesce", () => {
const { sql } = printQuery("SELECT coalesce(started_at, created_at) FROM task_runs");
expect(sql).toContain("coalesce(started_at, created_at)");
});
});
describe("Arrays and tuples", () => {
it("should print array literals", () => {
const { sql } = printQuery("SELECT * FROM task_runs WHERE status IN ['completed', 'failed']");
expect(sql).toContain("[");
expect(sql).toContain("]");
});
it("should print tuple", () => {
const { sql } = printQuery("SELECT tuple(id, status) FROM task_runs");
expect(sql).toContain("tuple(id, status)");
});
});
describe("Error handling", () => {
it("should throw QueryError for unknown tables", () => {
expect(() => {
printQuery("SELECT * FROM unknown_table");
}).toThrow(QueryError);
});
it("should throw QueryError for unknown functions", () => {
expect(() => {
printQuery("SELECT unknown_function(id) FROM task_runs");
}).toThrow(QueryError);
});
it("should throw QueryError for nested aggregations", () => {
expect(() => {
printQuery("SELECT sum(count(*)) FROM task_runs");
}).toThrow(QueryError);
});
it("should throw SyntaxError for malformed queries", () => {
expect(() => {
parseTSQLSelect("SELECT * FORM task_runs"); // typo: FORM instead of FROM
}).toThrow();
});
});
describe("Pretty printing", () => {
it("should format SQL with newlines when pretty=true", () => {
const ast = parseTSQLSelect(
"SELECT id, status FROM task_runs WHERE status = 'completed' ORDER BY created_at"
);
const context = createTestContext();
const printer = new ClickHousePrinter(context, { pretty: true });
const { sql } = printer.print(ast);
expect(sql).toContain("\n");
});
it("should produce single-line SQL when pretty=false", () => {
const ast = parseTSQLSelect(
"SELECT id, status FROM task_runs WHERE status = 'completed' ORDER BY created_at"
);
const context = createTestContext();
const printer = new ClickHousePrinter(context, { pretty: false });
const { sql } = printer.print(ast);
// Count newlines - there should be very few or none in the main query structure
const newlineCount = (sql.match(/\n/g) || []).length;