-
Notifications
You must be signed in to change notification settings - Fork 606
/
Copy pathsql_expression.cpp
2307 lines (2131 loc) · 98 KB
/
sql_expression.cpp
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
#include "sql_expression.h"
#include "sql_call_expr.h"
#include "sql_select.h"
#include "sql_values.h"
#include <ydb/library/yql/parser/proto_ast/gen/v1/SQLv1Lexer.h>
#include <ydb/library/yql/parser/proto_ast/gen/v1_antlr4/SQLv1Antlr4Lexer.h>
#include <ydb/library/yql/utils/utf8.h>
#include <util/charset/wide.h>
#include <util/string/ascii.h>
#include <util/string/hex.h>
namespace NSQLTranslationV1 {
using NALPDefault::SQLv1LexerTokens;
using NALPDefaultAntlr4::SQLv1Antlr4Lexer;
using namespace NSQLv1Generated;
TNodePtr TSqlExpression::Build(const TRule_expr& node) {
// expr:
// or_subexpr (OR or_subexpr)*
// | type_name_composite
switch (node.Alt_case()) {
case TRule_expr::kAltExpr1: {
auto getNode = [](const TRule_expr_TAlt1_TBlock2& b) -> const TRule_or_subexpr& { return b.GetRule_or_subexpr2(); };
return BinOper("Or", node.GetAlt_expr1().GetRule_or_subexpr1(), getNode,
node.GetAlt_expr1().GetBlock2().begin(), node.GetAlt_expr1().GetBlock2().end(), {});
}
case TRule_expr::kAltExpr2: {
return TypeNode(node.GetAlt_expr2().GetRule_type_name_composite1());
}
case TRule_expr::ALT_NOT_SET:
Y_ABORT("You should change implementation according to grammar changes");
}
}
TNodePtr TSqlExpression::SubExpr(const TRule_mul_subexpr& node, const TTrailingQuestions& tail) {
// mul_subexpr: con_subexpr (DOUBLE_PIPE con_subexpr)*;
auto getNode = [](const TRule_mul_subexpr::TBlock2& b) -> const TRule_con_subexpr& { return b.GetRule_con_subexpr2(); };
return BinOper("Concat", node.GetRule_con_subexpr1(), getNode, node.GetBlock2().begin(), node.GetBlock2().end(), tail);
}
TNodePtr TSqlExpression::SubExpr(const TRule_add_subexpr& node, const TTrailingQuestions& tail) {
// add_subexpr: mul_subexpr ((ASTERISK | SLASH | PERCENT) mul_subexpr)*;
auto getNode = [](const TRule_add_subexpr::TBlock2& b) -> const TRule_mul_subexpr& { return b.GetRule_mul_subexpr2(); };
return BinOpList(node.GetRule_mul_subexpr1(), getNode, node.GetBlock2().begin(), node.GetBlock2().end(), tail);
}
TNodePtr TSqlExpression::SubExpr(const TRule_bit_subexpr& node, const TTrailingQuestions& tail) {
// bit_subexpr: add_subexpr ((PLUS | MINUS) add_subexpr)*;
auto getNode = [](const TRule_bit_subexpr::TBlock2& b) -> const TRule_add_subexpr& { return b.GetRule_add_subexpr2(); };
return BinOpList(node.GetRule_add_subexpr1(), getNode, node.GetBlock2().begin(), node.GetBlock2().end(), tail);
}
TNodePtr TSqlExpression::SubExpr(const TRule_neq_subexpr& node, const TTrailingQuestions& tailExternal) {
//neq_subexpr: bit_subexpr ((SHIFT_LEFT | shift_right | ROT_LEFT | rot_right | AMPERSAND | PIPE | CARET) bit_subexpr)*
// // trailing QUESTIONS are used in optional simple types (String?) and optional lambda args: ($x, $y?) -> ($x)
// ((double_question neq_subexpr) => double_question neq_subexpr | QUESTION+)?;
YQL_ENSURE(tailExternal.Count == 0);
MaybeUnnamedSmartParenOnTop = MaybeUnnamedSmartParenOnTop && !node.HasBlock3();
TTrailingQuestions tail;
if (node.HasBlock3() && node.GetBlock3().Alt_case() == TRule_neq_subexpr::TBlock3::kAlt2) {
auto& questions = node.GetBlock3().GetAlt2();
tail.Count = questions.GetBlock1().size();
tail.Pos = Ctx.TokenPosition(questions.GetBlock1().begin()->GetToken1());
YQL_ENSURE(tail.Count > 0);
}
auto getNode = [](const TRule_neq_subexpr::TBlock2& b) -> const TRule_bit_subexpr& { return b.GetRule_bit_subexpr2(); };
auto result = BinOpList(node.GetRule_bit_subexpr1(), getNode, node.GetBlock2().begin(), node.GetBlock2().end(), tail);
if (!result) {
return {};
}
if (node.HasBlock3()) {
auto& block = node.GetBlock3();
if (block.Alt_case() == TRule_neq_subexpr::TBlock3::kAlt1) {
TSqlExpression altExpr(Ctx, Mode);
auto altResult = SubExpr(block.GetAlt1().GetRule_neq_subexpr2(), {});
if (!altResult) {
return {};
}
const TVector<TNodePtr> args({result, altResult});
Token(block.GetAlt1().GetRule_double_question1().GetToken1());
result = BuildBuiltinFunc(Ctx, Ctx.Pos(), "Coalesce", args);
}
}
return result;
}
TNodePtr TSqlExpression::SubExpr(const TRule_eq_subexpr& node, const TTrailingQuestions& tail) {
// eq_subexpr: neq_subexpr ((LESS | LESS_OR_EQ | GREATER | GREATER_OR_EQ) neq_subexpr)*;
auto getNode = [](const TRule_eq_subexpr::TBlock2& b) -> const TRule_neq_subexpr& { return b.GetRule_neq_subexpr2(); };
return BinOpList(node.GetRule_neq_subexpr1(), getNode, node.GetBlock2().begin(), node.GetBlock2().end(), tail);
}
TNodePtr TSqlExpression::SubExpr(const TRule_or_subexpr& node, const TTrailingQuestions& tail) {
// or_subexpr: and_subexpr (AND and_subexpr)*;
auto getNode = [](const TRule_or_subexpr::TBlock2& b) -> const TRule_and_subexpr& { return b.GetRule_and_subexpr2(); };
return BinOper("And", node.GetRule_and_subexpr1(), getNode, node.GetBlock2().begin(), node.GetBlock2().end(), tail);
}
TNodePtr TSqlExpression::SubExpr(const TRule_and_subexpr& node, const TTrailingQuestions& tail) {
// and_subexpr: xor_subexpr (XOR xor_subexpr)*;
auto getNode = [](const TRule_and_subexpr::TBlock2& b) -> const TRule_xor_subexpr& { return b.GetRule_xor_subexpr2(); };
return BinOper("Xor", node.GetRule_xor_subexpr1(), getNode, node.GetBlock2().begin(), node.GetBlock2().end(), tail);
}
bool ChangefeedSettingsEntry(const TRule_changefeed_settings_entry& node, TSqlExpression& ctx, TChangefeedSettings& settings, bool alter) {
const auto id = IdEx(node.GetRule_an_id1(), ctx);
if (alter) {
// currently we don't support alter settings
ctx.Error() << to_upper(id.Name) << " alter is not supported";
return false;
}
const auto& setting = node.GetRule_changefeed_setting_value3();
auto exprNode = ctx.Build(setting.GetRule_expr1());
if (!exprNode) {
ctx.Context().Error(id.Pos) << "Invalid changefeed setting: " << id.Name;
return false;
}
if (to_lower(id.Name) == "sink_type") {
if (!exprNode->IsLiteral() || exprNode->GetLiteralType() != "String") {
ctx.Context().Error() << "Literal of String type is expected for " << id.Name;
return false;
}
const auto value = exprNode->GetLiteralValue();
if (to_lower(value) == "local") {
settings.SinkSettings = TChangefeedSettings::TLocalSinkSettings();
} else {
ctx.Context().Error() << "Unknown changefeed sink type: " << value;
return false;
}
} else if (to_lower(id.Name) == "mode") {
if (!exprNode->IsLiteral() || exprNode->GetLiteralType() != "String") {
ctx.Context().Error() << "Literal of String type is expected for " << id.Name;
return false;
}
settings.Mode = exprNode;
} else if (to_lower(id.Name) == "format") {
if (!exprNode->IsLiteral() || exprNode->GetLiteralType() != "String") {
ctx.Context().Error() << "Literal of String type is expected for " << id.Name;
return false;
}
settings.Format = exprNode;
} else if (to_lower(id.Name) == "initial_scan") {
if (!exprNode->IsLiteral() || exprNode->GetLiteralType() != "Bool") {
ctx.Context().Error() << "Literal of Bool type is expected for " << id.Name;
return false;
}
settings.InitialScan = exprNode;
} else if (to_lower(id.Name) == "virtual_timestamps") {
if (!exprNode->IsLiteral() || exprNode->GetLiteralType() != "Bool") {
ctx.Context().Error() << "Literal of Bool type is expected for " << id.Name;
return false;
}
settings.VirtualTimestamps = exprNode;
} else if (to_lower(id.Name) == "resolved_timestamps") {
if (exprNode->GetOpName() != "Interval") {
ctx.Context().Error() << "Literal of Interval type is expected for " << id.Name;
return false;
}
settings.ResolvedTimestamps = exprNode;
} else if (to_lower(id.Name) == "retention_period") {
if (exprNode->GetOpName() != "Interval") {
ctx.Context().Error() << "Literal of Interval type is expected for " << id.Name;
return false;
}
settings.RetentionPeriod = exprNode;
} else if (to_lower(id.Name) == "topic_auto_partitioning") {
auto v = to_lower(exprNode->GetLiteralValue());
if (v != "enabled" && v != "disabled") {
ctx.Context().Error() << "Literal of Interval type is expected for " << id.Name;
}
settings.TopicAutoPartitioning = exprNode;
} else if (to_lower(id.Name) == "topic_max_active_partitions") {
if (!exprNode->IsIntegerLiteral()) {
ctx.Context().Error() << "Literal of integer type is expected for " << id.Name;
return false;
}
settings.TopicMaxActivePartitions = exprNode;
} else if (to_lower(id.Name) == "topic_min_active_partitions") {
if (!exprNode->IsIntegerLiteral()) {
ctx.Context().Error() << "Literal of integer type is expected for " << id.Name;
return false;
}
settings.TopicPartitions = exprNode;
} else if (to_lower(id.Name) == "aws_region") {
if (!exprNode->IsLiteral() || exprNode->GetLiteralType() != "String") {
ctx.Context().Error() << "Literal of String type is expected for " << id.Name;
return false;
}
settings.AwsRegion = exprNode;
} else {
ctx.Context().Error(id.Pos) << "Unknown changefeed setting: " << id.Name;
return false;
}
return true;
}
bool ChangefeedSettings(const TRule_changefeed_settings& node, TSqlExpression& ctx, TChangefeedSettings& settings, bool alter) {
if (!ChangefeedSettingsEntry(node.GetRule_changefeed_settings_entry1(), ctx, settings, alter)) {
return false;
}
for (auto& block : node.GetBlock2()) {
if (!ChangefeedSettingsEntry(block.GetRule_changefeed_settings_entry2(), ctx, settings, alter)) {
return false;
}
}
return true;
}
bool CreateChangefeed(const TRule_changefeed& node, TSqlExpression& ctx, TVector<TChangefeedDescription>& changefeeds) {
changefeeds.emplace_back(IdEx(node.GetRule_an_id2(), ctx));
if (!ChangefeedSettings(node.GetRule_changefeed_settings5(), ctx, changefeeds.back().Settings, false)) {
return false;
}
return true;
}
namespace {
bool WithoutAlpha(const std::string_view &literal) {
return literal.cend() == std::find_if(literal.cbegin(), literal.cend(), [](char c) { return std::isalpha(c) || (c & '\x80'); });
}
}
bool Expr(TSqlExpression& sqlExpr, TVector<TNodePtr>& exprNodes, const TRule_expr& node) {
TNodePtr exprNode = sqlExpr.Build(node);
if (!exprNode) {
return false;
}
exprNodes.push_back(exprNode);
return true;
}
bool ExprList(TSqlExpression& sqlExpr, TVector<TNodePtr>& exprNodes, const TRule_expr_list& node) {
if (!Expr(sqlExpr, exprNodes, node.GetRule_expr1())) {
return false;
}
for (auto b: node.GetBlock2()) {
sqlExpr.Token(b.GetToken1());
if (!Expr(sqlExpr, exprNodes, b.GetRule_expr2())) {
return false;
}
}
return true;
}
bool ParseNumbers(TContext& ctx, const TString& strOrig, ui64& value, TString& suffix) {
const auto str = to_lower(strOrig);
const auto strLen = str.size();
ui64 base = 10;
if (strLen > 2 && str[0] == '0') {
const auto formatChar = str[1];
if (formatChar == 'x') {
base = 16;
} else if (formatChar == 'o') {
base = 8;
} else if (formatChar == 'b') {
base = 2;
}
}
if (strLen > 1) {
auto iter = str.cend() - 1;
if (*iter == 'l' || *iter == 's' || *iter == 't' || *iter == 's' || *iter == 'i' || *iter == 'b' || *iter == 'n') {
--iter;
}
if (*iter == 'u' || *iter == 'p') {
--iter;
}
suffix = TString(++iter, str.cend());
}
value = 0;
const TString digString(str.begin() + (base == 10 ? 0 : 2), str.end() - suffix.size());
for (const char& cur: digString) {
const ui64 curDigit = Char2DigitTable[static_cast<int>(cur)];
if (curDigit >= base) {
ctx.Error(ctx.Pos()) << "Failed to parse number from string: " << strOrig << ", char: '" << cur <<
"' is out of base: " << base;
return false;
}
ui64 curValue = value;
value *= base;
bool overflow = ((value / base) != curValue);
if (!overflow) {
curValue = value;
value += curDigit;
overflow = value < curValue;
}
if (overflow) {
ctx.Error(ctx.Pos()) << "Failed to parse number from string: " << strOrig << ", number limit overflow";
return false;
}
}
return true;
}
TNodePtr LiteralNumber(TContext& ctx, const TRule_integer& node) {
const TString intergerString = ctx.Token(node.GetToken1());
if (to_lower(intergerString).EndsWith("pn")) {
// TODO: add validation
return new TLiteralNode(ctx.Pos(), "PgNumeric", intergerString.substr(0, intergerString.size() - 2));
}
ui64 value;
TString suffix;
if (!ParseNumbers(ctx, intergerString, value, suffix)) {
return {};
}
const bool noSpaceForInt32 = value >> 31;
const bool noSpaceForInt64 = value >> 63;
if (suffix == "") {
bool implicitType = true;
if (noSpaceForInt64) {
return new TLiteralNumberNode<ui64>(ctx.Pos(), "Uint64", ToString(value), implicitType);
} else if (noSpaceForInt32) {
return new TLiteralNumberNode<i64>(ctx.Pos(), "Int64", ToString(value), implicitType);
}
return new TLiteralNumberNode<i32>(ctx.Pos(), "Int32", ToString(value), implicitType);
} else if (suffix == "p") {
bool implicitType = true;
if (noSpaceForInt64) {
ctx.Error(ctx.Pos()) << "Failed to parse number from string: " << intergerString << ", 64 bit signed integer overflow";
return {};
} else if (noSpaceForInt32) {
return new TLiteralNumberNode<i64>(ctx.Pos(), "PgInt8", ToString(value), implicitType);
}
return new TLiteralNumberNode<i32>(ctx.Pos(), "PgInt4", ToString(value), implicitType);
} else if (suffix == "u") {
return new TLiteralNumberNode<ui32>(ctx.Pos(), "Uint32", ToString(value));
} else if (suffix == "ul") {
return new TLiteralNumberNode<ui64>(ctx.Pos(), "Uint64", ToString(value));
} else if (suffix == "ut") {
return new TLiteralNumberNode<ui8>(ctx.Pos(), "Uint8", ToString(value));
} else if (suffix == "t") {
return new TLiteralNumberNode<i8>(ctx.Pos(), "Int8", ToString(value));
} else if (suffix == "l") {
return new TLiteralNumberNode<i64>(ctx.Pos(), "Int64", ToString(value));
} else if (suffix == "us") {
return new TLiteralNumberNode<ui16>(ctx.Pos(), "Uint16", ToString(value));
} else if (suffix == "s") {
return new TLiteralNumberNode<i16>(ctx.Pos(), "Int16", ToString(value));
} else if (suffix == "ps") {
return new TLiteralNumberNode<i16>(ctx.Pos(), "PgInt2", ToString(value));
} else if (suffix == "pi") {
return new TLiteralNumberNode<i32>(ctx.Pos(), "PgInt4", ToString(value));
} else if (suffix == "pb") {
return new TLiteralNumberNode<i64>(ctx.Pos(), "PgInt8", ToString(value));
} else {
ctx.Error(ctx.Pos()) << "Failed to parse number from string: " << intergerString << ", invalid suffix: " << suffix;
return {};
}
}
TNodePtr LiteralReal(TContext& ctx, const TRule_real& node) {
const TString value(ctx.Token(node.GetToken1()));
YQL_ENSURE(!value.empty());
auto lower = to_lower(value);
if (lower.EndsWith("f")) {
return new TLiteralNumberNode<float>(ctx.Pos(), "Float", value.substr(0, value.size()-1));
} else if (lower.EndsWith("p")) {
return new TLiteralNumberNode<float>(ctx.Pos(), "PgFloat8", value.substr(0, value.size()-1));
} else if (lower.EndsWith("pf4")) {
return new TLiteralNumberNode<float>(ctx.Pos(), "PgFloat4", value.substr(0, value.size()-3));
} else if (lower.EndsWith("pf8")) {
return new TLiteralNumberNode<float>(ctx.Pos(), "PgFloat8", value.substr(0, value.size()-3));
} else if (lower.EndsWith("pn")) {
return new TLiteralNode(ctx.Pos(), "PgNumeric", value.substr(0, value.size()-2));
} else {
return new TLiteralNumberNode<double>(ctx.Pos(), "Double", value);
}
}
TMaybe<TExprOrIdent> TSqlExpression::LiteralExpr(const TRule_literal_value& node) {
TExprOrIdent result;
switch (node.Alt_case()) {
case TRule_literal_value::kAltLiteralValue1: {
result.Expr = LiteralNumber(Ctx, node.GetAlt_literal_value1().GetRule_integer1());
break;
}
case TRule_literal_value::kAltLiteralValue2: {
result.Expr = LiteralReal(Ctx, node.GetAlt_literal_value2().GetRule_real1());
break;
}
case TRule_literal_value::kAltLiteralValue3: {
const TString value(Token(node.GetAlt_literal_value3().GetToken1()));
return BuildLiteralTypedSmartStringOrId(Ctx, value);
}
case TRule_literal_value::kAltLiteralValue5: {
Token(node.GetAlt_literal_value5().GetToken1());
result.Expr = BuildLiteralNull(Ctx.Pos());
break;
}
case TRule_literal_value::kAltLiteralValue9: {
const TString value(to_lower(Token(node.GetAlt_literal_value9().GetRule_bool_value1().GetToken1())));
result.Expr = BuildLiteralBool(Ctx.Pos(), FromString<bool>(value));
break;
}
case TRule_literal_value::kAltLiteralValue10: {
result.Expr = BuildEmptyAction(Ctx.Pos());
break;
}
case TRule_literal_value::kAltLiteralValue4:
case TRule_literal_value::kAltLiteralValue6:
case TRule_literal_value::kAltLiteralValue7:
case TRule_literal_value::kAltLiteralValue8:
case TRule_literal_value::ALT_NOT_SET:
AltNotImplemented("literal_value", node);
}
if (!result.Expr) {
return {};
}
return result;
}
template<typename TUnarySubExprType>
TNodePtr TSqlExpression::UnaryExpr(const TUnarySubExprType& node, const TTrailingQuestions& tail) {
if constexpr (std::is_same_v<TUnarySubExprType, TRule_unary_subexpr>) {
if (node.Alt_case() == TRule_unary_subexpr::kAltUnarySubexpr1) {
return UnaryCasualExpr(node.GetAlt_unary_subexpr1().GetRule_unary_casual_subexpr1(), tail);
} else if (tail.Count) {
UnexpectedQuestionToken(tail);
return {};
} else {
MaybeUnnamedSmartParenOnTop = false;
return JsonApiExpr(node.GetAlt_unary_subexpr2().GetRule_json_api_expr1());
}
} else {
MaybeUnnamedSmartParenOnTop = false;
if (node.Alt_case() == TRule_in_unary_subexpr::kAltInUnarySubexpr1) {
return UnaryCasualExpr(node.GetAlt_in_unary_subexpr1().GetRule_in_unary_casual_subexpr1(), tail);
} else if (tail.Count) {
UnexpectedQuestionToken(tail);
return {};
} else {
return JsonApiExpr(node.GetAlt_in_unary_subexpr2().GetRule_json_api_expr1());
}
}
}
TNodePtr TSqlExpression::JsonPathSpecification(const TRule_jsonpath_spec& node) {
/*
jsonpath_spec: STRING_VALUE;
*/
TString value = Token(node.GetToken1());
TPosition pos = Ctx.Pos();
auto parsed = StringContent(Ctx, pos, value);
if (!parsed) {
return nullptr;
}
return new TCallNodeImpl(pos, "Utf8", {BuildQuotedAtom(pos, parsed->Content, parsed->Flags)});
}
TNodePtr TSqlExpression::JsonReturningTypeRule(const TRule_type_name_simple& node) {
/*
(RETURNING type_name_simple)?
*/
return TypeSimple(node, /* onlyDataAllowed */ true);
}
TNodePtr TSqlExpression::JsonInputArg(const TRule_json_common_args& node) {
/*
json_common_args: expr COMMA jsonpath_spec (PASSING json_variables)?;
*/
TNodePtr jsonExpr = Build(node.GetRule_expr1());
if (!jsonExpr || jsonExpr->IsNull()) {
jsonExpr = new TCallNodeImpl(Ctx.Pos(), "Nothing", {
new TCallNodeImpl(Ctx.Pos(), "OptionalType", {BuildDataType(Ctx.Pos(), "Json")})
});
}
return jsonExpr;
}
void TSqlExpression::AddJsonVariable(const TRule_json_variable& node, TVector<TNodePtr>& children) {
/*
json_variable: expr AS json_variable_name;
*/
TNodePtr expr;
TString rawName;
TPosition namePos = Ctx.Pos();
ui32 nameFlags = 0;
expr = Build(node.GetRule_expr1());
const auto& nameRule = node.GetRule_json_variable_name3();
switch (nameRule.GetAltCase()) {
case TRule_json_variable_name::kAltJsonVariableName1:
rawName = Id(nameRule.GetAlt_json_variable_name1().GetRule_id_expr1(), *this);
nameFlags = TNodeFlags::ArbitraryContent;
break;
case TRule_json_variable_name::kAltJsonVariableName2: {
const auto& token = nameRule.GetAlt_json_variable_name2().GetToken1();
namePos = GetPos(token);
auto parsed = StringContentOrIdContent(Ctx, namePos, token.GetValue());
if (!parsed) {
return;
}
rawName = parsed->Content;
nameFlags = parsed->Flags;
break;
}
case TRule_json_variable_name::ALT_NOT_SET:
Y_ABORT("You should change implementation according to grammar changes");
}
TNodePtr nameExpr = BuildQuotedAtom(namePos, rawName, nameFlags);
children.push_back(BuildTuple(namePos, {nameExpr, expr}));
}
void TSqlExpression::AddJsonVariables(const TRule_json_variables& node, TVector<TNodePtr>& children) {
/*
json_variables: json_variable (COMMA json_variable)*;
*/
AddJsonVariable(node.GetRule_json_variable1(), children);
for (size_t i = 0; i < node.Block2Size(); i++) {
AddJsonVariable(node.GetBlock2(i).GetRule_json_variable2(), children);
}
}
TNodePtr TSqlExpression::JsonVariables(const TRule_json_common_args& node) {
/*
json_common_args: expr COMMA jsonpath_spec (PASSING json_variables)?;
*/
TVector<TNodePtr> variables;
TPosition pos = Ctx.Pos();
if (node.HasBlock4()) {
const auto& block = node.GetBlock4();
pos = GetPos(block.GetToken1());
AddJsonVariables(block.GetRule_json_variables2(), variables);
}
return new TCallNodeImpl(pos, "JsonVariables", variables);
}
void TSqlExpression::AddJsonCommonArgs(const TRule_json_common_args& node, TVector<TNodePtr>& children) {
/*
json_common_args: expr COMMA jsonpath_spec (PASSING json_variables)?;
*/
TNodePtr jsonExpr = JsonInputArg(node);
TNodePtr jsonPath = JsonPathSpecification(node.GetRule_jsonpath_spec3());
TNodePtr variables = JsonVariables(node);
children.push_back(jsonExpr);
children.push_back(jsonPath);
children.push_back(variables);
}
TNodePtr TSqlExpression::JsonValueCaseHandler(const TRule_json_case_handler& node, EJsonValueHandlerMode& mode) {
/*
json_case_handler: ERROR | NULL | (DEFAULT expr);
*/
switch (node.GetAltCase()) {
case TRule_json_case_handler::kAltJsonCaseHandler1: {
const auto pos = GetPos(node.GetAlt_json_case_handler1().GetToken1());
mode = EJsonValueHandlerMode::Error;
return new TCallNodeImpl(pos, "Null", {});
}
case TRule_json_case_handler::kAltJsonCaseHandler2: {
const auto pos = GetPos(node.GetAlt_json_case_handler2().GetToken1());
mode = EJsonValueHandlerMode::DefaultValue;
return new TCallNodeImpl(pos, "Null", {});
}
case TRule_json_case_handler::kAltJsonCaseHandler3:
mode = EJsonValueHandlerMode::DefaultValue;
return Build(node.GetAlt_json_case_handler3().GetRule_expr2());
case TRule_json_case_handler::ALT_NOT_SET:
Y_ABORT("You should change implementation according to grammar changes");
}
}
void TSqlExpression::AddJsonValueCaseHandlers(const TRule_json_value& node, TVector<TNodePtr>& children) {
/*
json_case_handler*
*/
if (node.Block5Size() > 2) {
Ctx.Error() << "Only 1 ON EMPTY and/or 1 ON ERROR clause is expected";
Ctx.IncrementMonCounter("sql_errors", "JsonValueTooManyHandleClauses");
return;
}
TNodePtr onEmpty;
EJsonValueHandlerMode onEmptyMode = EJsonValueHandlerMode::DefaultValue;
TNodePtr onError;
EJsonValueHandlerMode onErrorMode = EJsonValueHandlerMode::DefaultValue;
for (size_t i = 0; i < node.Block5Size(); i++) {
const auto block = node.GetBlock5(i);
const bool isEmptyClause = to_lower(block.GetToken3().GetValue()) == "empty";
if (isEmptyClause && onEmpty != nullptr) {
Ctx.Error() << "Only 1 ON EMPTY clause is expected";
Ctx.IncrementMonCounter("sql_errors", "JsonValueMultipleOnEmptyClauses");
return;
}
if (!isEmptyClause && onError != nullptr) {
Ctx.Error() << "Only 1 ON ERROR clause is expected";
Ctx.IncrementMonCounter("sql_errors", "JsonValueMultipleOnErrorClauses");
return;
}
if (isEmptyClause && onError != nullptr) {
Ctx.Error() << "ON EMPTY clause must be before ON ERROR clause";
Ctx.IncrementMonCounter("sql_errors", "JsonValueOnEmptyAfterOnError");
return;
}
EJsonValueHandlerMode currentMode;
TNodePtr currentHandler = JsonValueCaseHandler(block.GetRule_json_case_handler1(), currentMode);
if (isEmptyClause) {
onEmpty = currentHandler;
onEmptyMode = currentMode;
} else {
onError = currentHandler;
onErrorMode = currentMode;
}
}
if (onEmpty == nullptr) {
onEmpty = new TCallNodeImpl(Ctx.Pos(), "Null", {});
}
if (onError == nullptr) {
onError = new TCallNodeImpl(Ctx.Pos(), "Null", {});
}
children.push_back(BuildQuotedAtom(Ctx.Pos(), ToString(onEmptyMode), TNodeFlags::Default));
children.push_back(onEmpty);
children.push_back(BuildQuotedAtom(Ctx.Pos(), ToString(onErrorMode), TNodeFlags::Default));
children.push_back(onError);
}
TNodePtr TSqlExpression::JsonValueExpr(const TRule_json_value& node) {
/*
json_value: JSON_VALUE LPAREN
json_common_args
(RETURNING type_name_simple)?
(json_case_handler ON (EMPTY | ERROR))*
RPAREN;
*/
TVector<TNodePtr> children;
AddJsonCommonArgs(node.GetRule_json_common_args3(), children);
AddJsonValueCaseHandlers(node, children);
if (node.HasBlock4()) {
auto returningType = JsonReturningTypeRule(node.GetBlock4().GetRule_type_name_simple2());
if (!returningType) {
return {};
}
children.push_back(returningType);
}
return new TCallNodeImpl(GetPos(node.GetToken1()), "JsonValue", children);
}
void TSqlExpression::AddJsonExistsHandler(const TRule_json_exists& node, TVector<TNodePtr>& children) {
/*
json_exists: JSON_EXISTS LPAREN
json_common_args
json_exists_handler?
RPAREN;
*/
auto buildJustBool = [&](const TPosition& pos, bool value) {
return new TCallNodeImpl(pos, "Just", {BuildLiteralBool(pos, value)});
};
if (!node.HasBlock4()) {
children.push_back(buildJustBool(Ctx.Pos(), false));
return;
}
const auto& handlerRule = node.GetBlock4().GetRule_json_exists_handler1();
const auto& token = handlerRule.GetToken1();
const auto pos = GetPos(token);
const auto mode = to_lower(token.GetValue());
if (mode == "unknown") {
const auto nothingNode = new TCallNodeImpl(pos, "Nothing", {
new TCallNodeImpl(pos, "OptionalType", {BuildDataType(pos, "Bool")})
});
children.push_back(nothingNode);
} else if (mode != "error") {
children.push_back(buildJustBool(pos, FromString<bool>(mode)));
}
}
TNodePtr TSqlExpression::JsonExistsExpr(const TRule_json_exists& node) {
/*
json_exists: JSON_EXISTS LPAREN
json_common_args
json_exists_handler?
RPAREN;
*/
TVector<TNodePtr> children;
AddJsonCommonArgs(node.GetRule_json_common_args3(), children);
AddJsonExistsHandler(node, children);
return new TCallNodeImpl(GetPos(node.GetToken1()), "JsonExists", children);
}
EJsonQueryWrap TSqlExpression::JsonQueryWrapper(const TRule_json_query& node) {
/*
json_query: JSON_QUERY LPAREN
json_common_args
(json_query_wrapper WRAPPER)?
(json_query_handler ON EMPTY)?
(json_query_handler ON ERROR)?
RPAREN;
*/
// default behaviour - no wrapping
if (!node.HasBlock4()) {
return EJsonQueryWrap::NoWrap;
}
// WITHOUT ARRAY? - no wrapping
const auto& wrapperRule = node.GetBlock4().GetRule_json_query_wrapper1();
if (wrapperRule.GetAltCase() == TRule_json_query_wrapper::kAltJsonQueryWrapper1) {
return EJsonQueryWrap::NoWrap;
}
// WITH (CONDITIONAL | UNCONDITIONAL)? ARRAY? - wrapping depends on 2nd token. Default is UNCONDITIONAL
const auto& withWrapperRule = wrapperRule.GetAlt_json_query_wrapper2();
if (!withWrapperRule.HasBlock2()) {
return EJsonQueryWrap::Wrap;
}
const auto& token = withWrapperRule.GetBlock2().GetToken1();
if (to_lower(token.GetValue()) == "conditional") {
return EJsonQueryWrap::ConditionalWrap;
} else {
return EJsonQueryWrap::Wrap;
}
}
EJsonQueryHandler TSqlExpression::JsonQueryHandler(const TRule_json_query_handler& node) {
/*
json_query_handler: ERROR | NULL | (EMPTY ARRAY) | (EMPTY OBJECT);
*/
switch (node.GetAltCase()) {
case TRule_json_query_handler::kAltJsonQueryHandler1:
return EJsonQueryHandler::Error;
case TRule_json_query_handler::kAltJsonQueryHandler2:
return EJsonQueryHandler::Null;
case TRule_json_query_handler::kAltJsonQueryHandler3:
return EJsonQueryHandler::EmptyArray;
case TRule_json_query_handler::kAltJsonQueryHandler4:
return EJsonQueryHandler::EmptyObject;
case TRule_json_query_handler::ALT_NOT_SET:
Y_ABORT("You should change implementation according to grammar changes");
}
}
TNodePtr TSqlExpression::JsonQueryExpr(const TRule_json_query& node) {
/*
json_query: JSON_QUERY LPAREN
json_common_args
(json_query_wrapper WRAPPER)?
(json_query_handler ON EMPTY)?
(json_query_handler ON ERROR)?
RPAREN;
*/
TVector<TNodePtr> children;
AddJsonCommonArgs(node.GetRule_json_common_args3(), children);
auto addChild = [&](TPosition pos, const TString& content) {
children.push_back(BuildQuotedAtom(pos, content, TNodeFlags::Default));
};
const auto wrapMode = JsonQueryWrapper(node);
addChild(Ctx.Pos(), ToString(wrapMode));
auto onEmpty = EJsonQueryHandler::Null;
if (node.HasBlock5()) {
if (wrapMode != EJsonQueryWrap::NoWrap) {
Ctx.Error() << "ON EMPTY is prohibited because WRAPPER clause is specified";
Ctx.IncrementMonCounter("sql_errors", "JsonQueryOnEmptyWithWrapper");
return nullptr;
}
onEmpty = JsonQueryHandler(node.GetBlock5().GetRule_json_query_handler1());
}
addChild(Ctx.Pos(), ToString(onEmpty));
auto onError = EJsonQueryHandler::Null;
if (node.HasBlock6()) {
onError = JsonQueryHandler(node.GetBlock6().GetRule_json_query_handler1());
}
addChild(Ctx.Pos(), ToString(onError));
return new TCallNodeImpl(GetPos(node.GetToken1()), "JsonQuery", children);
}
TNodePtr TSqlExpression::JsonApiExpr(const TRule_json_api_expr& node) {
/*
json_api_expr: json_value | json_exists | json_query;
*/
TPosition pos = Ctx.Pos();
TNodePtr result = nullptr;
switch (node.GetAltCase()) {
case TRule_json_api_expr::kAltJsonApiExpr1: {
const auto& jsonValue = node.GetAlt_json_api_expr1().GetRule_json_value1();
pos = GetPos(jsonValue.GetToken1());
result = JsonValueExpr(jsonValue);
break;
}
case TRule_json_api_expr::kAltJsonApiExpr2: {
const auto& jsonExists = node.GetAlt_json_api_expr2().GetRule_json_exists1();
pos = GetPos(jsonExists.GetToken1());
result = JsonExistsExpr(jsonExists);
break;
}
case TRule_json_api_expr::kAltJsonApiExpr3: {
const auto& jsonQuery = node.GetAlt_json_api_expr3().GetRule_json_query1();
pos = GetPos(jsonQuery.GetToken1());
result = JsonQueryExpr(jsonQuery);
break;
}
case TRule_json_api_expr::ALT_NOT_SET:
Y_ABORT("You should change implementation according to grammar changes");
}
return result;
}
TNodePtr MatchRecognizeVarAccess(TTranslation& ctx, const TString& var, const TRule_an_id_or_type& suffix, bool theSameVar) {
switch (suffix.GetAltCase()) {
case TRule_an_id_or_type::kAltAnIdOrType1:
break;
case TRule_an_id_or_type::kAltAnIdOrType2:
break;
case TRule_an_id_or_type::ALT_NOT_SET:
break;
}
const auto& column = Id(
suffix.GetAlt_an_id_or_type1()
.GetRule_id_or_type1().GetAlt_id_or_type1().GetRule_id1(),
ctx
);
return BuildMatchRecognizeVarAccess(TPosition{}, var, column, theSameVar);
}
TNodePtr TSqlExpression::RowPatternVarAccess(const TString& alias, const TRule_unary_subexpr_suffix_TBlock1_TBlock1_TAlt3_TBlock2 block) {
switch (block.GetAltCase()) {
case TRule_unary_subexpr_suffix_TBlock1_TBlock1_TAlt3_TBlock2::kAlt1:
break;
case TRule_unary_subexpr_suffix_TBlock1_TBlock1_TAlt3_TBlock2::kAlt2:
break;
case TRule_unary_subexpr_suffix_TBlock1_TBlock1_TAlt3_TBlock2::kAlt3:
switch (block.GetAlt3().GetRule_an_id_or_type1().GetAltCase()) {
case TRule_an_id_or_type::kAltAnIdOrType1: {
const auto &idOrType = block.GetAlt3().GetRule_an_id_or_type1().GetAlt_an_id_or_type1().GetRule_id_or_type1();
switch(idOrType.GetAltCase()) {
case TRule_id_or_type::kAltIdOrType1:
return BuildMatchRecognizeVarAccess(
Ctx.Pos(),
alias,
Id(idOrType.GetAlt_id_or_type1().GetRule_id1(), *this),
Ctx.GetMatchRecognizeDefineVar() == alias
);
case TRule_id_or_type::kAltIdOrType2:
break;
case TRule_id_or_type::ALT_NOT_SET:
break;
}
break;
}
case TRule_an_id_or_type::kAltAnIdOrType2:
break;
case TRule_an_id_or_type::ALT_NOT_SET:
break;
}
break;
case TRule_unary_subexpr_suffix_TBlock1_TBlock1_TAlt3_TBlock2::ALT_NOT_SET:
Y_ABORT("You should change implementation according to grammar changes");
}
return TNodePtr{};
}
template<typename TUnaryCasualExprRule>
TNodePtr TSqlExpression::UnaryCasualExpr(const TUnaryCasualExprRule& node, const TTrailingQuestions& tail) {
// unary_casual_subexpr: (id_expr | atom_expr) unary_subexpr_suffix;
// OR
// in_unary_casual_subexpr: (id_expr_in | in_atom_expr) unary_subexpr_suffix;
// where
// unary_subexpr_suffix: (key_expr | invoke_expr |(DOT (bind_parameter | DIGITS | id)))* (COLLATE id)?;
const auto& suffix = node.GetRule_unary_subexpr_suffix2();
const bool suffixIsEmpty = suffix.GetBlock1().empty() && !suffix.HasBlock2();
MaybeUnnamedSmartParenOnTop = MaybeUnnamedSmartParenOnTop && suffixIsEmpty;
TString name;
TNodePtr expr;
bool typePossible = false;
auto& block = node.GetBlock1();
switch (block.Alt_case()) {
case TUnaryCasualExprRule::TBlock1::kAlt1: {
MaybeUnnamedSmartParenOnTop = false;
auto& alt = block.GetAlt1();
if constexpr (std::is_same_v<TUnaryCasualExprRule, TRule_unary_casual_subexpr>) {
name = Id(alt.GetRule_id_expr1(), *this);
typePossible = !IsQuotedId(alt.GetRule_id_expr1(), *this);
} else {
// type was never possible here
name = Id(alt.GetRule_id_expr_in1(), *this);
}
break;
}
case TUnaryCasualExprRule::TBlock1::kAlt2: {
auto& alt = block.GetAlt2();
TMaybe<TExprOrIdent> exprOrId;
if constexpr (std::is_same_v<TUnaryCasualExprRule, TRule_unary_casual_subexpr>) {
exprOrId = AtomExpr(alt.GetRule_atom_expr1(), suffixIsEmpty ? tail : TTrailingQuestions{});
} else {
MaybeUnnamedSmartParenOnTop = false;
exprOrId = InAtomExpr(alt.GetRule_in_atom_expr1(), suffixIsEmpty ? tail : TTrailingQuestions{});
}
if (!exprOrId) {
Ctx.IncrementMonCounter("sql_errors", "BadAtomExpr");
return nullptr;
}
if (!exprOrId->Expr) {
name = exprOrId->Ident;
} else {
expr = exprOrId->Expr;
}
break;
}
case TUnaryCasualExprRule::TBlock1::ALT_NOT_SET:
Y_ABORT("You should change implementation according to grammar changes");
}
// bool onlyDots = true;
bool isColumnRef = !expr;
bool isFirstElem = true;
for (auto& _b : suffix.GetBlock1()) {
auto& b = _b.GetBlock1();
switch (b.Alt_case()) {
case TRule_unary_subexpr_suffix::TBlock1::TBlock1::kAlt1: {
// key_expr
// onlyDots = false;
break;
}
case TRule_unary_subexpr_suffix::TBlock1::TBlock1::kAlt2: {
// invoke_expr - cannot be a column, function name
if (isFirstElem) {
isColumnRef = false;
}
// onlyDots = false;
break;
}
case TRule_unary_subexpr_suffix::TBlock1::TBlock1::kAlt3: {
// In case of MATCH_RECOGNIZE lambdas
// X.Y is treated as Var.Column access
if (isColumnRef && EColumnRefState::MatchRecognize == Ctx.GetColumnReferenceState()) {
if (auto rowPatternVarAccess = RowPatternVarAccess(
name,
b.GetAlt3().GetBlock2())
) {
return rowPatternVarAccess;
}
}
break;
}
case TRule_unary_subexpr_suffix::TBlock1::TBlock1::ALT_NOT_SET:
AltNotImplemented("unary_subexpr_suffix", b);
return nullptr;
}
isFirstElem = false;
}
isFirstElem = true;
TVector<INode::TIdPart> ids;
INode::TPtr lastExpr;
if (!isColumnRef) {
lastExpr = expr;
} else {
const bool flexibleTypes = Ctx.FlexibleTypes;
bool columnOrType = false;
auto columnRefsState = Ctx.GetColumnReferenceState();
bool explicitPgType = columnRefsState == EColumnRefState::AsPgType;
if (explicitPgType && typePossible && suffixIsEmpty) {
auto pgType = BuildSimpleType(Ctx, Ctx.Pos(), name, false);
if (pgType && tail.Count) {
Ctx.Error() << "Optional types are not supported in this context";