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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
|
#include "executor.h"
#include "parse_double.h"
#include <yql/essentials/core/issue/protos/issue_id.pb.h>
#include <yql/essentials/minikql/dom/node.h>
#include <util/generic/scope.h>
#include <util/generic/maybe.h>
#include <util/system/compiler.h>
#include <cmath>
namespace NYql::NJsonPath {
using namespace NJson;
using namespace NUdf;
using namespace NDom;
namespace {
bool IsObjectOrArray(const TValue& value) {
return value.IsArray() || value.IsObject();
}
TIssue MakeError(TPosition pos, TIssueCode code, const TStringBuf message) {
TIssue error(pos, message);
error.SetCode(code, TSeverityIds::S_ERROR);
return error;
}
TIssue MakeError(const TJsonPathItem& item, TIssueCode code, const TStringBuf message) {
return MakeError(item.Pos, code, message);
}
}
TResult::TResult(TJsonNodes&& nodes)
: Result(std::move(nodes))
{
}
TResult::TResult(const TJsonNodes& nodes)
: Result(nodes)
{
}
TResult::TResult(TIssue&& issue)
: Result(std::move(issue))
{
}
const TJsonNodes& TResult::GetNodes() const {
return std::get<TJsonNodes>(Result);
}
TJsonNodes& TResult::GetNodes() {
return std::get<TJsonNodes>(Result);
}
const TIssue& TResult::GetError() const {
return std::get<TIssue>(Result);
}
bool TResult::IsError() const {
return std::holds_alternative<TIssue>(Result);
}
TExecutor::TExecutor(
const TJsonPathPtr path,
const TJsonNodes& input,
const TVariablesMap& variables,
const IValueBuilder* valueBuilder)
: Reader(path)
, Input(input)
, Variables(variables)
, ValueBuilder(valueBuilder)
{
}
bool TExecutor::IsZero(double value) {
return -EPSILON <= value && value <= EPSILON;
}
bool TExecutor::IsLess(double a, double b) {
return (b - a) > EPSILON;
}
bool TExecutor::IsGreater(double a, double b) {
return (a - b) > EPSILON;
}
bool TExecutor::IsEqual(double a, double b) {
return IsZero(a - b);
}
bool TExecutor::IsStrict() const {
return Reader.GetMode() == EJsonPathMode::Strict;
}
bool TExecutor::IsLax() const {
return Reader.GetMode() == EJsonPathMode::Lax;
}
TResult TExecutor::Execute() {
return Execute(Reader.ReadFirst());
}
TResult TExecutor::Execute(const TJsonPathItem& item) {
switch (item.Type) {
case EJsonPathItemType::MemberAccess:
return MemberAccess(item);
case EJsonPathItemType::WildcardMemberAccess:
return WildcardMemberAccess(item);
case EJsonPathItemType::ContextObject:
return ContextObject();
case EJsonPathItemType::Variable:
return Variable(item);
case EJsonPathItemType::NumberLiteral:
return NumberLiteral(item);
case EJsonPathItemType::ArrayAccess:
return ArrayAccess(item);
case EJsonPathItemType::WildcardArrayAccess:
return WildcardArrayAccess(item);
case EJsonPathItemType::LastArrayIndex:
return LastArrayIndex(item);
case EJsonPathItemType::UnaryMinus:
case EJsonPathItemType::UnaryPlus:
return UnaryArithmeticOp(item);
case EJsonPathItemType::BinaryAdd:
case EJsonPathItemType::BinarySubstract:
case EJsonPathItemType::BinaryMultiply:
case EJsonPathItemType::BinaryDivide:
case EJsonPathItemType::BinaryModulo:
return BinaryArithmeticOp(item);
case EJsonPathItemType::BinaryAnd:
case EJsonPathItemType::BinaryOr:
return BinaryLogicalOp(item);
case EJsonPathItemType::UnaryNot:
return UnaryLogicalOp(item);
case EJsonPathItemType::BooleanLiteral:
return BooleanLiteral(item);
case EJsonPathItemType::NullLiteral:
return NullLiteral();
case EJsonPathItemType::StringLiteral:
return StringLiteral(item);
case EJsonPathItemType::FilterObject:
return FilterObject(item);
case EJsonPathItemType::FilterPredicate:
return FilterPredicate(item);
case EJsonPathItemType::BinaryLess:
case EJsonPathItemType::BinaryLessEqual:
case EJsonPathItemType::BinaryGreater:
case EJsonPathItemType::BinaryGreaterEqual:
case EJsonPathItemType::BinaryEqual:
case EJsonPathItemType::BinaryNotEqual:
return CompareOp(item);
case EJsonPathItemType::AbsMethod:
case EJsonPathItemType::FloorMethod:
case EJsonPathItemType::CeilingMethod:
return NumericMethod(item);
case EJsonPathItemType::DoubleMethod:
return DoubleMethod(item);
case EJsonPathItemType::TypeMethod:
return TypeMethod(item);
case EJsonPathItemType::SizeMethod:
return SizeMethod(item);
case EJsonPathItemType::KeyValueMethod:
return KeyValueMethod(item);
case EJsonPathItemType::StartsWithPredicate:
return StartsWithPredicate(item);
case EJsonPathItemType::IsUnknownPredicate:
return IsUnknownPredicate(item);
case EJsonPathItemType::ExistsPredicate:
return ExistsPredicate(item);
case EJsonPathItemType::LikeRegexPredicate:
return LikeRegexPredicate(item);
}
}
TResult TExecutor::ContextObject() {
return Input;
}
TResult TExecutor::Variable(const TJsonPathItem& item) {
const auto it = Variables.find(item.GetString());
if (it == Variables.end()) {
return MakeError(item, TIssuesIds::JSONPATH_UNDEFINED_VARIABLE, TStringBuilder() << "Undefined variable '" << item.GetString() << "'");
}
return TJsonNodes({it->second});
}
TResult TExecutor::LastArrayIndex(const TJsonPathItem& item) {
if (ArraySubscriptSource.empty()) {
return MakeError(item, TIssuesIds::JSONPATH_LAST_OUTSIDE_OF_ARRAY_SUBSCRIPT, "'last' is only allowed inside array subscripts");
}
const auto& array = ArraySubscriptSource.top();
const i64 arraySize = array.GetSize();
// NOTE: For empty arrays `last` equals `-1`. This is intended, PostgreSQL 12 has the same behaviour
return TJsonNodes({TValue(MakeDouble(static_cast<double>(arraySize - 1)))});
}
TResult TExecutor::NumberLiteral(const TJsonPathItem& item) {
return TJsonNodes({TValue(MakeDouble(item.GetNumber()))});
}
TResult TExecutor::MemberAccess(const TJsonPathItem& item) {
const auto input = Execute(Reader.ReadInput(item));
if (input.IsError()) {
return input;
}
TJsonNodes result;
for (const auto& node : OptionalUnwrapArrays(input.GetNodes())) {
if (!node.IsObject()) {
if (IsStrict()) {
return MakeError(item, TIssuesIds::JSONPATH_EXPECTED_OBJECT, "Expected object");
} else {
continue;
}
}
if (const auto payload = node.Lookup(item.GetString())) {
result.push_back(*payload);
continue;
}
if (IsStrict()) {
return MakeError(item, TIssuesIds::JSONPATH_MEMBER_NOT_FOUND, "Member not found");
}
}
return std::move(result);
}
TResult TExecutor::WildcardMemberAccess(const TJsonPathItem& item) {
const auto input = Execute(Reader.ReadInput(item));
if (input.IsError()) {
return input;
}
TJsonNodes result;
for (const auto& node : OptionalUnwrapArrays(input.GetNodes())) {
if (!node.IsObject()) {
if (IsStrict()) {
return MakeError(item, TIssuesIds::JSONPATH_EXPECTED_OBJECT, "Expected object");
} else {
continue;
}
}
TValue key;
TValue value;
auto it = node.GetObjectIterator();
while (it.Next(key, value)) {
result.push_back(value);
}
}
return std::move(result);
}
TMaybe<TIssue> TExecutor::EnsureSingleSubscript(TPosition pos, const TJsonNodes& index, i64& result) {
if (index.size() != 1) {
return MakeError(pos, TIssuesIds::JSONPATH_INVALID_ARRAY_INDEX, "Expected single number item for array index");
}
const auto& indexValue = index[0];
if (!indexValue.IsNumber()) {
return MakeError(pos, TIssuesIds::JSONPATH_INVALID_ARRAY_INDEX, "Array index must be number");
}
result = static_cast<i64>(std::floor(indexValue.GetNumber()));
return Nothing();
}
TMaybe<TIssue> TExecutor::EnsureArraySubscripts(const TJsonPathItem& item, TVector<TArraySubscript>& result) {
for (const auto& subscript : item.GetSubscripts()) {
const auto& fromItem = Reader.ReadFromSubscript(subscript);
const auto fromResult = Execute(fromItem);
if (fromResult.IsError()) {
return fromResult.GetError();
}
i64 fromIndex = 0;
TMaybe<TIssue> error = EnsureSingleSubscript(fromItem.Pos, fromResult.GetNodes(), fromIndex);
if (error) {
return error;
}
if (!subscript.IsRange()) {
result.emplace_back(fromIndex, fromItem.Pos);
continue;
}
const auto& toItem = Reader.ReadToSubscript(subscript);
const auto toResult = Execute(toItem);
if (toResult.IsError()) {
return toResult.GetError();
}
i64 toIndex = 0;
error = EnsureSingleSubscript(toItem.Pos, toResult.GetNodes(), toIndex);
if (error) {
return error;
}
result.emplace_back(fromIndex, fromItem.Pos, toIndex, toItem.Pos);
}
return Nothing();
}
TResult TExecutor::ArrayAccess(const TJsonPathItem& item) {
const auto input = Execute(Reader.ReadInput(item));
if (input.IsError()) {
return input;
}
TJsonNodes result;
for (const auto& node : OptionalArrayWrapNodes(input.GetNodes())) {
if (!node.IsArray()) {
return MakeError(item, TIssuesIds::JSONPATH_EXPECTED_ARRAY, "Expected array");
}
ArraySubscriptSource.push(node);
Y_DEFER {
ArraySubscriptSource.pop();
};
// Check for "hard" errors in array subscripts. These are forbidden even in lax mode
// NOTE: We intentionally execute subscripts expressions for each array in the input
// because they can contain `last` keyword which value is different for each array
TVector<TArraySubscript> subscripts;
TMaybe<TIssue> error = EnsureArraySubscripts(item, subscripts);
if (error) {
return std::move(*error);
}
const ui64 arraySize = node.GetSize();
for (const auto& idx : subscripts) {
// Check bounds for first subscript
if (idx.GetFrom() < 0 || idx.GetFrom() >= static_cast<i64>(arraySize)) {
if (IsStrict()) {
return MakeError(idx.GetFromPos(), TIssuesIds::JSONPATH_ARRAY_INDEX_OUT_OF_BOUNDS, "Array index out of bounds");
} else {
continue;
}
}
// If there is no second subcripts, just return corresponding array element
if (!idx.IsRange()) {
result.push_back(node.GetElement(idx.GetFrom()));
continue;
}
// Check bounds for second subscript
if (idx.GetTo() < 0 || idx.GetTo() >= static_cast<i64>(arraySize)) {
if (IsStrict()) {
return MakeError(idx.GetToPos(), TIssuesIds::JSONPATH_ARRAY_INDEX_OUT_OF_BOUNDS, "Array index out of bounds");
} else {
continue;
}
}
// In strict mode invalid ranges are forbidden
if (idx.GetFrom() > idx.GetTo() && IsStrict()) {
return MakeError(idx.GetFromPos(), TIssuesIds::JSONPATH_INVALID_ARRAY_INDEX_RANGE, "Range lower bound is greater than upper bound");
}
for (i64 i = idx.GetFrom(); i <= idx.GetTo(); i++) {
result.push_back(node.GetElement(i));
}
}
}
return std::move(result);
}
TResult TExecutor::WildcardArrayAccess(const TJsonPathItem& item) {
const auto input = Execute(Reader.ReadInput(item));
if (input.IsError()) {
return input;
}
TJsonNodes result;
for (const auto& node : OptionalArrayWrapNodes(input.GetNodes())) {
if (!node.IsArray()) {
return MakeError(item, TIssuesIds::JSONPATH_EXPECTED_ARRAY, "Expected array");
}
auto it = node.GetArrayIterator();
TValue value;
while (it.Next(value)) {
result.push_back(value);
}
}
return std::move(result);
}
TResult TExecutor::UnaryArithmeticOp(const TJsonPathItem& item) {
const auto& operandItem = Reader.ReadInput(item);
const auto operandsResult = Execute(operandItem);
if (operandsResult.IsError()) {
return operandsResult;
}
const auto& operands = operandsResult.GetNodes();
TJsonNodes result;
result.reserve(operands.size());
for (const auto& operand : operands) {
if (!operand.IsNumber()) {
return MakeError(
operandItem, TIssuesIds::JSONPATH_INVALID_UNARY_OPERATION_ARGUMENT_TYPE,
TStringBuilder() << "Unsupported type for unary operations"
);
}
if (item.Type == EJsonPathItemType::UnaryPlus) {
result.push_back(operand);
continue;
}
const auto value = operand.GetNumber();
result.push_back(TValue(MakeDouble(-value)));
}
return std::move(result);
}
TMaybe<TIssue> TExecutor::EnsureBinaryArithmeticOpArgument(TPosition pos, const TJsonNodes& nodes, double& result) {
if (nodes.size() != 1) {
return MakeError(pos, TIssuesIds::JSONPATH_INVALID_BINARY_OPERATION_ARGUMENT, "Expected exactly 1 item as an operand for binary operation");
}
const auto& value = nodes[0];
if (!value.IsNumber()) {
return MakeError(
pos, TIssuesIds::JSONPATH_INVALID_BINARY_OPERATION_ARGUMENT_TYPE,
TStringBuilder() << "Unsupported type for binary operations"
);
}
result = value.GetNumber();
return Nothing();
}
TResult TExecutor::BinaryArithmeticOp(const TJsonPathItem& item) {
const auto& leftItem = Reader.ReadLeftOperand(item);
const auto leftResult = Execute(leftItem);
if (leftResult.IsError()) {
return leftResult;
}
double left = 0;
TMaybe<TIssue> error = EnsureBinaryArithmeticOpArgument(leftItem.Pos, leftResult.GetNodes(), left);
if (error) {
return std::move(*error);
}
const auto& rightItem = Reader.ReadRightOperand(item);
const auto rightResult = Execute(rightItem);
if (rightResult.IsError()) {
return rightResult;
}
double right = 0;
error = EnsureBinaryArithmeticOpArgument(rightItem.Pos, rightResult.GetNodes(), right);
if (error) {
return std::move(*error);
}
double result = 0;
switch (item.Type) {
case EJsonPathItemType::BinaryAdd:
result = left + right;
break;
case EJsonPathItemType::BinarySubstract:
result = left - right;
break;
case EJsonPathItemType::BinaryMultiply:
result = left * right;
break;
case EJsonPathItemType::BinaryDivide:
if (IsZero(right)) {
return MakeError(rightItem, TIssuesIds::JSONPATH_DIVISION_BY_ZERO, "Division by zero");
}
result = left / right;
break;
case EJsonPathItemType::BinaryModulo:
if (IsZero(right)) {
return MakeError(rightItem, TIssuesIds::JSONPATH_DIVISION_BY_ZERO, "Division by zero");
}
result = std::fmod(left, right);
break;
default:
YQL_ENSURE(false, "Expected binary arithmetic operation");
}
if (Y_UNLIKELY(std::isinf(result))) {
return MakeError(item, TIssuesIds::JSONPATH_BINARY_OPERATION_RESULT_INFINITY, "Binary operation result is infinity");
}
return TJsonNodes({TValue(MakeDouble(result))});
}
TMaybe<TIssue> TExecutor::EnsureLogicalOpArgument(TPosition pos, const TJsonNodes& nodes, TMaybe<bool>& result) {
if (nodes.size() != 1) {
return MakeError(pos, TIssuesIds::JSONPATH_INVALID_LOGICAL_OPERATION_ARGUMENT, "Expected exactly 1 item as an operand for logical operation");
}
const auto& value = nodes[0];
if (value.IsNull()) {
result = Nothing();
} else if (value.IsBool()) {
result = value.GetBool();
} else {
return MakeError(pos, TIssuesIds::JSONPATH_INVALID_LOGICAL_OPERATION_ARGUMENT, "Unsupported type for logical operation");
}
return Nothing();
}
TResult TExecutor::BinaryLogicalOp(const TJsonPathItem& item) {
const auto& leftItem = Reader.ReadLeftOperand(item);
const auto leftResult = Execute(leftItem);
if (leftResult.IsError()) {
return leftResult;
}
TMaybe<bool> left;
TMaybe<TIssue> error = EnsureLogicalOpArgument(leftItem.Pos, leftResult.GetNodes(), left);
if (error) {
return std::move(*error);
}
const auto& rightItem = Reader.ReadRightOperand(item);
const auto rightResult = Execute(rightItem);
if (rightResult.IsError()) {
return rightResult;
}
TMaybe<bool> right;
error = EnsureLogicalOpArgument(rightItem.Pos, rightResult.GetNodes(), right);
if (error) {
return std::move(*error);
}
switch (item.Type) {
case EJsonPathItemType::BinaryAnd: {
/*
AND truth table (taken from SQL JSON standard)
| && | true | false | null |
| ----- | ----- | ----- | ----- |
| true | true | false | null |
| false | false | false | false |
| null | null | false | null |
*/
if (left.Defined() && right.Defined()) {
return TJsonNodes({TValue(MakeBool(*left && *right))});
}
const bool falseVsNull = !left.GetOrElse(true) && !right.Defined();
const bool nullVsFalse = !right.GetOrElse(true) && !left.Defined();
if (falseVsNull || nullVsFalse) {
return TJsonNodes({TValue(MakeBool(false))});
}
return TJsonNodes({TValue(MakeEntity())});
}
case EJsonPathItemType::BinaryOr: {
/*
OR truth table (taken from SQL JSON standard)
| || | true | false | null |
| ----- | ----- | ----- | ----- |
| true | true | true | true |
| false | true | false | null |
| null | true | null | null |
*/
if (left.Defined() && right.Defined()) {
return TJsonNodes({TValue(MakeBool(*left || *right))});
}
const bool trueVsNull = left.GetOrElse(false) && !right.Defined();
const bool nullVsTrue = right.GetOrElse(false) && !left.Defined();
if (trueVsNull || nullVsTrue) {
return TJsonNodes({TValue(MakeBool(true))});
}
return TJsonNodes({TValue(MakeEntity())});
}
default:
YQL_ENSURE(false, "Expected binary logical operation");
}
}
TResult TExecutor::UnaryLogicalOp(const TJsonPathItem& item) {
/*
NOT truth table (taken from SQL JSON standard)
| x | !x |
| ----- | ----- |
| true | false |
| false | true |
| null | null |
*/
const auto& operandItem = Reader.ReadInput(item);
const auto operandResult = Execute(operandItem);
if (operandResult.IsError()) {
return operandResult;
}
TMaybe<bool> operand;
TMaybe<TIssue> error = EnsureLogicalOpArgument(operandItem.Pos, operandResult.GetNodes(), operand);
if (error) {
return std::move(*error);
}
if (!operand.Defined()) {
return TJsonNodes({TValue(MakeEntity())});
}
return TJsonNodes({TValue(MakeBool(!(*operand)))});
}
TResult TExecutor::BooleanLiteral(const TJsonPathItem& item) {
return TJsonNodes({TValue(MakeBool(item.GetBoolean()))});
}
TResult TExecutor::NullLiteral() {
return TJsonNodes({TValue(MakeEntity())});
}
TResult TExecutor::StringLiteral(const TJsonPathItem& item) {
return TJsonNodes({TValue(MakeString(item.GetString(), ValueBuilder))});
}
TMaybe<bool> TExecutor::CompareValues(const TValue& left, const TValue& right, EJsonPathItemType operation) {
if (IsObjectOrArray(left) || IsObjectOrArray(right)) {
// Comparisons of objects and arrays are prohibited
return Nothing();
}
if (left.IsNull() && right.IsNull()) {
// null == null is true, but all other comparisons are false
return operation == EJsonPathItemType::BinaryEqual;
}
if (left.IsNull() || right.IsNull()) {
// All operations between null and non-null are false
return false;
}
auto doCompare = [&operation](const auto& left, const auto& right) {
switch (operation) {
case EJsonPathItemType::BinaryEqual:
return left == right;
case EJsonPathItemType::BinaryNotEqual:
return left != right;
case EJsonPathItemType::BinaryLess:
return left < right;
case EJsonPathItemType::BinaryLessEqual:
return left <= right;
case EJsonPathItemType::BinaryGreater:
return left > right;
case EJsonPathItemType::BinaryGreaterEqual:
return left >= right;
default:
YQL_ENSURE(false, "Expected compare operation");
}
};
if (left.IsBool() && right.IsBool()) {
return doCompare(left.GetBool(), right.GetBool());
} else if (left.IsString() && right.IsString()) {
// NOTE: Strings are compared as byte arrays.
// YQL does the same thing for UTF-8 strings and according to SQL/JSON
// standard JsonPath must use the same semantics.
//
// However this is not correct in logical meaning. Let us consider strings:
// - U+00e9 (LATIN SMALL LETTER E WITH ACUTE), 'é'
// - U+0065 (LATIN SMALL LETTER E) U+0301 (COMBINING ACUTE ACCENT), `é`
// Even though these two strings are different byte sequences, they are identical
// from UTF-8 perspective.
return doCompare(left.GetString(), right.GetString());
}
if (!left.IsNumber() || !right.IsNumber()) {
return Nothing();
}
const auto leftNumber = left.GetNumber();
const auto rightNumber = right.GetNumber();
switch (operation) {
case EJsonPathItemType::BinaryEqual:
return IsEqual(leftNumber, rightNumber);
case EJsonPathItemType::BinaryNotEqual:
return !IsEqual(leftNumber, rightNumber);
case EJsonPathItemType::BinaryLess:
return IsLess(leftNumber, rightNumber);
case EJsonPathItemType::BinaryLessEqual:
return !IsGreater(leftNumber, rightNumber);
case EJsonPathItemType::BinaryGreater:
return IsGreater(leftNumber, rightNumber);
case EJsonPathItemType::BinaryGreaterEqual:
return !IsLess(leftNumber, rightNumber);
default:
YQL_ENSURE(false, "Expected compare operation");
}
}
TResult TExecutor::CompareOp(const TJsonPathItem& item) {
const auto& leftItem = Reader.ReadLeftOperand(item);
const auto leftResult = Execute(leftItem);
if (leftResult.IsError()) {
return TJsonNodes({TValue(MakeEntity())});
}
const auto& rightItem = Reader.ReadRightOperand(item);
const auto rightResult = Execute(rightItem);
if (rightResult.IsError()) {
return TJsonNodes({TValue(MakeEntity())});
}
const auto leftNodes = OptionalUnwrapArrays(leftResult.GetNodes());
const auto rightNodes = OptionalUnwrapArrays(rightResult.GetNodes());
bool error = false;
bool found = false;
for (const auto& left : leftNodes) {
for (const auto& right : rightNodes) {
const auto result = CompareValues(left, right, item.Type);
if (!result.Defined()) {
error = true;
} else {
found |= *result;
}
if (IsLax() && (error || found)) {
break;
}
}
if (IsLax() && (error || found)) {
break;
}
}
if (error) {
return TJsonNodes({TValue(MakeEntity())});
}
return TJsonNodes({TValue(MakeBool(found))});
}
TResult TExecutor::FilterObject(const TJsonPathItem& item) {
if (CurrentFilterObject.empty()) {
return MakeError(item, TIssuesIds::JSONPATH_FILTER_OBJECT_OUTSIDE_OF_FILTER, "'@' is only allowed inside filters");
}
return TJsonNodes({CurrentFilterObject.top()});
}
TResult TExecutor::FilterPredicate(const TJsonPathItem& item) {
const auto input = Execute(Reader.ReadInput(item));
if (input.IsError()) {
return input;
}
const auto& predicateItem = Reader.ReadFilterPredicate(item);
TJsonNodes result;
for (const auto& node : OptionalUnwrapArrays(input.GetNodes())) {
CurrentFilterObject.push(node);
Y_DEFER {
CurrentFilterObject.pop();
};
const auto predicateResult = Execute(predicateItem);
if (predicateResult.IsError()) {
continue;
}
const auto& predicateNodes = predicateResult.GetNodes();
if (predicateNodes.size() != 1) {
continue;
}
const auto& value = predicateNodes[0];
if (value.IsBool() && value.GetBool()) {
result.push_back(node);
continue;
}
}
return std::move(result);
}
TResult TExecutor::NumericMethod(const TJsonPathItem& item) {
const auto& input = Execute(Reader.ReadInput(item));
if (input.IsError()) {
return input;
}
TJsonNodes result;
for (const auto& node : OptionalUnwrapArrays(input.GetNodes())) {
if (!node.IsNumber()) {
return MakeError(item, TIssuesIds::JSONPATH_INVALID_NUMERIC_METHOD_ARGUMENT, "Unsupported type for numeric method");
}
double applied = node.GetNumber();
switch (item.Type) {
case EJsonPathItemType::AbsMethod:
applied = std::fabs(applied);
break;
case EJsonPathItemType::FloorMethod:
applied = std::floor(applied);
break;
case EJsonPathItemType::CeilingMethod:
applied = std::ceil(applied);
break;
default:
YQL_ENSURE(false, "Expected numeric method");
}
result.push_back(TValue(MakeDouble(applied)));
}
return std::move(result);
}
TResult TExecutor::DoubleMethod(const TJsonPathItem& item) {
const auto& input = Execute(Reader.ReadInput(item));
if (input.IsError()) {
return input;
}
TJsonNodes result;
for (const auto& node : OptionalUnwrapArrays(input.GetNodes())) {
if (!node.IsString()) {
return MakeError(item, TIssuesIds::JSONPATH_INVALID_DOUBLE_METHOD_ARGUMENT, "Unsupported type for double() method");
}
const double parsed = ParseDouble(node.GetString());
if (std::isnan(parsed)) {
return MakeError(item, TIssuesIds::JSONPATH_INVALID_NUMBER_STRING, "Error parsing number from string");
}
if (std::isinf(parsed)) {
return MakeError(item, TIssuesIds::JSONPATH_INFINITE_NUMBER_STRING, "Parsed number is infinity");
}
result.push_back(TValue(MakeDouble(parsed)));
}
return std::move(result);
}
TResult TExecutor::TypeMethod(const TJsonPathItem& item) {
const auto& input = Execute(Reader.ReadInput(item));
if (input.IsError()) {
return input;
}
TJsonNodes result;
for (const auto& node : input.GetNodes()) {
TStringBuf type;
switch (node.GetType()) {
case EValueType::Null:
type = "null";
break;
case EValueType::Bool:
type = "boolean";
break;
case EValueType::Number:
type = "number";
break;
case EValueType::String:
type = "string";
break;
case EValueType::Array:
type = "array";
break;
case EValueType::Object:
type = "object";
break;
}
result.push_back(TValue(MakeString(type, ValueBuilder)));
}
return std::move(result);
}
TResult TExecutor::SizeMethod(const TJsonPathItem& item) {
const auto& input = Execute(Reader.ReadInput(item));
if (input.IsError()) {
return input;
}
TJsonNodes result;
for (const auto& node : input.GetNodes()) {
ui64 size = 1;
if (node.IsArray()) {
size = node.GetSize();
}
result.push_back(TValue(MakeDouble(static_cast<double>(size))));
}
return std::move(result);
}
TResult TExecutor::KeyValueMethod(const TJsonPathItem& item) {
const auto& input = Execute(Reader.ReadInput(item));
if (input.IsError()) {
return input;
}
TJsonNodes result;
TPair row[2];
TPair& nameEntry = row[0];
TPair& valueEntry = row[1];
for (const auto& node : OptionalUnwrapArrays(input.GetNodes())) {
if (!node.IsObject()) {
return MakeError(item, TIssuesIds::JSONPATH_INVALID_KEYVALUE_METHOD_ARGUMENT, "Unsupported type for keyvalue() method");
}
TValue key;
TValue value;
auto it = node.GetObjectIterator();
while (it.Next(key, value)) {
nameEntry.first = MakeString("name", ValueBuilder);
nameEntry.second = key.ConvertToUnboxedValue(ValueBuilder);
valueEntry.first = MakeString("value", ValueBuilder);
valueEntry.second = value.ConvertToUnboxedValue(ValueBuilder);
result.push_back(TValue(MakeDict(row, 2)));
}
}
return std::move(result);
}
TResult TExecutor::StartsWithPredicate(const TJsonPathItem& item) {
const auto& input = Execute(Reader.ReadInput(item));
if (input.IsError()) {
return input;
}
const auto& inputNodes = input.GetNodes();
if (inputNodes.size() != 1) {
return MakeError(item, TIssuesIds::JSONPATH_INVALID_STARTS_WITH_ARGUMENT, "Expected exactly 1 item as input argument for starts with predicate");
}
const auto& inputString = inputNodes[0];
if (!inputString.IsString()) {
return MakeError(item, TIssuesIds::JSONPATH_INVALID_STARTS_WITH_ARGUMENT, "Type of input argument for starts with predicate must be string");
}
const auto prefix = Execute(Reader.ReadPrefix(item));
if (prefix.IsError()) {
return prefix;
}
bool error = false;
bool found = false;
for (const auto& node : prefix.GetNodes()) {
if (node.IsString()) {
found |= inputString.GetString().StartsWith(node.GetString());
} else {
error = true;
}
if (IsLax() && (found || error)) {
break;
}
}
if (error) {
return TJsonNodes({TValue(MakeEntity())});
}
return TJsonNodes({TValue(MakeBool(found))});
}
TResult TExecutor::IsUnknownPredicate(const TJsonPathItem& item) {
const auto input = Execute(Reader.ReadInput(item));
if (input.IsError()) {
return input;
}
const auto& nodes = input.GetNodes();
if (nodes.size() != 1) {
return MakeError(item, TIssuesIds::JSONPATH_INVALID_IS_UNKNOWN_ARGUMENT, "Expected exactly 1 item as an argument for is unknown predicate");
}
const auto& node = nodes[0];
if (node.IsNull()) {
return TJsonNodes({TValue(MakeBool(true))});
}
if (!node.IsBool()) {
return MakeError(item, TIssuesIds::JSONPATH_INVALID_IS_UNKNOWN_ARGUMENT, "is unknown predicate supports only bool and null types for its argument");
}
return TJsonNodes({TValue(MakeBool(false))});
}
TResult TExecutor::ExistsPredicate(const TJsonPathItem& item) {
const auto input = Execute(Reader.ReadInput(item));
if (input.IsError()) {
return TJsonNodes({TValue(MakeEntity())});
}
const auto& nodes = input.GetNodes();
return TJsonNodes({TValue(MakeBool(!nodes.empty()))});
}
TResult TExecutor::LikeRegexPredicate(const TJsonPathItem& item) {
const auto input = Execute(Reader.ReadInput(item));
if (input.IsError()) {
return input;
}
const auto& regex = item.GetRegex();
bool error = false;
bool found = false;
for (const auto& node : OptionalUnwrapArrays(input.GetNodes())) {
if (node.IsString()) {
found |= regex->Matches(node.GetString());
} else {
error = true;
}
if (IsLax() && (found || error)) {
break;
}
}
if (error) {
return TJsonNodes({TValue(MakeEntity())});
}
return TJsonNodes({TValue(MakeBool(found))});
}
TJsonNodes TExecutor::OptionalUnwrapArrays(const TJsonNodes& input) {
if (IsStrict()) {
return input;
}
TJsonNodes result;
for (const auto& node : input) {
if (!node.IsArray()) {
result.push_back(node);
continue;
}
auto it = node.GetArrayIterator();
TValue value;
while (it.Next(value)) {
result.push_back(value);
}
}
return result;
}
TJsonNodes TExecutor::OptionalArrayWrapNodes(const TJsonNodes& input) {
if (IsStrict()) {
return input;
}
TJsonNodes result;
for (const auto& node : input) {
if (node.IsArray()) {
result.push_back(node);
continue;
}
TUnboxedValue nodeCopy(node.ConvertToUnboxedValue(ValueBuilder));
result.push_back(TValue(MakeList(&nodeCopy, 1, ValueBuilder)));
}
return result;
}
}
|