forked from taozhi8833998/node-sql-parser
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathselect.spec.js
More file actions
1583 lines (1421 loc) · 65.4 KB
/
select.spec.js
File metadata and controls
1583 lines (1421 loc) · 65.4 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
const { expect } = require('chai');
const Parser = require('../src/parser').default
describe('select', () => {
const parser = new Parser();
function getParsedSql(sql, opt) {
const ast = parser.astify(sql, opt);
return parser.sqlify(ast, opt);
}
it('should be null if empty', () => {
const ast = parser.astify('SELECT a');
expect(ast.options).to.be.null;
expect(ast.distinct).to.be.null;
expect(ast.from).to.be.null;
expect(ast.where).to.be.null;
expect(ast.groupby).to.be.null;
expect(ast.orderby).to.be.null;
expect(ast.limit).to.be.null;
});
it('should support * with optional table prefix and other columns alias', () => {
[
{
sql: 'SELECT *, \'a\' as col2 FROM table1',
expected: 'SELECT *, \'a\' AS `col2` FROM `table1`'
},
{
sql: 'SELECT table1.*, \'a\' as col2 FROM table1',
expected: 'SELECT `table1`.*, \'a\' AS `col2` FROM `table1`'
}
].forEach(({sql, expected}, index) => {
const ast = parser.astify(sql)
expect(ast.options).to.be.null;
expect(ast.distinct).to.be.null;
expect(ast.columns).to.be.eql([
{
"expr": {
"type": "column_ref",
"table": index === 0 ? null: "table1",
"column": "*"
},
"as": null
},
{
"expr": {
"type": "single_quote_string",
"value": "a"
},
"as": "col2"
}
]);
expect(ast.from).to.be.eql([
{
"db": null,
"table": "table1",
"as": null
}
]);
expect(ast.where).to.be.null;
expect(ast.groupby).to.be.null;
expect(ast.orderby).to.be.null;
expect(ast.limit).to.be.null;
expect(parser.sqlify(ast)).to.be.eql(expected)
})
})
it('should support for update', () => {
const ast = parser.astify('select SOME_COLUMN from TABLE_NAME where ID_COLUMN = 0 for update');
expect(parser.sqlify(ast)).to.eql('SELECT `SOME_COLUMN` FROM `TABLE_NAME` WHERE `ID_COLUMN` = 0 FOR UPDATE');
});
it('should support for update with wait', () => {
const ast = parser.astify('select SOME_COLUMN from TABLE_NAME where ID_COLUMN = 0 for update wait 1234');
expect(parser.sqlify(ast)).to.eql('SELECT `SOME_COLUMN` FROM `TABLE_NAME` WHERE `ID_COLUMN` = 0 FOR UPDATE WAIT 1234');
});
it('should support for update with nowait', () => {
const ast = parser.astify('select SOME_COLUMN from TABLE_NAME where ID_COLUMN = 0 for update nowait');
expect(parser.sqlify(ast)).to.eql('SELECT `SOME_COLUMN` FROM `TABLE_NAME` WHERE `ID_COLUMN` = 0 FOR UPDATE NOWAIT');
});
it('should support for update with skip locked', () => {
const ast = parser.astify('select SOME_COLUMN from TABLE_NAME where ID_COLUMN = 0 for update skip locked');
expect(parser.sqlify(ast)).to.eql('SELECT `SOME_COLUMN` FROM `TABLE_NAME` WHERE `ID_COLUMN` = 0 FOR UPDATE SKIP LOCKED');
});
it('should support lock in share mode', () => {
const ast = parser.astify('select SOME_COLUMN from TABLE_NAME where ID_COLUMN = 0 lock in share mode');
expect(parser.sqlify(ast)).to.eql('SELECT `SOME_COLUMN` FROM `TABLE_NAME` WHERE `ID_COLUMN` = 0 LOCK IN SHARE MODE');
});
it('should support lock in share mode with wait', () => {
const ast = parser.astify('select SOME_COLUMN from TABLE_NAME where ID_COLUMN = 0 lock in share mode wait 1234');
expect(parser.sqlify(ast)).to.eql('SELECT `SOME_COLUMN` FROM `TABLE_NAME` WHERE `ID_COLUMN` = 0 LOCK IN SHARE MODE WAIT 1234');
});
it('should support lock in share mode witn nowait', () => {
const ast = parser.astify('select SOME_COLUMN from TABLE_NAME where ID_COLUMN = 0 lock in share mode nowait');
expect(parser.sqlify(ast)).to.eql('SELECT `SOME_COLUMN` FROM `TABLE_NAME` WHERE `ID_COLUMN` = 0 LOCK IN SHARE MODE NOWAIT');
});
it('should support lock in share mode with skip locked', () => {
const ast = parser.astify('select SOME_COLUMN from TABLE_NAME where ID_COLUMN = 0 lock in share mode skip locked');
expect(parser.sqlify(ast)).to.eql('SELECT `SOME_COLUMN` FROM `TABLE_NAME` WHERE `ID_COLUMN` = 0 LOCK IN SHARE MODE SKIP LOCKED');
});
it('should support div as divsion', () => {
expect(getParsedSql('SELECT * FROM businesses WHERE SUBSTRING(street_physical, 1, LENGTH(street_physical) div 2) = SUBSTRING(street_physical, LENGTH(street_physical) DIV 2 + 1, LENGTH(street_physical) / 2);'))
.to.be.equal('SELECT * FROM `businesses` WHERE SUBSTRING(`street_physical`, 1, LENGTH(`street_physical`) DIV 2) = SUBSTRING(`street_physical`, LENGTH(`street_physical`) DIV 2 + 1, LENGTH(`street_physical`) / 2)')
})
it('should support select * from', () => {
const ast = parser.astify('SELECT *from abc');
expect(ast.options).to.be.null;
expect(ast.distinct).to.be.null;
expect(ast.columns).to.be.eql([{
expr: {
type: 'column_ref',
table: null,
column: '*'
},
as: null
}])
expect(ast.from).to.be.eql([
{
"db": null,
"table": "abc",
"as": null
}
]);
expect(ast.where).to.be.null;
expect(ast.groupby).to.be.null;
expect(ast.orderby).to.be.null;
expect(ast.limit).to.be.null;
});
it('should support parse any column name', () => {
const sql = 'select book_view.code from book_view where book_view.type= "A"'
const ast = parser.astify(sql)
const backSQL = parser.sqlify(ast)
expect(backSQL).to.be.equal('SELECT `book_view`.`code` FROM `book_view` WHERE `book_view`.`type` = "A"')
})
it('should have appropriate types', () => {
const ast = parser.astify('SELECT SQL_NO_CACHE DISTINCT a FROM b WHERE c = 0 GROUP BY d ORDER BY e limit 3');
expect(ast.options).to.be.an('array');
expect(ast.distinct).to.equal('DISTINCT');
expect(ast.from).to.be.an('array');
expect(ast.where).to.be.an('object');
expect(ast.groupby).to.be.an('object');
expect(ast.groupby.columns).to.be.an('array');
expect(ast.orderby).to.be.an('array');
expect(ast.limit).to.be.an('object');
});
describe('column clause', () => {
it('should parse "*" shorthand', () => {
const ast = parser.astify('SELECT * FROM t');
expect(ast.columns).to.be.eql([{
expr: {
type: 'column_ref',
table: null,
column: '*'
},
as: null
}]);
});
it('should parse "table.*" column expressions', () => {
const ast = parser.astify('SELECT t.* FROM t');
expect(ast.columns).to.eql([
{ expr: { type: 'column_ref', table: 't', column: '*' }, as: null }
]);
});
it('should parse json column query expressions', () => {
const ast = parser.astify("SELECT item.jsonCol->>'$.test.path' from 'items'");
expect(parser.sqlify(ast)).to.be.equal("SELECT `item`.`jsonCol` ->> '$.test.path' FROM `items`")
});
it('should parse json column query expressions with collate', () => {
const ast = parser.astify("SELECT item.jsonCol->>'$.test.path' collate utf8mb4_unicode_ci from 'items'");
expect(parser.sqlify(ast)).to.be.equal("SELECT `item`.`jsonCol` ->> '$.test.path' COLLATE utf8mb4_unicode_ci FROM `items`")
});
it('should parse aliases w/o "AS" keyword', () => {
const ast = parser.astify('SELECT a aa FROM t');
expect(ast.columns).to.eql([
{ expr: { collate: null, type: 'column_ref', table: null, column: 'a' }, as: 'aa' }
]);
});
it('should parse aliases w/ "AS" keyword', () => {
const ast = parser.astify('SELECT b.c as bc FROM t');
expect(ast.columns).to.eql([
{ expr: { collate: null, type: 'column_ref', table: 'b', column: 'c' }, as: 'bc' }
]);
});
describe('logic operator', () => {
it('should support column concatenation operator', () => {
const { tableList, columnList, ast } = parser.parse('SELECT "a" || "," || b as ab, t.cd && "ef" FROM t');
expect(tableList).to.eql(['select::null::t']);
expect(columnList).to.eql(['select::null::b', 'select::t::cd']);
expect(ast.columns).to.eql([
{
expr: {
type: 'binary_expr',
operator: '||',
left: {
type: 'binary_expr',
operator: '||',
left: {
type: 'double_quote_string',
value: 'a'
},
right: {
type: 'double_quote_string',
value: ','
}
},
right: {
collate: null,
type: 'column_ref',
table: null,
column: 'b'
}
},
as: 'ab'
},
{
expr: {
type: 'binary_expr',
operator: '&&',
left: {
collate: null,
type: 'column_ref',
table: 't',
column: 'cd'
},
right: {
type: 'double_quote_string',
value: 'ef'
}
},
"as": null
}
]);
expect(ast.options).to.be.null;
expect(ast.distinct).to.be.null;
expect(ast.from).to.be.eql([
{
db: null,
table: 't',
as: null
}
]);
expect(ast.where).to.be.null;
expect(ast.groupby).to.be.null;
expect(ast.orderby).to.be.null;
expect(ast.limit).to.be.null;
});
})
describe('functions', () => {
it(`should parse function dot name`, () => {
const ast = parser.astify(`SELECT a.func() FROM t`);
expect(parser.sqlify(ast)).to.eql('SELECT a.func() FROM `t`');
});
it('should parse extract function in pg', () => {
const opt = { database: 'postgresql' }
const ast = parser.astify("SELECT EXTRACT(MICROSECONDS FROM TIME '17:12:28.5')", opt);
expect(parser.sqlify(ast, opt)).to.eql("SELECT EXTRACT(MICROSECONDS FROM TIME '17:12:28.5')");
expect(parser.sqlify(parser.astify("SELECT EXTRACT(MILLISECONDS FROM TIMESTAMP '2016-12-31 13:30:15')", opt), opt)).to.eql("SELECT EXTRACT(MILLISECONDS FROM TIMESTAMP '2016-12-31 13:30:15')");
expect(parser.sqlify(parser.astify("SELECT EXTRACT(MILLISECONDS FROM '2016-12-31 13:30:15')", opt), opt)).to.eql("SELECT EXTRACT(MILLISECONDS FROM '2016-12-31 13:30:15')");
expect(parser.sqlify(parser.astify(`WITH tss AS
(SELECT CURRENT_TIMESTAMP AS ts)
SELECT
EXTRACT(EPOCH FROM ts)
FROM
tss`, opt), opt)).to.eql('WITH "tss" AS (SELECT CURRENT_TIMESTAMP AS "ts") SELECT EXTRACT(EPOCH FROM ts) FROM "tss"');
});
it('should parse function expression', () => {
const ast = parser.astify('SELECT fun(d) FROM t');
expect(ast.columns).to.eql([
{
expr: {
type: 'function',
name: { name: [{ type: 'default', value: 'fun' }]},
over: null,
args: {
type : 'expr_list',
value : [ { collate: null, type: 'column_ref', table: null, column: 'd' } ]
}
},
as: null
}
]);
})
it('should support select group_concat', () => {
let sql = "select group_concat(distinct asd) as 'abc';"
expect(getParsedSql(sql)).to.equal('SELECT GROUP_CONCAT(DISTINCT `asd`) AS `abc`')
sql = "select group_concat(distinct(asd)) as 'abc';"
expect(getParsedSql(sql)).to.equal('SELECT GROUP_CONCAT(DISTINCT (`asd`)) AS `abc`')
sql = "select Quantity, group_concat(distinct(IF(Quantity>10, \"MORE\", \"LESS\"))) as 'abc';"
expect(getParsedSql(sql)).to.equal('SELECT `Quantity`, GROUP_CONCAT(DISTINCT (IF(`Quantity` > 10, "MORE", "LESS"))) AS `abc`')
sql = "select group_concat(distinct(organization.name) order by organization.name) as colum1"
expect(getParsedSql(sql)).to.equal('SELECT GROUP_CONCAT(DISTINCT (`organization`.`name`) ORDER BY `organization`.`name` ASC) AS `colum1`')
})
it('should parse position function',() => {
const ast = parser.astify("SELECT position(', ' in 'a, b')")
expect(ast.columns).to.eql([
{
expr: {
type: 'function',
name: { name: [{ type: 'default', value: 'position' }]},
over: null,
args: {
type: 'expr_list',
value: [
{
type: 'binary_expr',
operator: 'IN',
left: { type: 'single_quote_string', value: ', ' },
right: { type: 'single_quote_string', value: 'a, b' }
}
]
}
},
as: null
}
]);
expect(parser.sqlify(ast)).to.be.equal("SELECT position(', ' IN 'a, b')")
});
[
'CURRENT_DATE',
'CURRENT_TIME',
'CURRENT_TIMESTAMP',
'CURRENT_USER',
'SESSION_USER',
'USER',
'SYSTEM_USER'
].forEach((func) => {
const columnAst = [
{
expr: {
type: 'function',
name: { name: [{ type: 'default', value: func }]},
over: null,
args: {
type: 'expr_list',
value: []
}
},
as: null
}
]
it(`should parse scalar function ${func}() with parentheses`, () => {
const ast = parser.astify(`SELECT ${func}() FROM t`);
expect(ast.columns).to.eql(columnAst);
});
});
it('should support function argument with and expr', () => {
expect(getParsedSql('SELECT IF((`open_time` <= UNIX_TIMESTAMP()) AND (`close_time` > UNIX_TIMESTAMP()), 1, 0) FROM sometable'))
.to.be.equal('SELECT IF((`open_time` <= UNIX_TIMESTAMP()) AND (`close_time` > UNIX_TIMESTAMP()), 1, 0) FROM `sometable`')
})
});
it('should parse multiple columns', () => {
const ast = parser.astify('SELECT b.c as bc, 1+3 FROM t');
expect(ast.columns).to.eql([
{ expr: { collate: null, type: 'column_ref', table: 'b', column: 'c' }, as: 'bc' },
{
expr: {
type: 'binary_expr',
operator: '+',
left: { type: 'number', value: 1 },
right: { type: 'number', value: 3 }
},
as: null
}
]);
});
});
describe('from clause', () => {
it('should parse single table', () => {
const ast = parser.astify('SELECT * FROM t');
expect(ast.from).to.eql([{ db: null, table: 't', as: null }]);
});
it('should parse tables from other databases', () => {
const ast = parser.astify('SELECT * FROM u.t');
expect(ast.from).to.eql([{ db: 'u', table: 't', as: null }]);
});
it('should parse tables from other databases (ANSI identifier)', () => {
const ast = parser.astify('SELECT * FROM "u"."t"');
expect(ast.from).to.eql([{ db: 'u', table: 't', as: null }]);
});
it('should support keyword as tablename', () => {
const sql = 'select user0__.user_id as userId from user user0__'
const ast = parser.astify(sql)
const backSQL = parser.sqlify(ast)
expect(backSQL).to.equal('SELECT `user0__`.`user_id` AS `userId` FROM `user` AS `user0__`')
})
it('should support select from db.xxx.table', () => {
const sql = 'select id from db-name.public.table-name'
const opt = { database: 'postgresql' }
const ast = parser.astify(sql, opt)
const backSQL = parser.sqlify(ast,opt )
expect(backSQL).to.equal('SELECT id FROM "db-name"."public"."table-name"')
})
it('should parse subselect', () => {
const ast = parser.astify('SELECT * FROM (SELECT id FROM t1) someAlias');
expect(ast.from).to.eql([{
expr: {
tableList: ['select::null::t1'],
columnList: ['select::null::(.*)', 'select::null::id'],
ast: {
with: null,
type: 'select',
options: null,
distinct: null,
locking_read: null,
from: [{ db: null, table: 't1', as: null }],
columns: [{ expr: { collate: null, type: 'column_ref', table: null, column: 'id' }, as: null }],
into: { position: null },
where: null,
groupby: null,
having: null,
orderby: null,
collate: null,
limit: null,
window: null,
},
parentheses: true
},
as: 'someAlias'
}]);
});
describe('joins', () => {
it('should parse implicit joins', () => {
const ast = parser.astify('SELECT * FROM t, a.b b, c.d as cd');
expect(ast.from).to.eql([
{ db: null, table: 't', as: null },
{ db: 'a', table: 'b', as: 'b' },
{ db: 'c', table: 'd', as: 'cd' }
]);
});
['left', 'right', 'full'].forEach((join) => {
[' ', ' outer '].forEach((outer) => {
it(`should parse ${join}${outer}joins`, () => {
const ast = parser.astify(`SELECT * FROM t ${join} ${outer} join d on d.d = d.a`);
expect(ast.from).to.eql([
{ db: null, table: 't', as: null },
{
db: null,
table: 'd',
as: null,
join: `${join.toUpperCase()} JOIN`,
on: {
type: 'binary_expr',
operator: '=',
left: { collate: null, type: 'column_ref', table: 'd', column: 'd' },
right: { collate: null, type: 'column_ref', table: 'd', column: 'a' }
}
}
]);
});
});
});
it('should parse joined subselect', () => {
const ast = parser.astify('SELECT * FROM t1 JOIN (SELECT id, col1 FROM t2) someAlias ON t1.id = someAlias.id');
expect(ast.from).to.eql([
{ db: null, table: 't1', as: null },
{
expr: {
tableList: ["select::null::t2"],
columnList: ["select::null::(.*)", "select::null::id", "select::null::col1"],
ast: {
with: null,
type: 'select',
options: null,
distinct: null,
locking_read: null,
from: [{ db: null, table: 't2', as: null }],
columns: [
{ expr: { collate: null, type: 'column_ref', table: null, 'column': 'id' }, as: null },
{ expr: { collate: null, type: 'column_ref', table: null, 'column': 'col1' }, as: null }
],
into: { position: null },
where: null,
groupby: null,
having: null,
orderby: null,
collate: null,
limit: null,
window: null,
},
parentheses: true
},
as: 'someAlias',
join: 'INNER JOIN',
on: {
type: 'binary_expr',
operator: '=',
left: { collate: null, type: 'column_ref', table: 't1', column: 'id' },
right: { collate: null, type: 'column_ref', table: 'someAlias', column: 'id' }
}
}
]);
});
it('should parse joins with USING (single column)', () => {
const ast = parser.astify('SELECT * FROM t1 JOIN t2 USING (id)');
expect(ast.from).to.eql([
{ db: null, table: 't1', as: null },
{ db: null, table: 't2', as: null, join: 'INNER JOIN', using: [{ type: 'default', value: 'id' }] }
]);
});
it('should parse joins with USING (multiple columns)', () => {
const ast = parser.astify('SELECT * FROM t1 JOIN t2 USING (id1, `id2`)');
expect(ast.from).to.eql([
{ db: null, table: 't1', as: null },
{ db: null, table: 't2', as: null, join: 'INNER JOIN', using: [{ type: 'default', value: 'id1' }, { type: 'backticks_quote_string', value: 'id2' }] }
]);
});
});
it('should parse DUAL table', () => {
const ast = parser.astify('SELECT * FROM DUAL');
expect(ast.from).to.eql([{ type: 'dual' }]);
});
it('should parse function as table in pg', () => {
const opt = { database: 'postgresql' }
const sql = "select * from generate_series('2021-01-01'::date, '2021-12-31'::date, '1 day')"
expect(getParsedSql(sql, opt)).to.be.equal("SELECT * FROM generate_series('2021-01-01'::DATE, '2021-12-31'::DATE, '1 day')")
});
});
describe('where clause', () => {
it('should parse single condition', () => {
const ast = parser.astify('SELECT * FROM t where t.a > 0');
expect(ast.where).to.eql({
type: 'binary_expr',
operator: '>',
left: { collate: null, type: 'column_ref', table: 't', column: 'a' },
right: { type: 'number', value: 0 }
});
});
it('should parse like and or statement', () => {
expect(getParsedSql(`SELECT a, b, c FROM tb WHERE a like 'test1' OR b = 'test2';`)).to.equal("SELECT `a`, `b`, `c` FROM `tb` WHERE `a` LIKE 'test1' OR `b` = 'test2'")
})
it('should parse or statement with parentheses', () => {
expect(getParsedSql(`select * from tableName where (a = 1 or b = 2) and c=3;`)).to.equal("SELECT * FROM `tableName` WHERE (`a` = 1 OR `b` = 2) AND `c` = 3")
expect(getParsedSql(`select * from tableName where (a = 1) or b = 2 and c=3;`)).to.equal("SELECT * FROM `tableName` WHERE (`a` = 1) OR `b` = 2 AND `c` = 3")
expect(getParsedSql(`select * from tableName where (name LIKE "dummy" and sku = "dummy") or b = 2 and c=3;`)).to.equal('SELECT * FROM `tableName` WHERE (`name` LIKE "dummy" AND `sku` = "dummy") OR `b` = 2 AND `c` = 3')
expect(getParsedSql(`select * from tableName where (a = 1 and b = 2) or c=3;`)).to.equal("SELECT * FROM `tableName` WHERE (`a` = 1 AND `b` = 2) OR `c` = 3")
expect(getParsedSql(`select * from tableName where a = 1 or (b = 2) and c=3;`)).to.equal("SELECT * FROM `tableName` WHERE `a` = 1 OR (`b` = 2) AND `c` = 3")
expect(getParsedSql(`select * from tableName where a = 1 or (b = 2 and d=4) and c=3;`)).to.equal("SELECT * FROM `tableName` WHERE `a` = 1 OR (`b` = 2 AND `d` = 4) AND `c` = 3")
expect(getParsedSql(`SELECT * FROM messages WHERE (year = 2012 AND month >= 9) OR (year = 2021 AND month <= 4) OR (year > 2012 AND year < 2021);`)).to.equal("SELECT * FROM `messages` WHERE (`year` = 2012 AND `month` >= 9) OR (`year` = 2021 AND `month` <= 4) OR (`year` > 2012 AND `year` < 2021)")
expect(getParsedSql(`SELECT max('Y')
FROM "TABLE_1" as ST INNER JOIN
(SELECT * FROM "TABLE_2" AS JT_1
WHERE JT_1.dcc_user_y_n='N' and JT_1.wax_user_y_n='N'
)
ON ST.senderId=JT_1.customerId
WHERE (ST.is_pmt_official_y_n='Y' and ST.rcvr_id IN ('1903441177248177755','1253078913466070789','2028875792797419044','1363196721610324064') and ST.pmt_usd_amt>0 and (ST.pmt_txn_status_code='S' or (ST.pmt_txn_status_code='V' and ST.cum_pmt_cnt=1)) and ST.sndr_type_key=1) AND (ST.pmt_cre_dt>=JT_2.cust_signup_dt) GROUP BY JT_1.cust_id`)).to.equal("SELECT MAX('Y') FROM `TABLE_1` AS `ST` INNER JOIN (SELECT * FROM `TABLE_2` AS `JT_1` WHERE `JT_1`.`dcc_user_y_n` = 'N' AND `JT_1`.`wax_user_y_n` = 'N') ON `ST`.`senderId` = `JT_1`.`customerId` WHERE (`ST`.`is_pmt_official_y_n` = 'Y' AND `ST`.`rcvr_id` IN ('1903441177248177755', '1253078913466070789', '2028875792797419044', '1363196721610324064') AND `ST`.`pmt_usd_amt` > 0 AND (`ST`.`pmt_txn_status_code` = 'S' OR (`ST`.`pmt_txn_status_code` = 'V' AND `ST`.`cum_pmt_cnt` = 1)) AND `ST`.`sndr_type_key` = 1) AND (`ST`.`pmt_cre_dt` >= `JT_2`.`cust_signup_dt`) GROUP BY `JT_1`.`cust_id`")
})
it('should parse parameters', () => {
const ast = parser.astify('SELECT * FROM t where t.a > :my_param');
expect(ast.where).to.eql({
type: 'binary_expr',
operator: '>',
left: { collate: null, type: 'column_ref', table: 't', column: 'a' },
right: { type: 'param', value: 'my_param' }
});
});
it('should parse multiple conditions', () => {
const ast = parser.astify(`SELECT * FROM t where t.c between 1 and 't' AND Not true`);
expect(ast.where).to.eql({
type: 'binary_expr',
operator: 'AND',
left: {
type: 'binary_expr',
operator: 'BETWEEN',
left: { collate: null, type: 'column_ref', table: 't', column: 'c' },
right: {
type : 'expr_list',
value : [
{ type: 'number', value: 1 },
{ type: 'single_quote_string', value: 't' }
]
}
},
right: {
type: 'unary_expr',
operator: 'NOT',
expr: { type: 'bool', value: true }
}
});
});
it('should parse single condition with boolean', () => {
const ast = parser.astify('SELECT * FROM t where t.a = TRUE');
expect(ast.where).to.eql({
type: 'binary_expr',
operator: '=',
left: { collate: null, type: 'column_ref', table: 't', column: 'a' },
right: { type: 'bool', value: true }
});
});
it('should parse multiple condition with boolean', () => {
expect(getParsedSql('SELECT id FROM t where deleted and not suspended')).to.be.equal('SELECT `id` FROM `t` WHERE `deleted` AND NOT `suspended`')
expect(getParsedSql('SELECT id FROM t where not deleted and not suspended')).to.be.equal('SELECT `id` FROM `t` WHERE NOT `deleted` AND NOT `suspended`')
expect(getParsedSql('SELECT id FROM t where deleted and suspended')).to.be.equal('SELECT `id` FROM `t` WHERE `deleted` AND `suspended`')
expect(getParsedSql('SELECT id FROM t where true and id > 10')).to.be.equal('SELECT `id` FROM `t` WHERE TRUE AND `id` > 10')
});
['is', 'is not'].forEach((operator) => {
it(`should parse ${operator} condition`, () => {
const ast = parser.astify(`SELECT * FROM t WHERE col ${operator} NULL`);
expect(ast.where).to.eql({
type: 'binary_expr',
operator: operator.toUpperCase(),
left: { collate: null, type: 'column_ref', table: null, column: 'col' },
right: { type: 'null', value: null }
});
});
});
['not exists'].forEach((operator) => {
it('should parse ' + operator.toUpperCase() + ' condition', () => {
const ast = parser.astify(`SELECT * FROM t WHERE ${operator} (SELECT 1)`);
expect(ast.where).to.eql({
type: 'unary_expr',
operator: operator.toUpperCase(),
expr: {
tableList: [],
columnList: ["select::null::(.*)"],
ast: {
with: null,
type: 'select',
options: null,
distinct: null,
locking_read: null,
columns: [{ expr: { type: 'number', value: 1 }, as: null }],
into: { position: null },
from: null,
where: null,
groupby: null,
having: null,
orderby: null,
collate: null,
limit: null,
window: null,
},
parentheses: true
}
});
});
});
it('should parse exists condition', () => {
const operator = 'EXISTS'
const sql = `SELECT * FROM t WHERE ${operator} (SELECT 1)`
expect(getParsedSql(sql)).to.be.equal('SELECT * FROM `t` WHERE EXISTS(SELECT 1)')
});
it(`should parse + and - unary`, () => {
const { tableList, columnList, ast } = parser.parse('select -1, -a, +b, +abc.e from abc')
expect(tableList).to.eql(['select::null::abc'])
expect(columnList).to.eql([
'select::null::a',
'select::null::b',
'select::abc::e'
])
expect(ast.columns).to.eql([
{
expr: { type: 'number', value: -1 },
as: null
},
{
expr: { type: 'unary_expr', operator: '-', expr: { collate: null, type: 'column_ref', table: null, column: 'a' } } ,
as: null
},
{
expr: { type: 'unary_expr', operator: '+', expr: { collate: null, type: 'column_ref', table: null, column: 'b' } },
as: null
},
{
expr: { type: 'unary_expr', operator: '+', expr: { collate: null, type: 'column_ref', table: 'abc', column: 'e' } },
as: null
}
])
expect(ast.options).to.be.null;
expect(ast.distinct).to.be.null;
expect(ast.from).to.eql([
{
db: null,
table: 'abc',
as: null
}
]);
expect(ast.where).to.be.null;
expect(ast.groupby).to.be.null;
expect(ast.orderby).to.be.null;
expect(ast.limit).to.be.null;
})
it('should support left and convert fun', () => {
expect(getParsedSql(`select * from test where LEFT(column,2)="ts";`))
.to.equal('SELECT * FROM `test` WHERE LEFT(`column`, 2) = "ts"')
expect(getParsedSql(`select * from test where CONVERT(column, DATE)="test";`))
.to.equal('SELECT * FROM `test` WHERE CONVERT(`column`, DATE) = "test"')
expect(getParsedSql(`select * from test where CONVERT(column using utf8)="test";`))
.to.equal('SELECT * FROM `test` WHERE CONVERT(`column` USING UTF8) = "test"')
expect(getParsedSql(`SELECT CONVERT('test', CHAR CHARACTER SET utf8mb4);`))
.to.equal("SELECT CONVERT('test', CHAR CHARACTER SET utf8mb4)")
expect(getParsedSql(`SELECT CONVERT('test', CHAR(10) CHARACTER SET utf8mb4);`))
.to.equal("SELECT CONVERT('test', CHAR(10) CHARACTER SET utf8mb4)")
expect(getParsedSql(`SELECT CONVERT('test' USING utf8mb4) COLLATE utf8mb4_bin;`))
.to.equal("SELECT CONVERT('test' USING UTF8MB4) COLLATE utf8mb4_bin")
expect(getParsedSql(`SELECT CONCAT("a", "b") COLLATE UTF8MB4_BIN = "AB" AS result`))
.to.equal('SELECT CONCAT("a", "b") COLLATE UTF8MB4_BIN = "AB" AS `result`')
})
it('should parse COLLATE on function expressions', () => {
const ast = parser.astify('SELECT CONCAT("a", "b") COLLATE UTF8MB4_BIN = "AB" AS result');
expect(ast.columns[0]).to.have.property('as', 'result');
expect(ast.columns[0].expr).to.have.property('type', 'binary_expr');
expect(ast.columns[0].expr).to.have.property('operator', '=');
expect(ast.columns[0].expr.left).to.have.property('type', 'function');
expect(ast.columns[0].expr.left).to.have.property('collate');
expect(ast.columns[0].expr.left.collate).to.have.property('type', 'collate');
expect(ast.columns[0].expr.left.collate.collate).to.have.property('name', 'UTF8MB4_BIN');
})
it('should parse COLLATE on CONVERT expressions', () => {
const ast = parser.astify("SELECT CONVERT('test' USING utf8mb4) COLLATE utf8mb4_bin");
expect(ast.columns[0].expr).to.have.property('type', 'function');
expect(ast.columns[0].expr).to.have.property('collate');
expect(ast.columns[0].expr.collate).to.have.property('type', 'collate');
expect(ast.columns[0].expr.collate.collate).to.have.property('name', 'utf8mb4_bin');
})
it('should parse COLLATE on parenthesized expressions', () => {
const ast = parser.astify("SELECT * FROM product WHERE (id = '1' OR id = '2') COLLATE utf8mb4_general_ci");
expect(ast.where).to.have.property('type', 'binary_expr');
expect(ast.where).to.have.property('operator', 'OR');
expect(ast.where).to.have.property('parentheses', true);
expect(ast.where).to.have.property('collate');
expect(ast.where.collate).to.have.property('type', 'collate');
expect(ast.where.collate.collate).to.have.property('name', 'utf8mb4_general_ci');
})
it('should parse COLLATE on CAST expressions', () => {
const ast = parser.astify('SELECT CAST(test AS CHAR CHARACTER SET utf8mb4) COLLATE utf8mb4_bin');
expect(ast.columns[0].expr).to.have.property('type', 'cast');
expect(ast.columns[0].expr).to.have.property('collate');
expect(ast.columns[0].expr.collate).to.have.property('type', 'collate');
expect(ast.columns[0].expr.collate.collate).to.have.property('name', 'utf8mb4_bin');
})
it('should parse COLLATE on arithmetic expressions', () => {
const ast = parser.astify('SELECT (1 + 2) COLLATE UTF8_BIN = "12" AS result');
expect(ast.columns[0]).to.have.property('as', 'result');
expect(ast.columns[0].expr).to.have.property('type', 'binary_expr');
expect(ast.columns[0].expr).to.have.property('operator', '=');
expect(ast.columns[0].expr.left).to.have.property('type', 'binary_expr');
expect(ast.columns[0].expr.left).to.have.property('parentheses', true);
expect(ast.columns[0].expr.left).to.have.property('collate');
expect(ast.columns[0].expr.left.collate).to.have.property('type', 'collate');
expect(ast.columns[0].expr.left.collate.collate).to.have.property('name', 'UTF8_BIN');
})
it('should support convert additive expr', () => {
expect(getParsedSql(`select TYPE,taxpayer_Type,CONVERT(tax_Amount, DECIMAL(12,2)) AS tax_amount,CAST(tax_currency AS DECIMAL(12,2)) tax_currency from rs_order_tax where billno="{{billno}}" and Business_Type="order";`))
.to.equal('SELECT `TYPE`, `taxpayer_Type`, CONVERT(`tax_Amount`, DECIMAL(12, 2)) AS `tax_amount`, CAST(`tax_currency` AS DECIMAL(12, 2)) AS `tax_currency` FROM `rs_order_tax` WHERE `billno` = "{{billno}}" AND `Business_Type` = "order"')
expect(getParsedSql(`SELECT CONVERT('test', INT(11) unsigned);`))
.to.equal("SELECT CONVERT('test', INT(11) UNSIGNED)")
})
it('should support if', () => {
expect(getParsedSql(`select a from test where b like IF(-1 = -1, 'a', 'b');`))
.to.equal("SELECT `a` FROM `test` WHERE `b` LIKE IF(-1 = -1, 'a', 'b')")
})
})
describe('limit clause', () => {
it('should be parsed w/o', () => {
const ast = parser.astify('SELECT DISTINCT a FROM b WHERE c = 0 GROUP BY d ORDER BY e ASC limit 10');
expect(ast.limit).eql({
seperator: '',
value: [
{ type: 'number', value: 10 }
],
});
expect(parser.sqlify(ast)).to.be.equal('SELECT DISTINCT `a` FROM `b` WHERE `c` = 0 GROUP BY `d` ORDER BY `e` ASC LIMIT 10')
});
it('should be parsed w/o', () => {
const ast = parser.astify('SELECT DISTINCT a FROM b WHERE c = 0 GROUP BY d ORDER BY e limit 10,3');
expect(ast.limit).eql({
seperator: ',',
value: [
{ type: 'number', value: 10 },
{ type: 'number', value: 3 }
],
});
expect(parser.sqlify(ast)).to.be.equal('SELECT DISTINCT `a` FROM `b` WHERE `c` = 0 GROUP BY `d` ORDER BY `e` ASC LIMIT 10, 3')
});
it('should be parsed w/ offset', () => {
const ast = parser.astify('SELECT DISTINCT a FROM b WHERE c = 0 GROUP BY d ORDER BY e limit 10 offset 23');
expect(ast.limit).eql({
seperator: 'offset',
value: [
{ type: 'number', value: 10 },
{ type: 'number', value: 23 }
],
});
expect(parser.sqlify(ast)).to.be.equal('SELECT DISTINCT `a` FROM `b` WHERE `c` = 0 GROUP BY `d` ORDER BY `e` ASC LIMIT 10 OFFSET 23')
});
it('should be parsed pg offset', () => {
const opt = {
database: 'postgresql'
}
const ast = parser.astify('SELECT DISTINCT a FROM b WHERE c = 0 GROUP BY d ORDER BY e limit all', opt)
expect(ast.limit).to.be.eql({
seperator: '',
value: [
{ type: 'origin', value: 'all' },
],
});
expect(parser.sqlify(ast)).to.be.equal('SELECT DISTINCT a FROM `b` WHERE c = 0 GROUP BY d ORDER BY e ASC LIMIT ALL')
const offsetAst = parser.astify('SELECT DISTINCT a FROM b WHERE c = 0 GROUP BY d ORDER BY e limit all offset 100', opt);
expect(offsetAst.limit).eql({
seperator: 'offset',
value: [
{ type: 'origin', value: 'all' },
{ type: 'number', value: 100 }
],
});
expect(parser.sqlify(offsetAst)).to.be.equal('SELECT DISTINCT a FROM `b` WHERE c = 0 GROUP BY d ORDER BY e ASC LIMIT ALL OFFSET 100')
});
});
describe('group by clause', () => {
it('should parse single columns', () => {
const ast = parser.astify('SELECT a FROM b WHERE c = 0 GROUP BY d');
expect(ast.groupby.columns).to.eql([{ collate: null, type:'column_ref', table: null, column: 'd' }])
});
it('should parse multiple columns', () => {
const ast = parser.astify('SELECT a FROM b WHERE c = 0 GROUP BY d, t.b, t.c WITH ROLLUP');
expect(ast.groupby.columns).to.eql([
{ collate: null, type: 'column_ref', table: null, column: 'd' },
{ collate: null, type: 'column_ref', table: 't', column: 'b' },
{ collate: null, type: 'column_ref', table: 't', column: 'c' }
]);
expect(ast.groupby.modifiers).to.eql([
{ type: 'origin', value: 'with rollup' }
])
});
it('should parse column index', () => {
const sql = 'SELECT name, gender FROM Test.student GROUP BY 1, 2'
const ast = parser.astify(sql)
const backSQL = parser.sqlify(ast)
expect(backSQL).to.equal('SELECT `name`, `gender` FROM `Test`.`student` GROUP BY 1, 2')
})
it('should parser column expression', () => {
const sql = 'SELECT name, gender, date_format(gmt_created,"yyyyMM"), count(*) FROM Test.student GROUP BY date_format(gmt_created,"yyyyMM")'
const ast = parser.astify(sql)
const backSQL = parser.sqlify(ast)
expect(backSQL).to.equal('SELECT `name`, `gender`, date_format(`gmt_created`, "yyyyMM"), COUNT(*) FROM `Test`.`student` GROUP BY date_format(`gmt_created`, "yyyyMM")')
})
});
describe('having clause', () => {
it('should parse single conditions', () => {
const ast = parser.astify('SELECT col1 FROM t GROUP BY col2 HAVING COUNT(*) > 1');
expect(ast.having).to.eql({
type: 'binary_expr',
operator: '>',
left: {
type: 'aggr_func',
name: 'COUNT',
over: null,
args: { expr: { type: 'star', value: '*' } }
},
right: { type: 'number', value: 1 }
});
});
it('should parse multiple conditions', () => {
const ast = parser.astify('SELECT col1 FROM t GROUP BY col2 HAVING SUM(col2) > 10 OR 1 = 1');
expect(ast.having).to.eql({
type: 'binary_expr',
operator: 'OR',
left: {
type: 'binary_expr',
operator: '>',
left: {
type: 'aggr_func',
name: 'SUM',
over: null,
args: { expr: { collate: null, type: 'column_ref', table: null, column: 'col2' } }
},
right: { type: 'number', value: 10 }
},
right: {
type: 'binary_expr',
operator: '=',
left: { type: 'number', value: 1 },
right: { type: 'number', value: 1 }
}
});
});
it('should parse subselects', () => {
const sql = 'SELECT col1 FROM t GROUP BY col2 HAVING SUM(col2) > (SELECT 10)';
expect(getParsedSql(sql)).to.be.equal('SELECT `col1` FROM `t` GROUP BY `col2` HAVING SUM(`col2`) > (SELECT 10)')
});
});
describe('order by clause', () => {
it('should parse single column', () => {
const ast = parser.astify('SELECT a FROM b WHERE c = 0 order BY d');
expect(ast.orderby).to.eql([
{ expr: { collate: null, type: 'column_ref', table: null, column: 'd' }, type: null }
]);
});
it('should parse multiple columns', () => {
const ast = parser.astify('SELECT a FROM b WHERE c = 0 order BY d, t.b desc, t.c asc');
expect(ast.orderby).to.eql([
{ expr: { collate: null, type: 'column_ref', table: null, column: 'd' }, type: null },
{ expr: { collate: null, type: 'column_ref', table: 't', column: 'b' }, type: 'DESC' },
{ expr: { collate: null, type: 'column_ref', table: 't', column: 'c' }, type: 'ASC' }
]);
});
it('should parse expressions', () => {
const ast = parser.astify("SELECT a FROM b WHERE c = 0 order BY d, SuM(e)");
expect(ast.orderby).to.eql([