-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjson_dom.cc
3669 lines (3217 loc) · 123 KB
/
json_dom.cc
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
/* Copyright (c) 2015, 2024, Oracle and/or its affiliates.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2.0,
as published by the Free Software Foundation.
This program is designed to work with certain software (including
but not limited to OpenSSL) that is licensed under separate terms,
as designated in a particular file or component or in included license
documentation. The authors of MySQL hereby grant you an additional
permission to link the program and your derivative works with the
separately licensed software that they have either included with
the program or referenced in the documentation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License, version 2.0, for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
#include "sql-common/json_dom.h"
#include <errno.h>
#include <float.h>
#include <limits.h>
#include <stdint.h>
#include <string.h>
#include <sys/types.h>
#include <algorithm> // std::min, std::max
#include <cmath> // std::isfinite
#include <functional> // std::function
#include <new>
#include <utility>
#include "my_rapidjson_size_t.h" // IWYU pragma: keep
#include <rapidjson/error/en.h>
#include <rapidjson/error/error.h>
#include <rapidjson/memorystream.h>
#include <rapidjson/reader.h>
#include "base64.h"
#include "decimal.h"
#include "m_ctype.h"
#include "m_string.h" // my_gcvt, _dig_vec_lower
#include "my_byteorder.h"
#include "my_compare.h"
#include "my_dbug.h"
#include "my_double2ulonglong.h"
#include "my_sys.h"
#include "my_time.h"
#include "mysql/components/services/bits/psi_bits.h"
#include "mysql/service_mysql_alloc.h"
#include "mysql_com.h"
#include "mysqld_error.h" // ER_*
#include "sql/malloc_allocator.h"
#include "sql/my_decimal.h"
#ifdef MYSQL_SERVER
#include "sql/check_stack.h"
#endif
#include "sql-common/json_binary.h"
#include "sql-common/json_path.h"
#include "sql-common/json_syntax_check.h"
#include "sql/current_thd.h" // current_thd
#include "sql/derror.h" // ER_THD
#include "sql/field.h"
#include "sql/psi_memory_key.h" // key_memory_JSON
#include "sql/sql_class.h" // THD
#include "sql/sql_const.h" // STACK_MIN_SIZE
#include "sql/sql_error.h"
#include "sql/sql_sort.h"
#include "sql/sql_time.h"
#include "sql/system_variables.h"
#include "sql/table.h"
#include "sql_string.h"
#include "template_utils.h" // down_cast, pointer_cast
#ifndef MYSQL_SERVER
#define key_memory_JSON PSI_NOT_INSTRUMENTED
#endif
static Json_dom *json_binary_to_dom_template(const json_binary::Value &v);
#ifdef MYSQL_SERVER
/**
Auto-wrap a dom in an array if it is not already an array. Delete
the dom if there is a memory allocation failure.
*/
static Json_array_ptr wrap_in_array(Json_dom_ptr dom) {
if (dom->json_type() == enum_json_type::J_ARRAY)
return Json_array_ptr(down_cast<Json_array *>(dom.release()));
Json_array_ptr a = create_dom_ptr<Json_array>();
if (a == nullptr || a->append_alias(std::move(dom)))
return nullptr; /* purecov: inspected */
return a;
}
Json_dom_ptr merge_doms(Json_dom_ptr left, Json_dom_ptr right) {
if (left->json_type() == enum_json_type::J_OBJECT &&
right->json_type() == enum_json_type::J_OBJECT) {
Json_object_ptr left_object(down_cast<Json_object *>(left.release()));
Json_object_ptr right_object(down_cast<Json_object *>(right.release()));
if (left_object->consume(std::move(right_object)))
return nullptr; /* purecov: inspected */
return left_object;
}
Json_array_ptr left_array = wrap_in_array(std::move(left));
Json_array_ptr right_array = wrap_in_array(std::move(right));
if (left_array == nullptr || right_array == nullptr ||
left_array->consume(std::move(right_array)))
return nullptr; /* purecov: inspected */
return left_array;
}
#endif // ifdef MYSQL_SERVER
void *Json_dom::operator new(size_t size, const std::nothrow_t &) noexcept {
/*
Call my_malloc() with the MY_WME flag to make sure that it will
write an error message if the memory could not be allocated.
*/
return my_malloc(key_memory_JSON, size, MYF(MY_WME));
}
void Json_dom::operator delete(void *ptr) noexcept { my_free(ptr); }
/*
This operator is included in order to silence warnings on some
compilers. It is called if the constructor throws an exception when
an object is allocated with nothrow new. This is not supposed to
happen and is therefore hard to test, so annotate it to avoid
cluttering the test coverage reports.
*/
/* purecov: begin inspected */
void Json_dom::operator delete(void *ptr, const std::nothrow_t &) noexcept {
operator delete(ptr);
}
/* purecov: end */
/**
Add a value to a vector if it isn't already there.
This is used for removing duplicate matches for daisy-chained
ellipsis tokens in #find_child_doms(). The problem with
daisy-chained ellipses is that the candidate set may contain the
same Json_dom object multiple times at different nesting levels
after matching the first ellipsis. That is, the candidate set may
contain a Json_dom and its parent, grandparent and so on. When
matching the next ellipsis in the path, each value in the candidate
set and all its children will be inspected, so the nested Json_dom
will be seen multiple times, as its grandparent, parent and finally
itself are inspected. We want it to appear only once in the result.
The same problem occurs if a possibly auto-wrapping array path leg
comes after an ellipsis. If the candidate set contains both an array
element and its parent array due to the ellipsis, the auto-wrapping
path leg may match the array element twice, and we only want it once
in the result.
@param[in] candidate value to add
@param[in,out] duplicates set of values added, or `nullptr` if duplicate
checking is not needed
@param[in,out] result vector
@return false on success, true on error
*/
static bool add_if_missing(Json_dom *candidate, Json_dom_vector *duplicates,
Json_dom_vector *result) {
/*
If we are not checking duplicates, or if the candidate is not
already in the duplicate set, add the candidate to the result
vector.
*/
if (duplicates == nullptr || duplicates->insert_unique(candidate).second) {
return result->push_back(candidate);
}
return false;
}
/**
Check if a seek operation performed by find_child_doms()
or Json_dom::seek() is done.
@return true if only one result is needed and a result has been found
*/
static inline bool is_seek_done(const Json_dom_vector *hits,
bool only_need_one) {
return only_need_one && hits->size() > 0;
}
/**
Find the child Json_dom objects identified by the given path.
The child doms are added to a vector.
See the header comment for #Json_wrapper::seek() for a discussion
of complexities involving path expressions with more than one
ellipsis (**) token, or a combination of ellipsis and auto-wrapping
path legs.
@param[in] dom the DOM to search
@param[in] current_leg iterator to the path leg to look at
@param[in] last_leg iterator to the last path leg (exclusive)
@param[in] auto_wrap if true, auto-wrap non-arrays when matching against
array path legs
@param[in] only_need_one true if we can stop after finding one match
@param[in,out] duplicates set of values collected, which helps to identify
duplicate arrays and objects introduced by daisy-chained
** tokens or auto-wrapping, or `nullptr` if duplicate
elimination is not needed for this path leg
@param[in,out] result the vector of qualifying children
@return false on success, true on error
*/
static bool find_child_doms(Json_dom *dom,
const Json_path_iterator ¤t_leg,
const Json_path_iterator &last_leg, bool auto_wrap,
bool only_need_one, Json_dom_vector *duplicates,
Json_dom_vector *result) {
if (current_leg == last_leg) return add_if_missing(dom, duplicates, result);
const enum_json_type dom_type = dom->json_type();
const Json_path_leg *const path_leg = *current_leg;
const Json_path_iterator next_leg = current_leg + 1;
switch (path_leg->get_type()) {
case jpl_array_cell:
if (dom_type == enum_json_type::J_ARRAY) {
const auto array = down_cast<const Json_array *>(dom);
const Json_array_index idx = path_leg->first_array_index(array->size());
return idx.within_bounds() &&
find_child_doms((*array)[idx.position()], next_leg, last_leg,
auto_wrap, only_need_one, duplicates, result);
}
// Handle auto-wrapping of non-arrays.
return auto_wrap && path_leg->is_autowrap() &&
find_child_doms(dom, next_leg, last_leg, auto_wrap, only_need_one,
duplicates, result);
case jpl_array_range:
case jpl_array_cell_wildcard:
if (dom_type == enum_json_type::J_ARRAY) {
const auto array = down_cast<const Json_array *>(dom);
const auto range = path_leg->get_array_range(array->size());
for (size_t i = range.m_begin; i < range.m_end; ++i) {
if (find_child_doms((*array)[i], next_leg, last_leg, auto_wrap,
only_need_one, duplicates, result))
return true; /* purecov: inspected */
if (is_seek_done(result, only_need_one)) return false;
}
return false;
}
// Handle auto-wrapping of non-arrays.
return auto_wrap && path_leg->is_autowrap() &&
find_child_doms(dom, next_leg, last_leg, auto_wrap, only_need_one,
duplicates, result);
case jpl_ellipsis: {
// The ellipsis matches the value on which it is called ...
if (find_child_doms(dom, next_leg, last_leg, auto_wrap, only_need_one,
duplicates, result))
return true; /* purecov: inspected */
// ... and, recursively, all the values contained in it.
if (dom_type == enum_json_type::J_ARRAY) {
for (const Json_dom_ptr &child : *down_cast<const Json_array *>(dom)) {
if (is_seek_done(result, only_need_one)) return false;
// Now recurse and add the child and values under it.
if (find_child_doms(child.get(), current_leg, last_leg, auto_wrap,
only_need_one, duplicates, result))
return true; /* purecov: inspected */
} // end of loop through children
} else if (dom_type == enum_json_type::J_OBJECT) {
for (const auto &member : *down_cast<const Json_object *>(dom)) {
if (is_seek_done(result, only_need_one)) return false;
// Now recurse and add the child and values under it.
if (find_child_doms(member.second.get(), current_leg, last_leg,
auto_wrap, only_need_one, duplicates, result))
return true; /* purecov: inspected */
} // end of loop through children
}
return false;
}
case jpl_member: {
if (dom_type == enum_json_type::J_OBJECT) {
const auto object = down_cast<const Json_object *>(dom);
Json_dom *child = object->get(path_leg->get_member_name());
return child != nullptr &&
find_child_doms(child, next_leg, last_leg, auto_wrap,
only_need_one, duplicates, result);
}
return false;
}
case jpl_member_wildcard: {
if (dom_type == enum_json_type::J_OBJECT) {
for (const auto &member : *down_cast<const Json_object *>(dom)) {
if (find_child_doms(member.second.get(), next_leg, last_leg,
auto_wrap, only_need_one, duplicates, result))
return true; /* purecov: inspected */
if (is_seek_done(result, only_need_one)) return false;
}
}
return false;
}
}
/* purecov: begin deadcode */
assert(false);
return true;
/* purecov: end */
}
/**
Does a search on this path, using Json_dom::seek() or
Json_wrapper::seek(), need duplicate elimination?
Duplicate elimination is needed if the path contains multiple
ellipses, or if it contains an auto-wrapping array path leg after an
ellipses. See #Json_wrapper::seek() for more details.
@param begin the beginning of the path
@param end the end of the path (exclusive)
@param auto_wrap true if array auto-wrapping is used
@retval true if duplicate elimination is needed
@retval false if the path won't produce duplicates
*/
static bool path_gives_duplicates(const Json_path_iterator &begin,
const Json_path_iterator &end,
bool auto_wrap) {
auto it = std::find_if(begin, end, [](const Json_path_leg *leg) {
return leg->get_type() == jpl_ellipsis;
});
// If no ellipsis, no duplicates.
if (it == end) return false;
// Otherwise, possibly duplicates if ellipsis or autowrap leg follows.
return std::any_of(it + 1, end, [auto_wrap](const Json_path_leg *leg) {
return leg->get_type() == jpl_ellipsis || (auto_wrap && leg->is_autowrap());
});
}
Json_object::Json_object()
: m_map(Json_object_map::key_compare(),
Json_object_map::allocator_type(key_memory_JSON)) {}
namespace {
/**
This class implements rapidjson's Handler concept to make our own handler
which will construct our DOM from the parsing of the JSON text.
<code>
bool Null() { }
bool Bool(bool) { }
bool Int(int) { }
bool Uint(unsigned) { }
bool Int64(int64_t) { }
bool Uint64(uint64_t) { }
bool Double(double) { }
bool RawNumber(const Ch*, SizeType, bool) { }
bool String(const Ch*, SizeType, bool) { }
bool StartObject() { }
bool Key() { }
bool EndObject(SizeType) { }
bool StartArray() { }
bool EndArray(SizeType) { }
</code>
@see Json_dom::parse
*/
class Rapid_json_handler {
private:
// std::cerr << "callback " << name << ':' << state << '\n'; std::cerr.flush()
#define DUMP_CALLBACK(name, state)
enum enum_state {
expect_anything,
expect_array_value,
expect_object_key,
expect_object_value,
expect_eof
};
enum_state m_state; ///< Tells what kind of value to expect next.
Json_dom_ptr m_dom_as_built; ///< Root of the DOM being built.
Json_dom *m_current_element; ///< The current object/array being parsed.
size_t m_depth; ///< The depth at which parsing currently happens.
std::string m_key; ///< The name of the current member of an object.
public:
explicit Rapid_json_handler(JsonDocumentDepthHandler m_depth_handler)
: m_state(expect_anything),
m_dom_as_built(nullptr),
m_current_element(nullptr),
m_depth(0),
m_key(),
m_depth_handler(std::move(m_depth_handler)) {}
/**
@returns The built JSON DOM object.
Deallocation of the returned value is the responsibility of the caller.
*/
Json_dom_ptr get_built_doc() { return std::move(m_dom_as_built); }
private:
/**
Function which is called on each value found in the JSON
document being parsed.
@param[in] value the value that was seen
@return true if parsing should continue, false if an error was
found and parsing should stop
*/
bool seeing_value(Json_dom_ptr value) {
if (value == nullptr) return false; /* purecov: inspected */
switch (m_state) {
case expect_anything:
m_dom_as_built = std::move(value);
m_state = expect_eof;
return true;
case expect_array_value: {
auto array = down_cast<Json_array *>(m_current_element);
if (array->append_alias(std::move(value)))
return false; /* purecov: inspected */
return true;
}
case expect_object_value: {
m_state = expect_object_key;
auto object = down_cast<Json_object *>(m_current_element);
return !object->add_alias(m_key, std::move(value));
}
default:
/* purecov: begin inspected */
assert(false);
return false;
/* purecov: end */
}
}
public:
bool Null() {
DUMP_CALLBACK("null", state);
return seeing_value(create_dom_ptr<Json_null>());
}
bool Bool(bool b) {
DUMP_CALLBACK("bool", state);
return seeing_value(create_dom_ptr<Json_boolean>(b));
}
bool Int(int i) {
DUMP_CALLBACK("int", state);
return seeing_value(create_dom_ptr<Json_int>(i));
}
bool Uint(unsigned u) {
DUMP_CALLBACK("uint", state);
return seeing_value(create_dom_ptr<Json_int>(static_cast<longlong>(u)));
}
bool Int64(int64_t i) {
DUMP_CALLBACK("int64", state);
return seeing_value(create_dom_ptr<Json_int>(i));
}
bool Uint64(uint64_t ui64) {
DUMP_CALLBACK("uint64", state);
return seeing_value(create_dom_ptr<Json_uint>(ui64));
}
bool Double(double d) {
DUMP_CALLBACK("double", state);
/*
We only accept finite values. RapidJSON normally stops non-finite values
from getting here, but sometimes +/-inf values could end up here anyway.
*/
if (!std::isfinite(d)) return false;
return seeing_value(create_dom_ptr<Json_double>(d));
}
/* purecov: begin deadcode */
bool RawNumber(const char *, rapidjson::SizeType, bool) {
/*
Never called, since we don't instantiate the parser with
kParseNumbersAsStringsFlag.
*/
assert(false);
return false;
}
/* purecov: end */
bool String(const char *str, rapidjson::SizeType length, bool) {
DUMP_CALLBACK("string", state);
return seeing_value(create_dom_ptr<Json_string>(str, length));
}
bool StartObject() {
DUMP_CALLBACK("start object {", state);
return start_object_or_array(create_dom_ptr<Json_object>(),
expect_object_key);
}
bool EndObject(rapidjson::SizeType) {
DUMP_CALLBACK("} end object", state);
assert(m_state == expect_object_key);
end_object_or_array();
return true;
}
bool StartArray() {
DUMP_CALLBACK("start array [", state);
return start_object_or_array(create_dom_ptr<Json_array>(),
expect_array_value);
}
bool EndArray(rapidjson::SizeType) {
DUMP_CALLBACK("] end array", state);
assert(m_state == expect_array_value);
end_object_or_array();
return true;
}
bool Key(const char *str, rapidjson::SizeType len, bool) {
assert(m_state == expect_object_key);
m_state = expect_object_value;
m_key.assign(str, len);
return true;
}
private:
bool start_object_or_array(Json_dom_ptr value, enum_state next_state) {
Json_dom *dom = value.get();
bool success = seeing_value(std::move(value)) &&
!check_json_depth(++m_depth, m_depth_handler);
m_current_element = dom;
m_state = next_state;
return success;
}
void end_object_or_array() {
m_depth--;
m_current_element = m_current_element->parent();
if (m_current_element == nullptr) {
assert(m_depth == 0);
m_state = expect_eof;
} else if (m_current_element->json_type() == enum_json_type::J_OBJECT)
m_state = expect_object_key;
else {
assert(m_current_element->json_type() == enum_json_type::J_ARRAY);
m_state = expect_array_value;
}
}
JsonDocumentDepthHandler m_depth_handler{nullptr};
};
} // namespace
Json_dom_ptr Json_dom::parse(const char *text, size_t length,
const JsonParseErrorHandler &error_handler,
const JsonDocumentDepthHandler &depth_handler) {
Rapid_json_handler handler(depth_handler);
rapidjson::MemoryStream ss(text, length);
rapidjson::Reader reader;
bool success = reader.Parse<rapidjson::kParseDefaultFlags>(ss, handler);
if (success) return handler.get_built_doc();
// Report the error offset and the error message if requested by the caller.
size_t offset = reader.GetErrorOffset();
const char *syntaxerr =
rapidjson::GetParseError_En(reader.GetParseErrorCode());
error_handler(syntaxerr, offset);
return nullptr;
}
/**
Map the JSON type used by the binary representation to the type
used by Json_dom and Json_wrapper.
Note: Does not look into opaque values to determine if they
represent decimal or date/time values. For that, look into the
Value and retrieve field_type.
@param[in] bintype type of json_binary
@returns the JSON_dom JSON type.
*/
static enum_json_type bjson2json(const json_binary::Value::enum_type bintype) {
enum_json_type res = enum_json_type::J_ERROR;
switch (bintype) {
case json_binary::Value::STRING:
res = enum_json_type::J_STRING;
break;
case json_binary::Value::INT:
res = enum_json_type::J_INT;
break;
case json_binary::Value::UINT:
res = enum_json_type::J_UINT;
break;
case json_binary::Value::DOUBLE:
res = enum_json_type::J_DOUBLE;
break;
case json_binary::Value::LITERAL_TRUE:
case json_binary::Value::LITERAL_FALSE:
res = enum_json_type::J_BOOLEAN;
break;
case json_binary::Value::LITERAL_NULL:
res = enum_json_type::J_NULL;
break;
case json_binary::Value::ARRAY:
res = enum_json_type::J_ARRAY;
break;
case json_binary::Value::OBJECT:
res = enum_json_type::J_OBJECT;
break;
case json_binary::Value::ERROR:
res = enum_json_type::J_ERROR;
break;
case json_binary::Value::OPAQUE:
res = enum_json_type::J_OPAQUE;
break;
}
return res;
}
/// Get string data as std::string from a json_binary::Value.
static std::string get_string_data(const json_binary::Value &v) {
return std::string(v.get_data(), v.get_data_length());
}
Json_dom_ptr Json_dom::parse(const json_binary::Value &v) {
Json_dom_ptr root_dom(json_binary_to_dom_template(v));
if (root_dom == nullptr) return nullptr;
// if v is scalar
if (!v.is_array() && !v.is_object()) return root_dom;
Prealloced_array<std::pair<Json_dom *, const json_binary::Value>, 16> stack{
key_memory_JSON};
if (stack.emplace_back(root_dom.get(), v)) return nullptr;
while (!stack.empty()) {
auto pair = stack.back();
stack.pop_back();
const json_binary::Value &binary_val = pair.second;
bool is_object = binary_val.is_object();
Json_dom *const parent_dom = pair.first;
// Append each element
for (uint32 i = 0; i < binary_val.element_count(); ++i) {
json_binary::Value val = binary_val.element(i);
Json_dom *new_dom = json_binary_to_dom_template(val);
if (is_object) {
if (down_cast<Json_object *>(parent_dom)
->add_alias(get_string_data(binary_val.key(i)), new_dom))
return nullptr;
} else {
if (down_cast<Json_array *>(parent_dom)->append_alias(new_dom))
return nullptr;
}
// if this value is also an object or array, we need to traverse it too
if (val.is_object() || val.is_array())
if (stack.emplace_back(new_dom, val)) return nullptr;
}
}
return root_dom;
}
/**
Create a DOM template for the provided json_binary::Value.
If the binary value represents a scalar, create a Json_dom object
that represents the scalar and return a pointer to it.
If the binary value represents an object or an array, create an
empty Json_object or Json_array object and return a pointer to it.
@param v the binary value to convert to DOM
@return a DOM template for the top-level the binary value, or NULL
if an error is detected.
*/
static Json_dom *json_binary_to_dom_template(const json_binary::Value &v) {
switch (v.type()) {
case json_binary::Value::OBJECT:
return new (std::nothrow) Json_object();
case json_binary::Value::ARRAY:
return new (std::nothrow) Json_array();
case json_binary::Value::DOUBLE:
return new (std::nothrow) Json_double(v.get_double());
case json_binary::Value::INT:
return new (std::nothrow) Json_int(v.get_int64());
case json_binary::Value::UINT:
return new (std::nothrow) Json_uint(v.get_uint64());
case json_binary::Value::LITERAL_FALSE:
return new (std::nothrow) Json_boolean(false);
case json_binary::Value::LITERAL_TRUE:
return new (std::nothrow) Json_boolean(true);
case json_binary::Value::LITERAL_NULL:
return new (std::nothrow) Json_null();
case json_binary::Value::OPAQUE: {
const enum_field_types ftyp = v.field_type();
if (ftyp == MYSQL_TYPE_NEWDECIMAL) {
my_decimal m;
if (Json_decimal::convert_from_binary(v.get_data(), v.get_data_length(),
&m))
return nullptr; /* purecov: inspected */
return new (std::nothrow) Json_decimal(m);
}
if (ftyp == MYSQL_TYPE_DATE || ftyp == MYSQL_TYPE_TIME ||
ftyp == MYSQL_TYPE_DATETIME || ftyp == MYSQL_TYPE_TIMESTAMP) {
MYSQL_TIME t;
Json_datetime::from_packed(v.get_data(), ftyp, &t);
return new (std::nothrow) Json_datetime(t, ftyp);
}
return new (std::nothrow)
Json_opaque(v.field_type(), v.get_data(), v.get_data_length());
}
case json_binary::Value::STRING:
return new (std::nothrow) Json_string(v.get_data(), v.get_data_length());
case json_binary::Value::ERROR:
break; /* purecov: inspected */
}
/* purecov: begin inspected */
my_error(ER_INVALID_JSON_BINARY_DATA, MYF(0));
return nullptr;
/* purecov: end */
}
namespace {
/**
Functor which compares a child DOM of a JSON array or JSON object
for equality.
*/
struct Json_child_equal {
const Json_dom *const m_ptr;
bool operator()(const Json_dom_ptr &dom) const { return dom.get() == m_ptr; }
bool operator()(const Json_object_map::value_type &member) const {
return member.second.get() == m_ptr;
}
};
} // namespace
void Json_array::replace_dom_in_container(const Json_dom *oldv,
Json_dom_ptr newv) {
auto it = std::find_if(m_v.begin(), m_v.end(), Json_child_equal{oldv});
if (it != m_v.end()) {
newv->set_parent(this);
*it = std::move(newv);
}
}
void Json_object::replace_dom_in_container(const Json_dom *oldv,
Json_dom_ptr newv) {
auto it = std::find_if(m_map.begin(), m_map.end(), Json_child_equal{oldv});
if (it != m_map.end()) {
newv->set_parent(this);
it->second = std::move(newv);
}
}
bool Json_object::add_alias(const std::string &key, Json_dom_ptr value) {
if (!value) return true; /* purecov: inspected */
// We have taken over the ownership of this value.
value->set_parent(this);
/*
Insert the key and the value into the map. If we have already an element
with this key, the old value is replaced. Note we compare utf-8 bytes
directly here. It's complicated when you take into account composed
and decomposed forms of accented characters and ligatures: different
sequences might encode the same glyphs but we ignore that for now. For
example, the code point U+006E (the Latin lowercase "n") followed by
U+0303 (the combining tilde) is defined by Unicode to be canonically
equivalent to the single code point U+00F1 (the lowercase letter of the
Spanish alphabet). For now, users must normalize themselves to avoid
element dups.
This is what ECMAscript does also: "Two IdentifierName that are
canonically equivalent according to the Unicode standard are not equal
unless they are represented by the exact same sequence of code units (in
other words, conforming ECMAScript implementations are only required to
do bitwise comparison on IdentifierName values). The intent is that the
incoming source text has been converted to normalised form C before it
reaches the compiler." (ECMA-262 5.1 edition June 2011)
See WL-2048 Add function for Unicode normalization
*/
m_map.emplace(key, nullptr).first->second = std::move(value);
return false;
}
#ifdef MYSQL_SERVER
bool Json_object::consume(Json_object_ptr other) {
for (auto &other_member : other->m_map) {
auto &key = other_member.first;
auto &other_value = other_member.second;
auto it = m_map.find(key);
if (it == m_map.end()) {
// The key does not exist in this object, so add the key/value pair.
if (add_alias(key, std::move(other_value)))
return true; /* purecov: inspected */
} else {
/*
Oops. Duplicate key. Merge the values.
This is where the recursion in JSON_MERGE() occurs.
*/
it->second = merge_doms(std::move(it->second), std::move(other_value));
if (it->second == nullptr) return true; /* purecov: inspected */
it->second->set_parent(this);
}
}
return false;
}
#endif // ifdef MYSQL_SERVER
template <typename Key>
static Json_dom *json_object_get(const Json_dom *object [[maybe_unused]],
const Json_object_map &map, const Key &key) {
const Json_object_map::const_iterator iter = map.find(key);
if (iter != map.end()) {
assert(iter->second->parent() == object);
return iter->second.get();
}
return nullptr;
}
Json_dom *Json_object::get(const std::string &key) const {
return json_object_get(this, m_map, key);
}
Json_dom *Json_object::get(const MYSQL_LEX_CSTRING &key) const {
return json_object_get(this, m_map, key);
}
bool Json_object::remove(const std::string &key) {
auto it = m_map.find(key);
if (it == m_map.end()) return false;
m_map.erase(it);
return true;
}
size_t Json_object::cardinality() const { return m_map.size(); }
uint32 Json_object::depth() const {
uint deepest_child = 0;
for (Json_object_map::const_iterator iter = m_map.begin();
iter != m_map.end(); ++iter) {
deepest_child = std::max(deepest_child, iter->second->depth());
}
return 1 + deepest_child;
}
Json_dom_ptr Json_object::clone() const {
Json_object_ptr o = create_dom_ptr<Json_object>();
if (o == nullptr) return nullptr; /* purecov: inspected */
for (const auto &member : m_map) {
if (o->add_clone(member.first, member.second.get()))
return nullptr; /* purecov: inspected */
}
return o;
}
bool Json_object::merge_patch(Json_object_ptr patch) {
for (auto &member : patch->m_map) {
// Remove the member if the value in the patch is the null literal.
if (member.second->json_type() == enum_json_type::J_NULL) {
remove(member.first);
continue;
}
// See if the target has this member, add it if not.
Json_dom_ptr &target = m_map.emplace(member.first, nullptr).first->second;
/*
If the value in the patch is not an object and not the null
literal, the new value is the patch.
*/
if (member.second->json_type() != enum_json_type::J_OBJECT) {
target = std::move(member.second);
target->set_parent(this);
continue;
}
/*
If there is no target value, or if the target value is not an
object, use an empty object as the target value.
*/
if (target == nullptr || target->json_type() != enum_json_type::J_OBJECT)
target = create_dom_ptr<Json_object>();
// Recursively merge the target value with the patch.
Json_object *target_obj = down_cast<Json_object *>(target.get());
Json_object_ptr patch_obj(
down_cast<Json_object *>(member.second.release()));
if (target_obj == nullptr || target_obj->merge_patch(std::move(patch_obj)))
return true; /* purecov: inspected */
target->set_parent(this);
}
return false;
}
/**
Compare two keys from a JSON object and determine whether or not the
first key is less than the second key. key1 is considered less than
key2 if
a) key1 is shorter than key2, or if
b) key1 and key2 have the same length, but different contents, and
the first byte that differs has a smaller value in key1 than in key2
Otherwise, key1 is not less than key2.
@param key1 the first key to compare
@param length1 the length of the first key
@param key2 the second key to compare
@param length2 the length of the second key
@return true if key1 is considered less than key2, false otherwise
*/
static bool json_key_less(const char *key1, size_t length1, const char *key2,
size_t length2) {
if (length1 != length2) return length1 < length2;
return memcmp(key1, key2, length1) < 0;
}
bool Json_key_comparator::operator()(const std::string &key1,
const std::string &key2) const {
return json_key_less(key1.data(), key1.length(), key2.data(), key2.length());
}
bool Json_key_comparator::operator()(const MYSQL_LEX_CSTRING &key1,
const std::string &key2) const {
return json_key_less(key1.str, key1.length, key2.data(), key2.length());
}
bool Json_key_comparator::operator()(const std::string &key1,
const MYSQL_LEX_CSTRING &key2) const {
return json_key_less(key1.data(), key1.length(), key2.str, key2.length);
}
Json_array::Json_array() : m_v(Malloc_allocator<Json_dom *>(key_memory_JSON)) {}
bool Json_array::consume(Json_array_ptr other) {
// We've promised to delete other before returning.
m_v.reserve(size() + other->size());
for (auto &elt : other->m_v) {
if (append_alias(std::move(elt))) return true; /* purecov: inspected */
}
return false;
}
bool Json_array::insert_alias(size_t index, Json_dom_ptr value) {
if (!value) return true; /* purecov: inspected */
/*
Insert the value at the given index, or at the end of the array if the
index points past the end of the array.
*/
auto pos = m_v.begin() + std::min(m_v.size(), index);
value->set_parent(this);
m_v.emplace(pos, std::move(value));
return false;
}
bool Json_array::remove(size_t index) {
if (index < m_v.size()) {
m_v.erase(m_v.begin() + index);
return true;
}
return false;
}
uint32 Json_array::depth() const {
uint deepest_child = 0;