-
Notifications
You must be signed in to change notification settings - Fork 4
/
sql_parser.py
1046 lines (956 loc) · 34.5 KB
/
sql_parser.py
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
# bigquery_view_parser.py
#
# A parser to extract table names from BigQuery view definitions.
# This is based on the `select_parser.py` sample in pyparsing:
# https://github.com/pyparsing/pyparsing/blob/master/examples/select_parser.py
#
# Michael Smedberg
#
from pyparsing import ParserElement, Suppress, Forward, CaselessKeyword
from pyparsing import MatchFirst, alphas, alphanums, Combine, Word, Literal, White, Empty
from pyparsing import QuotedString, CharsNotIn, Optional, Group, ZeroOrMore, NoMatch
from pyparsing import oneOf, delimitedList, restOfLine, cStyleComment
from pyparsing import infixNotation, opAssoc, OneOrMore, Regex, nums
def debug(s, i, toks):
if len(toks) > 0:
#import ipdb; ipdb.set_trace()
pass
class SemanticToken(object):
def __iter__(self):
return (i for i in self.tokens)
def __len__(self):
return len(self.tokens)
class BigQueryViewParser:
"""Parser to extract table info from BigQuery view definitions"""
_parser = None
_table_identifiers = set()
_with_aliases = set()
def get_table_names(self, sql_stmt):
table_identifiers, with_aliases = self._parse(sql_stmt)
# Table names and alias names might differ by case, but that's not
# relevant- aliases are not case sensitive
lower_aliases = BigQueryViewParser.lowercase_set_of_tuples(with_aliases)
tables = {
x
for x in table_identifiers
if not BigQueryViewParser.lowercase_of_tuple(x) in lower_aliases
}
# Table names ARE case sensitive as described at
# https://cloud.google.com/bigquery/docs/reference/standard-sql/lexical#case_sensitivity
# return tables
return table_identifiers, with_aliases
def _parse(self, sql_stmt):
BigQueryViewParser._table_identifiers.clear()
BigQueryViewParser._with_aliases.clear()
res = BigQueryViewParser._get_parser().parseString(sql_stmt, parseAll=True)
def kk(v):
print(list(v.keys()))
return res
@classmethod
def lowercase_of_tuple(cls, tuple_to_lowercase):
return tuple(x.lower() if x else None for x in tuple_to_lowercase)
@classmethod
def lowercase_set_of_tuples(cls, set_of_tuples):
return {BigQueryViewParser.lowercase_of_tuple(x) for x in set_of_tuples}
@classmethod
def _get_parser(cls):
if cls._parser is not None:
return cls._parser
ParserElement.enablePackrat()
LPAR, RPAR, COMMA, LBRACKET, RBRACKET, LT, GT = map(Literal, "(),[]<>")
ungrouped_select_stmt = Forward().setName("select statement")
# keywords
(
UNION,
ALL,
AND,
INTERSECT,
EXCEPT,
COLLATE,
ASC,
DESC,
ON,
USING,
NATURAL,
INNER,
CROSS,
LEFT,
RIGHT,
OUTER,
FULL,
JOIN,
AS,
INDEXED,
NOT,
SELECT,
DISTINCT,
FROM,
WHERE,
GROUP,
BY,
HAVING,
ORDER,
BY,
LIMIT,
OFFSET,
OR,
CAST,
ISNULL,
NOTNULL,
NULL,
IS,
BETWEEN,
ELSE,
END,
CASE,
WHEN,
THEN,
EXISTS,
COLLATE,
IN,
LIKE,
GLOB,
REGEXP,
MATCH,
ESCAPE,
CURRENT_TIME,
CURRENT_DATE,
CURRENT_TIMESTAMP,
WITH,
EXTRACT,
PARTITION,
ROWS,
RANGE,
UNBOUNDED,
PRECEDING,
CURRENT,
ROW,
FOLLOWING,
OVER,
INTERVAL,
DATE_ADD,
DATE_SUB,
ADDDATE,
SUBDATE,
REGEXP_EXTRACT,
SPLIT,
ORDINAL,
FIRST_VALUE,
LAST_VALUE,
NTH_VALUE,
LEAD,
LAG,
PERCENTILE_CONT,
PRECENTILE_DISC,
RANK,
DENSE_RANK,
PERCENT_RANK,
CUME_DIST,
NTILE,
ROW_NUMBER,
DATE,
TIME,
DATETIME,
TIMESTAMP,
UNNEST,
INT64,
NUMERIC,
FLOAT64,
BOOL,
BYTES,
GEOGRAPHY,
ARRAY,
STRUCT,
SAFE_CAST,
ANY_VALUE,
ARRAY_AGG,
ARRAY_CONCAT_AGG,
AVG,
BIT_AND,
BIT_OR,
BIT_XOR,
COUNT,
COUNTIF,
LOGICAL_AND,
LOGICAL_OR,
MAX,
MIN,
STRING_AGG,
SUM,
CORR,
COVAR_POP,
COVAR_SAMP,
STDDEV_POP,
STDDEV_SAMP,
STDDEV,
VAR_POP,
VAR_SAMP,
VARIANCE,
TIMESTAMP_ADD,
TIMESTAMP_SUB,
GENERATE_ARRAY,
GENERATE_DATE_ARRAY,
GENERATE_TIMESTAMP_ARRAY,
FOR,
SYSTEMTIME,
AS,
OF,
WINDOW,
RESPECT,
IGNORE,
NULLS,
) = map(
CaselessKeyword,
"""
UNION, ALL, AND, INTERSECT, EXCEPT, COLLATE, ASC, DESC, ON, USING,
NATURAL, INNER, CROSS, LEFT, RIGHT, OUTER, FULL, JOIN, AS, INDEXED,
NOT, SELECT, DISTINCT, FROM, WHERE, GROUP, BY, HAVING, ORDER, BY,
LIMIT, OFFSET, OR, CAST, ISNULL, NOTNULL, NULL, IS, BETWEEN, ELSE,
END, CASE, WHEN, THEN, EXISTS, COLLATE, IN, LIKE, GLOB, REGEXP,
MATCH, ESCAPE, CURRENT_TIME, CURRENT_DATE, CURRENT_TIMESTAMP, WITH,
EXTRACT, PARTITION, ROWS, RANGE, UNBOUNDED, PRECEDING, CURRENT,
ROW, FOLLOWING, OVER, INTERVAL, DATE_ADD, DATE_SUB, ADDDATE,
SUBDATE, REGEXP_EXTRACT, SPLIT, ORDINAL, FIRST_VALUE, LAST_VALUE,
NTH_VALUE, LEAD, LAG, PERCENTILE_CONT, PRECENTILE_DISC, RANK,
DENSE_RANK, PERCENT_RANK, CUME_DIST, NTILE, ROW_NUMBER, DATE, TIME,
DATETIME, TIMESTAMP, UNNEST, INT64, NUMERIC, FLOAT64, BOOL, BYTES,
GEOGRAPHY, ARRAY, STRUCT, SAFE_CAST, ANY_VALUE, ARRAY_AGG,
ARRAY_CONCAT_AGG, AVG, BIT_AND, BIT_OR, BIT_XOR, COUNT, COUNTIF,
LOGICAL_AND, LOGICAL_OR, MAX, MIN, STRING_AGG, SUM, CORR,
COVAR_POP, COVAR_SAMP, STDDEV_POP, STDDEV_SAMP, STDDEV, VAR_POP,
VAR_SAMP, VARIANCE, TIMESTAMP_ADD, TIMESTAMP_SUB, GENERATE_ARRAY,
GENERATE_DATE_ARRAY, GENERATE_TIMESTAMP_ARRAY, FOR, SYSTEMTIME, AS,
OF, WINDOW, RESPECT, IGNORE, NULLS
""".replace(
",", ""
).split(),
)
keyword_nonfunctions = MatchFirst(
(
UNION,
ALL,
INTERSECT,
EXCEPT,
COLLATE,
ASC,
DESC,
ON,
USING,
NATURAL,
INNER,
CROSS,
LEFT,
RIGHT,
OUTER,
FULL,
JOIN,
AS,
INDEXED,
NOT,
SELECT,
DISTINCT,
FROM,
WHERE,
GROUP,
BY,
HAVING,
ORDER,
BY,
LIMIT,
OFFSET,
CAST,
ISNULL,
NOTNULL,
NULL,
IS,
BETWEEN,
ELSE,
END,
CASE,
WHEN,
THEN,
EXISTS,
COLLATE,
IN,
LIKE,
GLOB,
REGEXP,
MATCH,
STRUCT,
WINDOW,
)
)
keyword = keyword_nonfunctions | MatchFirst(
(
ESCAPE,
CURRENT_TIME,
CURRENT_DATE,
CURRENT_TIMESTAMP,
DATE_ADD,
DATE_SUB,
ADDDATE,
SUBDATE,
INTERVAL,
STRING_AGG,
REGEXP_EXTRACT,
SPLIT,
ORDINAL,
UNNEST,
SAFE_CAST,
PARTITION,
TIMESTAMP_ADD,
TIMESTAMP_SUB,
ARRAY,
GENERATE_ARRAY,
GENERATE_DATE_ARRAY,
GENERATE_TIMESTAMP_ARRAY,
)
)
identifier_word = Word(alphas + "_@#", alphanums + "@$#_")
identifier = ~keyword + identifier_word.copy()
collation_name = identifier.copy()
# NOTE: Column names can be keywords. Doc says they cannot, but in practice it seems to work.
column_name = identifier.copy()
cast_to = identifier.copy()
qualified_column_name = Group(
delimitedList(column_name, delim=".")
+ Optional(
Suppress("::")
+ delimitedList(cast_to("cast"), delim="::")
)
)
# NOTE: As with column names, column aliases can be keywords, e.g. functions like `current_time`. Other
# keywords, e.g. `from` make parsing pretty difficult (e.g. "SELECT a from from b" is confusing.)
column_alias = ~keyword_nonfunctions + column_name.copy()
table_name = identifier.copy()
table_alias = identifier.copy()
index_name = identifier.copy()
function_name = identifier.copy()
parameter_name = identifier.copy()
# NOTE: The expression in a CASE statement can be an integer. E.g. this is valid SQL:
# select CASE 1 WHEN 1 THEN -1 ELSE -2 END from test_table
unquoted_case_identifier = ~keyword + Word(alphanums + "$_")
quoted_case_identifier = ~keyword + (
QuotedString('"') ^ Suppress("`") + CharsNotIn("`") + Suppress("`")
)
case_identifier = quoted_case_identifier | unquoted_case_identifier
case_expr = (
Optional(case_identifier + Suppress("."))
+ Optional(case_identifier + Suppress("."))
+ case_identifier
)
# expression
expr = Forward().setName("expression")
integer = Regex(r"[+-]?\d+")
numeric_literal = Regex(r"[+-]?\d*\.?\d+([eE][+-]?\d+)?")
string_literal = QuotedString("'") | QuotedString('"') | QuotedString("`")
regex_literal = "r" + string_literal
blob_literal = Regex(r"[xX]'[0-9A-Fa-f]+'")
date_or_time_literal = (DATE | TIME | DATETIME | TIMESTAMP) + string_literal
literal_value = (
numeric_literal
| string_literal
| regex_literal
| blob_literal
| date_or_time_literal
| NULL
| CURRENT_TIME + Optional(LPAR + Optional(string_literal) + RPAR)
| CURRENT_DATE + Optional(LPAR + Optional(string_literal) + RPAR)
| CURRENT_TIMESTAMP + Optional(LPAR + Optional(string_literal) + RPAR)
)
bind_parameter = Word("?", nums) | Combine(oneOf(": @ $") + parameter_name)
type_name = oneOf(
"""TEXT REAL INTEGER BLOB NULL TIMESTAMP STRING DATE
INT64 NUMERIC FLOAT64 BOOL BYTES DATETIME GEOGRAPHY TIME ARRAY
STRUCT""",
caseless=True,
)
date_part = oneOf(
"""DAY DAY_HOUR DAY_MICROSECOND DAY_MINUTE DAY_SECOND
HOUR HOUR_MICROSECOND HOUR_MINUTE HOUR_SECOND MICROSECOND MINUTE
MINUTE_MICROSECOND MINUTE_SECOND MONTH QUARTER SECOND
SECOND_MICROSECOND WEEK YEAR YEAR_MONTH""",
caseless=True,
)
datetime_operators = (
DATE_ADD | DATE_SUB | ADDDATE | SUBDATE | TIMESTAMP_ADD | TIMESTAMP_SUB
)
def invalid_date_add(s, loc, tokens):
prev_newline = s[:loc].rfind('\n')
prev_prev_newline = s[:prev_newline].rfind('\n')
if '--ignore' in s[prev_prev_newline:prev_newline]:
pass
else:
raise RuntimeError("{} is not valid, did you mean 'date_add'".format(tokens[0]))
#bad_datetime_operators = (
# CaselessKeyword('dateadd').setParseAction(invalid_date_add)
#)
grouping_term = expr.copy()
ordering_term = Group(
expr("order_key")
+ Optional(COLLATE + collation_name("collate"))
+ Optional(ASC | DESC)("direction")
)("ordering_term")
function_arg = expr.copy()("function_arg")
function_args = Optional(
"*"
| Optional(DISTINCT)
+ delimitedList(function_arg)
+ Optional((RESPECT | IGNORE) + NULLS)
)("function_args")
function_call = (
(function_name | keyword)("function_name")
+ LPAR
+ Group(function_args)("function_args_group")
+ RPAR
)('function')
navigation_function_name = (
FIRST_VALUE
| LAST_VALUE
| NTH_VALUE
| LEAD
| LAG
| PERCENTILE_CONT
| PRECENTILE_DISC
)
aggregate_function_name = (
ANY_VALUE
| ARRAY_AGG
| ARRAY_CONCAT_AGG
| AVG
| BIT_AND
| BIT_OR
| BIT_XOR
| COUNT
| COUNTIF
| LOGICAL_AND
| LOGICAL_OR
| MAX
| MIN
| STRING_AGG
| SUM
)
statistical_aggregate_function_name = (
CORR
| COVAR_POP
| COVAR_SAMP
| STDDEV_POP
| STDDEV_SAMP
| STDDEV
| VAR_POP
| VAR_SAMP
| VARIANCE
)
numbering_function_name = (
RANK | DENSE_RANK | PERCENT_RANK | CUME_DIST | NTILE | ROW_NUMBER
)
analytic_function_name = (
navigation_function_name
| aggregate_function_name
| statistical_aggregate_function_name
| numbering_function_name
)("analytic_function_name")
partition_expression_list = delimitedList(grouping_term)(
"partition_expression_list"
)
window_frame_boundary_start = (
UNBOUNDED + PRECEDING
| numeric_literal + (PRECEDING | FOLLOWING)
| CURRENT + ROW
)
window_frame_boundary_end = (
UNBOUNDED + FOLLOWING
| numeric_literal + (PRECEDING | FOLLOWING)
| CURRENT + ROW
)
window_frame_clause = (ROWS | RANGE) + (
((UNBOUNDED + PRECEDING) | (numeric_literal + PRECEDING) | (CURRENT + ROW))
| (BETWEEN + window_frame_boundary_start + AND + window_frame_boundary_end)
)
window_name = identifier.copy()("window_name")
window_specification = (
Optional(window_name)
+ Optional(PARTITION + BY + partition_expression_list)
+ Optional(ORDER + BY + delimitedList(ordering_term))
+ Optional(window_frame_clause)("window_specification")
)
analytic_function = (
analytic_function_name
+ LPAR
+ function_args.setParseAction(debug)
+ RPAR
+ OVER
+ (window_name | LPAR + Optional(window_specification)('window') + RPAR)
)("analytic_function")
string_agg_term = (
STRING_AGG
+ LPAR
+ Optional(DISTINCT)('has_distinct')
+ expr('string_agg_expr')
+ Optional(COMMA + string_literal('delimiter'))
+ Optional(
ORDER + BY + expr + Optional(ASC | DESC) + Optional(LIMIT + integer)
)
+ RPAR
)("string_agg")
array_literal = (
Optional(ARRAY + Optional(LT + delimitedList(type_name) + GT))
+ LBRACKET
+ delimitedList(expr)
+ RBRACKET
)
interval = INTERVAL + expr + date_part
array_generator = (
GENERATE_ARRAY
+ LPAR
+ numeric_literal
+ COMMA
+ numeric_literal
+ COMMA
+ numeric_literal
+ RPAR
)
date_array_generator = (
(GENERATE_DATE_ARRAY | GENERATE_TIMESTAMP_ARRAY)
+ LPAR
+ expr("start_date")
+ COMMA
+ expr("end_date")
+ Optional(COMMA + interval)
+ RPAR
)
explicit_struct = (
STRUCT
+ Optional(LT + delimitedList(type_name) + GT)
+ LPAR
+ Optional(delimitedList(expr + Optional(AS + identifier)))
+ RPAR
)
case_when = WHEN + expr.copy()("when")
case_then = THEN + expr.copy()("then")
case_clauses = Group(ZeroOrMore(case_when + case_then))
case_else = ELSE + expr.copy()("_else")
case_stmt = (
CASE
+ Optional(case_expr.copy())
+ case_clauses("case_clauses")
+ Optional(case_else)
+ END
)("case")
class SelectStatement(SemanticToken):
def __init__(self, tokens):
self.tokens = tokens
def getName(self):
return 'select'
@classmethod
def parse(cls, tokens):
return SelectStatement(tokens)
class Function(SemanticToken):
def __init__(self, func, tokens):
self.func = func
self.tokens = tokens
def getName(self):
return 'function'
@classmethod
def parse(cls, tokens):
method = tokens[0]
args = tokens[2:-1]
return Function(method, args)
def __repr__(self):
return "func:{}({})".format(self.func, self.tokens)
class WindowFunction(Function):
def __init__(self, func, tokens, func_args, partition_args, order_args, window_args):
self.func = func
self.tokens = tokens
self.func_args = func_args
self.partition_args = partition_args
self.order_args = order_args
self.window_args = window_args
def getName(self):
return 'window function'
@classmethod
def parse(cls, tokens):
return WindowFunction(
tokens.analytic_function_name,
tokens,
tokens.function_args,
tokens.partition_expression_list,
tokens.ordering_term,
tokens.window_specification
)
def __repr__(self):
return "window:{}({})over({}, {}, {})".format(self.func, self.func_args, self.partition_args, self.order_args, self.window_args)
class CaseStatement(SemanticToken):
def __init__(self, tokens, whens, _else):
self.tokens = tokens
self.whens = whens
self._else = _else
def getName(self):
return 'case'
@classmethod
def parse_whens(self, tokens):
whens = []
while len(tokens) > 0:
_, when, _, then, *tokens = tokens
whens.append({"when": when, "then": then})
return whens
@classmethod
def parse(cls, tokens):
whens = tokens[1]
_else = tokens[3]
return CaseStatement(
tokens,
cls.parse_whens(whens),
_else
)
def __repr__(self):
return "<case statement ({}, {})>".format(len(self.whens), self._else)
expr_term = (
(analytic_function)("analytic_function").setParseAction(WindowFunction.parse)
| (CAST + LPAR + expr + AS + type_name + RPAR)("cast")
| (SAFE_CAST + LPAR + expr + AS + type_name + RPAR)("safe_cast")
| (Optional(EXISTS) + LPAR + ungrouped_select_stmt + RPAR)("subselect")
| (literal_value)("literal")
| (bind_parameter)("bind_parameter")
| (EXTRACT + LPAR + expr + FROM + expr + RPAR)("extract")
| case_stmt.setParseAction(CaseStatement.parse)
| (datetime_operators + LPAR + expr + COMMA + interval + RPAR)(
"date_operation"
)
#| (bad_datetime_operators + LPAR + expr + COMMA + interval + RPAR)
| string_agg_term("string_agg_term")
| array_literal("array_literal")
| array_generator("array_generator")
| date_array_generator("date_array_generator")
| explicit_struct("explicit_struct")
| function_call("function_call").setParseAction(Function.parse)
| qualified_column_name("column").setParseAction(lambda x: ".".join([str(i) for i in x[0]]))
).setParseAction(debug) + Optional(LBRACKET + (OFFSET | ORDINAL) + LPAR + expr + RPAR + RBRACKET)(
"offset_ordinal"
)
struct_term = (LPAR + delimitedList(expr_term) + RPAR)
KNOWN_OPS = [
(BETWEEN, AND),
Literal("||").setName("concat"),
Literal("*").setName("mul"),
Literal("/").setName("div"),
Literal("+").setName("add"),
Literal("-").setName("sub"),
Literal("<>").setName("neq"),
Literal(">").setName("gt"),
Literal("<").setName("lt"),
Literal(">=").setName("gte"),
Literal("<=").setName("lte"),
Literal("=").setName("eq"),
Literal("==").setName("eq"),
Literal("!=").setName("neq"),
IN.setName("in"),
IS.setName("is"),
LIKE.setName("like"),
OR.setName("or"),
AND.setName("and"),
NOT.setName('not')
]
class Operator(SemanticToken):
def __init__(self, op, assoc, name, tokens):
self.op = op
self.assoc = assoc
self.name = name
self.tokens = tokens
def getName(self):
return 'operator'
@classmethod
def parse(cls, tokens):
# ARRANGE INTO {op: params} FORMAT
toks = tokens[0]
if toks[1] in KNOWN_OPS:
op = KNOWN_OPS[KNOWN_OPS.index(toks[1])]
if toks.subselect:
import ipdb; ipdb.set_trace()
return Operator(op, 'binary', op.name, [toks[0], toks[2:]])
else:
import ipdb; ipdb.set_trace()
return tokens
@classmethod
def parse_unary(cls, tokens):
toks = tokens[0]
if toks[0] in KNOWN_OPS:
op = KNOWN_OPS[KNOWN_OPS.index(toks[0])]
else:
import ipdb; ipdb.set_trace()
return Operator(op, 'unary', op.name, [toks[1:]])
@classmethod
def parse_ternary(cls, tokens):
import ipdb; ipdb.set_trace()
def __repr__(self):
return "<operator({}, {}, {})>".format(self.op, self.assoc, self.tokens)
UNARY, BINARY, TERNARY = 1, 2, 3
expr << infixNotation(
(expr_term | struct_term),
[
(oneOf("- + ~") | NOT, UNARY, opAssoc.RIGHT, Operator.parse_unary),
(ISNULL | NOTNULL | NOT + NULL, UNARY, opAssoc.LEFT, Operator.parse_unary),
("||", BINARY, opAssoc.LEFT, Operator.parse),
(oneOf("* / %"), BINARY, opAssoc.LEFT, Operator.parse),
(oneOf("+ -"), BINARY, opAssoc.LEFT, Operator.parse),
(oneOf("<< >> & |"), BINARY, opAssoc.LEFT, Operator.parse),
(oneOf("= > < >= <= <> != !< !>"), BINARY, opAssoc.LEFT, Operator.parse),
(
IS + Optional(NOT)
| Optional(NOT) + IN
| Optional(NOT) + LIKE
| GLOB
| MATCH
| REGEXP,
BINARY,
opAssoc.LEFT,
Operator.parse
),
((BETWEEN, AND), TERNARY, opAssoc.LEFT, Operator.parse_ternary),
(
Optional(NOT)
+ IN
+ LPAR
+ Group(ungrouped_select_stmt | delimitedList(expr))
+ RPAR,
UNARY,
opAssoc.LEFT,
Operator.parse_unary
),
(AND, BINARY, opAssoc.LEFT, Operator.parse),
(OR, BINARY, opAssoc.LEFT, Operator.parse),
],
lpar=Literal('('),
rpar=Literal(')'),
)
quoted_expr = (
expr
^ Suppress('"') + expr + Suppress('"')
^ Suppress("'") + expr + Suppress("'")
^ Suppress("`") + expr + Suppress("`")
)("quoted_expr")
compound_operator = (
UNION + Optional(ALL | DISTINCT)
| INTERSECT + DISTINCT
| EXCEPT + DISTINCT
| INTERSECT
| EXCEPT
)("compound_operator")
join_constraint = Group(
Optional(
ON + expr
| USING + LPAR + Group(delimitedList(qualified_column_name)) + RPAR
)
)("join_constraint")
join_op = (
COMMA
| Group(
Optional(NATURAL)
+ Optional(
INNER
| CROSS
| LEFT + OUTER
| LEFT
| RIGHT + OUTER
| RIGHT
| FULL + OUTER
| OUTER
| FULL
)
+ JOIN
)
)("join_op")
join_source = Forward()
# We support three kinds of table identifiers.
#
# First, dot delimited info like project.dataset.table, where
# each component follows the rules described in the BigQuery
# docs, namely:
# Contain letters (upper or lower case), numbers, and underscores
#
# Second, a dot delimited quoted string. Since it's quoted, we'll be
# liberal w.r.t. what characters we allow. E.g.:
# `project.dataset.name-with-dashes`
#
# Third, a series of quoted strings, delimited by dots, e.g.:
# `project`.`dataset`.`name-with-dashes`
#
# We won't attempt to support combinations, like:
# project.dataset.`name-with-dashes`
# `project`.`dataset.name-with-dashes`
def record_table_identifier(t):
identifier_list = t.asList()
padded_list = [None] * (3 - len(identifier_list)) + identifier_list
cls._table_identifiers.add(tuple(padded_list))
standard_table_part = ~keyword + Word(alphanums + "_")
standard_table_identifier = (
Optional(standard_table_part("project") + Suppress("."))
+ Optional(standard_table_part("dataset") + Suppress("."))
+ standard_table_part("table")
).setParseAction(lambda t: record_table_identifier(t))
quoted_project_part = (
Suppress('"') + CharsNotIn('"') + Suppress('"')
| Suppress("'") + CharsNotIn("'") + Suppress("'")
| Suppress("`") + CharsNotIn("`") + Suppress("`")
)
quoted_table_part = (
Suppress('"') + CharsNotIn('".') + Suppress('"')
| Suppress("'") + CharsNotIn("'.") + Suppress("'")
| Suppress("`") + CharsNotIn("`.") + Suppress("`")
)
quoted_table_parts_identifier = (
Optional(quoted_project_part("project") + Suppress("."))
+ Optional(quoted_table_part("dataset") + Suppress("."))
+ quoted_table_part("table")
).setParseAction(lambda t: record_table_identifier(t))
def record_quoted_table_identifier(t):
identifier_list = t.asList()[0].split(".")
first = ".".join(identifier_list[0:-2]) or None
second = identifier_list[-2]
third = identifier_list[-1]
identifier_list = [first, second, third]
padded_list = [None] * (3 - len(identifier_list)) + identifier_list
cls._table_identifiers.add(tuple(padded_list))
quotable_table_parts_identifier = (
Suppress('"') + CharsNotIn('"') + Suppress('"')
| Suppress("'") + CharsNotIn("'") + Suppress("'")
| Suppress("`") + CharsNotIn("`") + Suppress("`")
).setParseAction(lambda t: record_quoted_table_identifier(t))
table_identifier = (
standard_table_identifier
| quoted_table_parts_identifier
| quotable_table_parts_identifier
)
def record_ref(t):
lol = [t.op] + t.ref_target.asList()
cls._with_aliases.add(tuple(lol))
cls._table_identifiers.add(tuple(lol))
ref_target = identifier.copy()
single_source = (
# ref + source statements
(
(
Suppress('{{')
+ (CaselessKeyword('ref') | CaselessKeyword("source"))("op")
+ LPAR
+ delimitedList(
(Suppress("'") | Suppress('"'))
+ ref_target
+ (Suppress("'") | Suppress('"'))
)("ref_target")
+ RPAR
+ Suppress("}}")
).setParseAction(record_ref)
| table_identifier
)
+ Optional(Optional(AS) + table_alias("table_alias*"))
+ Optional(FOR + SYSTEMTIME + AS + OF + string_literal)
+ Optional(INDEXED + BY + index_name("name") | NOT + INDEXED)("index")
| (
LPAR
+ ungrouped_select_stmt
+ RPAR
+ Optional(Optional(AS) + table_alias)
)('subquery')
| (LPAR + join_source + RPAR)
| (UNNEST + LPAR + expr + RPAR) + Optional(Optional(AS) + column_alias)
)
join_source << (
Group(single_source + OneOrMore(Group(join_op + single_source + join_constraint)('joins*')))
| single_source
)('sources*')
over_partition = (PARTITION + BY + delimitedList(partition_expression_list))(
"over_partition"
)
over_order = ORDER + BY + delimitedList(ordering_term)
over_unsigned_value_specification = expr
over_window_frame_preceding = (
UNBOUNDED + PRECEDING
| over_unsigned_value_specification + PRECEDING
| CURRENT + ROW
)
over_window_frame_following = (
UNBOUNDED + FOLLOWING
| over_unsigned_value_specification + FOLLOWING
| CURRENT + ROW
)
over_window_frame_bound = (
over_window_frame_preceding | over_window_frame_following
)
over_window_frame_between = (
BETWEEN + over_window_frame_bound + AND + over_window_frame_bound
)
over_window_frame_extent = (
over_window_frame_preceding | over_window_frame_between
)
over_row_or_range = (ROWS | RANGE) + over_window_frame_extent
over = (
OVER
+ LPAR
+ Optional(over_partition)
+ Optional(over_order)
+ Optional(over_row_or_range)
+ RPAR
)("over")
result_column = (
Optional(table_name + ".")
+ "*"
+ Optional(
EXCEPT
+ LPAR
+ delimitedList(column_name)
+ RPAR
) | Group(quoted_expr + Optional(over) + Optional(Optional(AS) + column_alias('alias')))
)
window_select_clause = (
WINDOW + identifier + AS + LPAR + window_specification + RPAR
)
select_core = (
SELECT
+ Optional(DISTINCT | ALL)
+ Group(delimitedList(result_column))("columns")
+ Optional(FROM - join_source("from*"))
+ Optional(WHERE + expr('where'))
+ Optional(
GROUP + BY + Group(delimitedList(grouping_term))("group_by_terms")
)
+ Optional(HAVING + expr("having_expr"))
+ Optional(