-
Notifications
You must be signed in to change notification settings - Fork 45
/
Copy pathjson_binary.cc
2155 lines (1888 loc) · 74.5 KB
/
json_binary.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_binary.h"
#include <string.h>
#include <algorithm> // std::min
#include <cassert>
#include <map>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#ifdef MYSQL_SERVER
#include <sys/types.h>
#endif // MYSQL_SERVER
#include "my_byteorder.h"
#include "my_dbug.h"
#include "my_inttypes.h"
#include "mysql/strings/m_ctype.h"
#include "sql-common/json_dom.h" // Json_dom
#include "sql-common/json_error_handler.h"
#include "sql-common/json_syntax_check.h"
#include "sql/sql_const.h"
#include "sql_string.h"
#include "template_utils.h" // down_cast
#ifdef MYSQL_SERVER
#include "my_sys.h"
#include "mysqld_error.h"
#include "sql/check_stack.h"
#include "sql/current_thd.h"
#include "sql/field.h"
#include "sql/table.h"
#endif // MYSQL_SERVER
namespace {
constexpr char JSONB_TYPE_SMALL_OBJECT = 0x0;
constexpr char JSONB_TYPE_LARGE_OBJECT = 0x1;
constexpr char JSONB_TYPE_SMALL_ARRAY = 0x2;
constexpr char JSONB_TYPE_LARGE_ARRAY = 0x3;
constexpr char JSONB_TYPE_LITERAL = 0x4;
constexpr char JSONB_TYPE_INT16 = 0x5;
constexpr char JSONB_TYPE_UINT16 = 0x6;
constexpr char JSONB_TYPE_INT32 = 0x7;
constexpr char JSONB_TYPE_UINT32 = 0x8;
constexpr char JSONB_TYPE_INT64 = 0x9;
constexpr char JSONB_TYPE_UINT64 = 0xA;
constexpr char JSONB_TYPE_DOUBLE = 0xB;
constexpr char JSONB_TYPE_STRING = 0xC;
constexpr char JSONB_TYPE_OPAQUE = 0xF;
constexpr char JSONB_NULL_LITERAL = 0x0;
constexpr char JSONB_TRUE_LITERAL = 0x1;
constexpr char JSONB_FALSE_LITERAL = 0x2;
/*
The size of offset or size fields in the small and the large storage
format for JSON objects and JSON arrays.
*/
constexpr uint8 SMALL_OFFSET_SIZE = 2;
constexpr uint8 LARGE_OFFSET_SIZE = 4;
/*
The size of key entries for objects when using the small storage
format or the large storage format. In the small format it is 4
bytes (2 bytes for key length and 2 bytes for key offset). In the
large format it is 6 (2 bytes for length, 4 bytes for offset).
*/
constexpr uint8 KEY_ENTRY_SIZE_SMALL = 2 + SMALL_OFFSET_SIZE;
constexpr uint8 KEY_ENTRY_SIZE_LARGE = 2 + LARGE_OFFSET_SIZE;
/*
The size of value entries for objects or arrays. When using the
small storage format, the entry size is 3 (1 byte for type, 2 bytes
for offset). When using the large storage format, it is 5 (1 byte
for type, 4 bytes for offset).
*/
constexpr uint8 VALUE_ENTRY_SIZE_SMALL = 1 + SMALL_OFFSET_SIZE;
constexpr uint8 VALUE_ENTRY_SIZE_LARGE = 1 + LARGE_OFFSET_SIZE;
} // namespace
namespace json_binary {
/// Status codes for JSON serialization.
enum enum_serialization_result {
/**
Success. The JSON value was successfully serialized.
*/
OK,
/**
The JSON value was too big to be serialized. If this status code
is returned, and the small storage format is in use, the caller
should retry the serialization with the large storage format. If
this status code is returned, and the large format is in use,
my_error() should be been called.
*/
VALUE_TOO_BIG,
/**
We only have two bytes for the key size. If this status code is returned
my_error() should be called.
*/
JSON_KEY_TOO_BIG,
/**
Some other error occurred. my_error() will have been called with
more specific information about the failure.
*/
FAILURE
};
static enum_serialization_result serialize_json_value(
const Json_dom *dom, size_t type_pos, size_t depth, bool small_parent,
const JsonSerializationErrorHandler &error_handler, String *dest);
bool serialize(const Json_dom *dom,
const JsonSerializationErrorHandler &error_handler,
String *dest) {
// Reset the destination buffer.
dest->length(0);
dest->set_charset(&my_charset_bin);
// Reserve space (one byte) for the type identifier.
if (dest->append('\0')) return true; /* purecov: inspected */
switch (serialize_json_value(dom, /*type_pos=*/0, /*depth=*/0,
/*small_parent=*/false, error_handler, dest)) {
case OK:
return false;
case VALUE_TOO_BIG:
error_handler.ValueTooBig();
return true;
case JSON_KEY_TOO_BIG:
error_handler.KeyTooBig();
return true;
case FAILURE:
return true;
}
return true; /* purecov: deadcode */
}
/**
Reserve space for the given amount of extra bytes at the end of a
String buffer. If the String needs to allocate more memory, it will
grow by at least 50%, to avoid frequent reallocations.
*/
static bool reserve(String *buffer, size_t bytes_needed) {
return buffer->reserve(bytes_needed, buffer->length() / 2);
}
/** Encode a 16-bit int at the end of the destination string. */
bool append_int16(String *dest, int16_t value) {
if (reserve(dest, sizeof(value))) return true; /* purecov: inspected */
int2store(dest->ptr() + dest->length(), value);
dest->length(dest->length() + sizeof(value));
return false;
}
/** Encode a 32-bit int at the end of the destination string. */
static bool append_int32(String *dest, int32 value) {
if (reserve(dest, sizeof(value))) return true; /* purecov: inspected */
int4store(dest->ptr() + dest->length(), value);
dest->length(dest->length() + sizeof(value));
return false;
}
/** Encode a 64-bit int at the end of the destination string. */
static bool append_int64(String *dest, int64 value) {
if (reserve(dest, sizeof(value))) return true; /* purecov: inspected */
int8store(dest->ptr() + dest->length(), value);
dest->length(dest->length() + sizeof(value));
return false;
}
/**
Append an offset or a size to a String.
@param dest the destination String
@param offset_or_size the offset or size to append
@param large if true, use the large storage format (4 bytes);
otherwise, use the small storage format (2 bytes)
@return false if successfully appended, true otherwise
*/
bool append_offset_or_size(String *dest, size_t offset_or_size, bool large) {
if (large)
return append_int32(dest, static_cast<int32>(offset_or_size));
else
return append_int16(dest, static_cast<int16>(offset_or_size));
}
/**
Insert an offset or a size at the specified position in a String. It
is assumed that the String has already allocated enough space to
hold the value.
@param dest the destination String
@param pos the position in the String
@param offset_or_size the offset or size to append
@param large if true, use the large storage format (4 bytes);
otherwise, use the small storage format (2 bytes)
*/
static void insert_offset_or_size(String *dest, size_t pos,
size_t offset_or_size, bool large) {
assert(pos + offset_size(large) <= dest->alloced_length());
write_offset_or_size(dest->ptr() + pos, offset_or_size, large);
}
/**
Write an offset or a size to a char array. The char array is assumed to be
large enough to hold an offset or size value.
@param dest the array to write to
@param offset_or_size the offset or size to write
@param large if true, use the large storage format
*/
void write_offset_or_size(char *dest, size_t offset_or_size, bool large) {
if (large)
int4store(dest, static_cast<uint32>(offset_or_size));
else
int2store(dest, static_cast<uint16>(offset_or_size));
}
/**
Check if the size of a document exceeds the maximum JSON binary size
(4 GB, aka UINT_MAX32). Raise an error if it is too big.
@param size the size of the document
@return true if the document is too big, false otherwise
*/
static bool check_document_size(size_t size) {
if (size > UINT_MAX32) {
/* purecov: begin inspected */
return true;
/* purecov: end */
}
return false;
}
/**
Append a length to a String. The number of bytes used to store the length
uses a variable number of bytes depending on how large the length is. If the
highest bit in a byte is 1, then the length is continued on the next byte.
The least significant bits are stored in the first byte.
@param dest the destination String
@param length the length to write
@return false on success, true on error
*/
static bool append_variable_length(String *dest, size_t length) {
do {
// Filter out the seven least significant bits of length.
uchar ch = (length & 0x7F);
/*
Right-shift length to drop the seven least significant bits. If there
is more data in length, set the high bit of the byte we're writing
to the String.
*/
length >>= 7;
if (length != 0) ch |= 0x80;
if (dest->append(ch)) return true; /* purecov: inspected */
} while (length != 0);
if (check_document_size(dest->length() + length))
return true; /* purecov: inspected */
// Successfully appended the length.
return false;
}
/**
Read a variable length written by append_variable_length().
@param[in] data the buffer to read from
@param[in] data_length the maximum number of bytes to read from data
@param[out] length the length that was read
@param[out] num the number of bytes needed to represent the length
@return false on success, true if the variable length field is ill-formed
*/
static bool read_variable_length(const char *data, size_t data_length,
uint32 *length, uint8 *num) {
/*
It takes five bytes to represent UINT_MAX32, which is the largest
supported length, so don't look any further.
*/
const size_t max_bytes = std::min(data_length, static_cast<size_t>(5));
size_t len = 0;
for (size_t i = 0; i < max_bytes; i++) {
// Get the next 7 bits of the length.
len |= (data[i] & 0x7f) << (7 * i);
if ((data[i] & 0x80) == 0) {
// The length shouldn't exceed 32 bits.
if (len > UINT_MAX32) return true; /* purecov: inspected */
// This was the last byte. Return successfully.
*num = static_cast<uint8>(i + 1);
*length = static_cast<uint32>(len);
return false;
}
}
// No more available bytes. Return true to signal error.
return true; /* purecov: inspected */
}
/**
Check if the specified offset or size is too big to store in the
binary JSON format.
If the small storage format is used, the caller is expected to retry
serialization in the large storage format, so no error is generated
if the offset or size is too big. If the large storage format is
used, an error will be generated if the offset or size is too big.
@param offset_or_size the offset or size to check
@param large if true, we are using the large storage format
for JSON arrays and objects, which allows offsets and sizes that
fit in a uint32; otherwise, we are using the small storage format,
which allow offsets and sizes that fit in a uint16.
@return true if offset_or_size is too big for the format, false
otherwise
*/
static bool is_too_big_for_json(size_t offset_or_size, bool large) {
if (offset_or_size > UINT_MAX16) {
if (!large) return true;
return check_document_size(offset_or_size);
}
return false;
}
/**
Append all the key entries of a JSON object to a destination string.
The key entries are just a series of offset/length pairs that point
to where the actual key names are stored.
@param[in] object the JSON object
@param[out] dest the destination string
@param[in] offset the offset of the first key
@param[in] large if true, the large storage format will be used
@return serialization status
*/
static enum_serialization_result append_key_entries(const Json_object *object,
String *dest, size_t offset,
bool large) {
#ifndef NDEBUG
const std::string *prev_key = nullptr;
#endif
// Add the key entries.
for (Json_object::const_iterator it = object->begin(); it != object->end();
++it) {
const std::string *key = &it->first;
size_t len = key->length();
#ifndef NDEBUG
// Check that the DOM returns the keys in the correct order.
if (prev_key) {
assert(prev_key->length() <= len);
if (len == prev_key->length())
assert(memcmp(prev_key->data(), key->data(), len) < 0);
}
prev_key = key;
#endif
// We only have two bytes for the key size. Check if the key is too big.
if (len > UINT_MAX16) {
return JSON_KEY_TOO_BIG;
}
if (is_too_big_for_json(offset, large))
return VALUE_TOO_BIG; /* purecov: inspected */
if (append_offset_or_size(dest, offset, large) ||
append_int16(dest, static_cast<int16>(len)))
return FAILURE; /* purecov: inspected */
offset += len;
}
return OK;
}
/**
Will a value of the specified type be inlined?
@param type the type to check
@param large true if the large storage format is used
@return true if the value will be inlined
*/
bool inlined_type(uint8_t type, bool large) {
switch (type) {
case JSONB_TYPE_LITERAL:
case JSONB_TYPE_INT16:
case JSONB_TYPE_UINT16:
return true;
case JSONB_TYPE_INT32:
case JSONB_TYPE_UINT32:
return large;
default:
return false;
}
}
/**
Get the size of an offset value.
@param large true if the large storage format is used
@return the size of an offset
*/
uint8_t offset_size(bool large) {
return large ? LARGE_OFFSET_SIZE : SMALL_OFFSET_SIZE;
}
/**
Get the size of a key entry.
@param large true if the large storage format is used
@return the size of a key entry
*/
uint8_t key_entry_size(bool large) {
return large ? KEY_ENTRY_SIZE_LARGE : KEY_ENTRY_SIZE_SMALL;
}
/**
Get the size of a value entry.
@param large true if the large storage format is used
@return the size of a value entry
*/
uint8_t value_entry_size(bool large) {
return large ? VALUE_ENTRY_SIZE_LARGE : VALUE_ENTRY_SIZE_SMALL;
}
/**
Attempt to inline a value in its value entry at the beginning of an
object or an array. This function assumes that the destination
string has already allocated enough space to hold the inlined value.
@param[in] value the JSON value
@param[out] dest the destination string
@param[in] pos the offset where the value should be inlined
@param[in] large true if the large storage format is used
@return true if the value was inlined, false if it was not
*/
bool attempt_inline_value(const Json_dom *value, String *dest, size_t pos,
bool large) {
int32 inlined_val;
char inlined_type;
switch (value->json_type()) {
case enum_json_type::J_NULL:
inlined_val = JSONB_NULL_LITERAL;
inlined_type = JSONB_TYPE_LITERAL;
break;
case enum_json_type::J_BOOLEAN:
inlined_val = down_cast<const Json_boolean *>(value)->value()
? JSONB_TRUE_LITERAL
: JSONB_FALSE_LITERAL;
inlined_type = JSONB_TYPE_LITERAL;
break;
case enum_json_type::J_INT: {
const Json_int *i = down_cast<const Json_int *>(value);
if (!i->is_16bit() && !(large && i->is_32bit()))
return false; // cannot inline this value
inlined_val = static_cast<int32>(i->value());
inlined_type = i->is_16bit() ? JSONB_TYPE_INT16 : JSONB_TYPE_INT32;
break;
}
case enum_json_type::J_UINT: {
const Json_uint *i = down_cast<const Json_uint *>(value);
if (!i->is_16bit() && !(large && i->is_32bit()))
return false; // cannot inline this value
inlined_val = static_cast<int32>(i->value());
inlined_type = i->is_16bit() ? JSONB_TYPE_UINT16 : JSONB_TYPE_UINT32;
break;
}
default:
return false; // cannot inline value of this type
}
(*dest)[pos] = inlined_type;
insert_offset_or_size(dest, pos + 1, inlined_val, large);
return true;
}
/**
Serialize a JSON array at the end of the destination string.
@param array the JSON array to serialize
@param large if true, the large storage format will be used
@param depth the current nesting level
@param error_handler a handler that is invoked if an error occurs
@param dest the destination string
@return serialization status
*/
static enum_serialization_result serialize_json_array(
const Json_array *array, bool large, size_t depth,
const JsonSerializationErrorHandler &error_handler, String *dest) {
if (error_handler.CheckStack()) {
return FAILURE; /* purecov: inspected */
}
const size_t start_pos = dest->length();
const size_t size = array->size();
if (check_json_depth(++depth, error_handler)) {
return FAILURE;
}
if (is_too_big_for_json(size, large)) return VALUE_TOO_BIG;
// First write the number of elements in the array.
if (append_offset_or_size(dest, size, large))
return FAILURE; /* purecov: inspected */
// Reserve space for the size of the array in bytes. To be filled in later.
const size_t size_pos = dest->length();
if (append_offset_or_size(dest, 0, large))
return FAILURE; /* purecov: inspected */
size_t entry_pos = dest->length();
// Reserve space for the value entries at the beginning of the array.
const auto entry_size = value_entry_size(large);
if (dest->fill(dest->length() + size * entry_size, 0))
return FAILURE; /* purecov: inspected */
for (const auto &child : *array) {
const Json_dom *elt = child.get();
if (!attempt_inline_value(elt, dest, entry_pos, large)) {
size_t offset = dest->length() - start_pos;
if (is_too_big_for_json(offset, large)) return VALUE_TOO_BIG;
insert_offset_or_size(dest, entry_pos + 1, offset, large);
auto res = serialize_json_value(elt, entry_pos, depth, !large,
error_handler, dest);
if (res != OK) return res;
}
entry_pos += entry_size;
}
// Finally, write the size of the object in bytes.
size_t bytes = dest->length() - start_pos;
if (is_too_big_for_json(bytes, large))
return VALUE_TOO_BIG; /* purecov: inspected */
insert_offset_or_size(dest, size_pos, bytes, large);
return OK;
}
/**
Serialize a JSON object at the end of the destination string.
@param object the JSON object to serialize
@param large if true, the large storage format will be used
@param depth the current nesting level
@param error_handler a handler that is invoked if an error occurs
@param dest the destination string
@return serialization status
*/
static enum_serialization_result serialize_json_object(
const Json_object *object, bool large, size_t depth,
const JsonSerializationErrorHandler &error_handler, String *dest) {
if (error_handler.CheckStack()) {
return FAILURE; /* purecov: inspected */
}
const size_t start_pos = dest->length();
const size_t size = object->cardinality();
if (check_json_depth(++depth, error_handler)) {
return FAILURE;
}
if (is_too_big_for_json(size, large))
return VALUE_TOO_BIG; /* purecov: inspected */
// First write the number of members in the object.
if (append_offset_or_size(dest, size, large))
return FAILURE; /* purecov: inspected */
// Reserve space for the size of the object in bytes. To be filled in later.
const size_t size_pos = dest->length();
if (append_offset_or_size(dest, 0, large))
return FAILURE; /* purecov: inspected */
const auto key_entry_size = json_binary::key_entry_size(large);
const auto value_entry_size = json_binary::value_entry_size(large);
/*
Calculate the offset of the first key relative to the start of the
object. The first key comes right after the value entries.
*/
const size_t first_key_offset =
dest->length() + size * (key_entry_size + value_entry_size) - start_pos;
// Append all the key entries.
enum_serialization_result res =
append_key_entries(object, dest, first_key_offset, large);
if (res != OK) return res;
const size_t start_of_value_entries = dest->length();
// Reserve space for the value entries. Will be filled in later.
dest->fill(dest->length() + size * value_entry_size, 0);
// Add the actual keys.
for (const auto &member : *object) {
if (dest->append(member.first.c_str(), member.first.length()))
return FAILURE; /* purecov: inspected */
}
// Add the values, and update the value entries accordingly.
size_t entry_pos = start_of_value_entries;
for (const auto &member : *object) {
const Json_dom *child = member.second.get();
if (!attempt_inline_value(child, dest, entry_pos, large)) {
size_t offset = dest->length() - start_pos;
if (is_too_big_for_json(offset, large)) return VALUE_TOO_BIG;
insert_offset_or_size(dest, entry_pos + 1, offset, large);
res = serialize_json_value(child, entry_pos, depth, !large, error_handler,
dest);
if (res != OK) return res;
}
entry_pos += value_entry_size;
}
// Finally, write the size of the object in bytes.
size_t bytes = dest->length() - start_pos;
if (is_too_big_for_json(bytes, large)) return VALUE_TOO_BIG;
insert_offset_or_size(dest, size_pos, bytes, large);
return OK;
}
/**
Serialize a JSON opaque value at the end of the destination string.
@param[in] opaque the JSON opaque value
@param[in] type_pos where to write the type specifier
@param[out] dest the destination string
@return serialization status
*/
static enum_serialization_result serialize_opaque(const Json_opaque *opaque,
size_t type_pos,
String *dest) {
assert(type_pos < dest->length());
if (dest->append(static_cast<char>(opaque->type())) ||
append_variable_length(dest, opaque->size()) ||
dest->append(opaque->value(), opaque->size()))
return FAILURE; /* purecov: inspected */
(*dest)[type_pos] = JSONB_TYPE_OPAQUE;
return OK;
}
/**
Serialize a DECIMAL value at the end of the destination string.
@param[in] jd the DECIMAL value
@param[in] type_pos where to write the type specifier
@param[out] dest the destination string
@return serialization status
*/
static enum_serialization_result serialize_decimal(const Json_decimal *jd,
size_t type_pos,
String *dest) {
// Store DECIMALs as opaque values.
const int bin_size = jd->binary_size();
char buf[Json_decimal::MAX_BINARY_SIZE];
if (jd->get_binary(buf)) return FAILURE; /* purecov: inspected */
Json_opaque o(MYSQL_TYPE_NEWDECIMAL, buf, bin_size);
return serialize_opaque(&o, type_pos, dest);
}
/**
Serialize a DATETIME value at the end of the destination string.
@param[in] jdt the DATETIME value
@param[in] type_pos where to write the type specifier
@param[out] dest the destination string
@return serialization status
*/
static enum_serialization_result serialize_datetime(const Json_datetime *jdt,
size_t type_pos,
String *dest) {
// Store datetime as opaque values.
char buf[Json_datetime::PACKED_SIZE];
jdt->to_packed(buf);
Json_opaque o(jdt->field_type(), buf, sizeof(buf));
return serialize_opaque(&o, type_pos, dest);
}
/**
Serialize a JSON value at the end of the destination string.
Also go back and update the type specifier for the value to specify
the correct type. For top-level documents, the type specifier is
located in the byte right in front of the value. For documents that
are nested within other documents, the type specifier is located in
the value entry portion at the beginning of the parent document.
@param dom the JSON value to serialize
@param type_pos the position of the type specifier to update
@param dest the destination string
@param depth the current nesting level
@param small_parent tells if @a dom is contained in an array or object
which is stored in the small storage format
@param error_handler a handler that is invoked if an error occurs
@return serialization status
*/
static enum_serialization_result serialize_json_value(
const Json_dom *dom, size_t type_pos, size_t depth, bool small_parent,
const JsonSerializationErrorHandler &error_handler, String *dest) {
const size_t start_pos = dest->length();
assert(type_pos < start_pos);
enum_serialization_result result = FAILURE;
switch (dom->json_type()) {
case enum_json_type::J_ARRAY: {
const Json_array *array = down_cast<const Json_array *>(dom);
(*dest)[type_pos] = JSONB_TYPE_SMALL_ARRAY;
result = serialize_json_array(array, /*large=*/false, depth,
error_handler, dest);
/*
If the array was too large to fit in the small storage format,
reset the destination buffer and retry with the large storage
format.
Possible future optimization: Analyze size up front and pick the
correct format on the first attempt, so that we don't have to
redo parts of the serialization.
*/
if (result == VALUE_TOO_BIG) {
// If the parent uses the small storage format, it needs to grow too.
if (small_parent) return VALUE_TOO_BIG;
dest->length(start_pos);
(*dest)[type_pos] = JSONB_TYPE_LARGE_ARRAY;
result = serialize_json_array(array, /*large=*/true, depth,
error_handler, dest);
}
break;
}
case enum_json_type::J_OBJECT: {
const Json_object *object = down_cast<const Json_object *>(dom);
(*dest)[type_pos] = JSONB_TYPE_SMALL_OBJECT;
result = serialize_json_object(object, /*large=*/false, depth,
error_handler, dest);
/*
If the object was too large to fit in the small storage format,
reset the destination buffer and retry with the large storage
format.
Possible future optimization: Analyze size up front and pick the
correct format on the first attempt, so that we don't have to
redo parts of the serialization.
*/
if (result == VALUE_TOO_BIG) {
// If the parent uses the small storage format, it needs to grow too.
if (small_parent) return VALUE_TOO_BIG;
dest->length(start_pos);
(*dest)[type_pos] = JSONB_TYPE_LARGE_OBJECT;
result = serialize_json_object(object, /*large=*/true, depth,
error_handler, dest);
}
break;
}
case enum_json_type::J_STRING: {
const Json_string *jstr = down_cast<const Json_string *>(dom);
size_t size = jstr->size();
if (append_variable_length(dest, size) ||
dest->append(jstr->value().c_str(), size))
return FAILURE; /* purecov: inspected */
(*dest)[type_pos] = JSONB_TYPE_STRING;
result = OK;
break;
}
case enum_json_type::J_INT: {
const Json_int *i = down_cast<const Json_int *>(dom);
longlong val = i->value();
if (i->is_16bit()) {
if (append_int16(dest, static_cast<int16>(val)))
return FAILURE; /* purecov: inspected */
(*dest)[type_pos] = JSONB_TYPE_INT16;
} else if (i->is_32bit()) {
if (append_int32(dest, static_cast<int32>(val)))
return FAILURE; /* purecov: inspected */
(*dest)[type_pos] = JSONB_TYPE_INT32;
} else {
if (append_int64(dest, val)) return FAILURE; /* purecov: inspected */
(*dest)[type_pos] = JSONB_TYPE_INT64;
}
result = OK;
break;
}
case enum_json_type::J_UINT: {
const Json_uint *i = down_cast<const Json_uint *>(dom);
ulonglong val = i->value();
if (i->is_16bit()) {
if (append_int16(dest, static_cast<int16>(val)))
return FAILURE; /* purecov: inspected */
(*dest)[type_pos] = JSONB_TYPE_UINT16;
} else if (i->is_32bit()) {
if (append_int32(dest, static_cast<int32>(val)))
return FAILURE; /* purecov: inspected */
(*dest)[type_pos] = JSONB_TYPE_UINT32;
} else {
if (append_int64(dest, val)) return FAILURE; /* purecov: inspected */
(*dest)[type_pos] = JSONB_TYPE_UINT64;
}
result = OK;
break;
}
case enum_json_type::J_DOUBLE: {
// Store the double in a platform-independent eight-byte format.
const Json_double *d = down_cast<const Json_double *>(dom);
if (reserve(dest, 8)) return FAILURE; /* purecov: inspected */
float8store(dest->ptr() + dest->length(), d->value());
dest->length(dest->length() + 8);
(*dest)[type_pos] = JSONB_TYPE_DOUBLE;
result = OK;
break;
}
case enum_json_type::J_NULL:
if (dest->append(JSONB_NULL_LITERAL))
return FAILURE; /* purecov: inspected */
(*dest)[type_pos] = JSONB_TYPE_LITERAL;
result = OK;
break;
case enum_json_type::J_BOOLEAN: {
char c = (down_cast<const Json_boolean *>(dom)->value())
? JSONB_TRUE_LITERAL
: JSONB_FALSE_LITERAL;
if (dest->append(c)) return FAILURE; /* purecov: inspected */
(*dest)[type_pos] = JSONB_TYPE_LITERAL;
result = OK;
break;
}
case enum_json_type::J_OPAQUE:
result =
serialize_opaque(down_cast<const Json_opaque *>(dom), type_pos, dest);
break;
case enum_json_type::J_DECIMAL:
result = serialize_decimal(down_cast<const Json_decimal *>(dom), type_pos,
dest);
break;
case enum_json_type::J_DATETIME:
case enum_json_type::J_DATE:
case enum_json_type::J_TIME:
case enum_json_type::J_TIMESTAMP:
result = serialize_datetime(down_cast<const Json_datetime *>(dom),
type_pos, dest);
break;
case enum_json_type::J_ERROR:
/* purecov: begin deadcode */
assert(false);
error_handler.InternalError("JSON serialization failed");
return FAILURE;
/* purecov: end */
}
return result;
}
bool Value::is_valid() const {
switch (m_type) {
case ERROR:
return false;
case ARRAY:
// Check that all the array elements are valid.
for (size_t i = 0; i < element_count(); i++)
if (!element(i).is_valid()) return false; /* purecov: inspected */
return true;
case OBJECT: {
/*
Check that all keys and values are valid, and that the keys come
in the correct order.
*/
const char *prev_key = nullptr;
size_t prev_key_len = 0;
for (size_t i = 0; i < element_count(); i++) {
Value k = key(i);
if (!k.is_valid() || !element(i).is_valid())
return false; /* purecov: inspected */
const char *curr_key = k.get_data();
size_t curr_key_len = k.get_data_length();
if (i > 0) {
if (prev_key_len > curr_key_len)
return false; /* purecov: inspected */
if (prev_key_len == curr_key_len &&
(memcmp(prev_key, curr_key, curr_key_len) >= 0))
return false; /* purecov: inspected */
}
prev_key = curr_key;
prev_key_len = curr_key_len;
}
return true;
}
default:
// This is a valid scalar value.
return true;
}
}
/**
Create a Value object that represents an error condition.
*/
static Value err() { return Value(Value::ERROR); }
/**
Parse a JSON scalar value.
@param type the binary type of the scalar
@param data pointer to the start of the binary representation of the scalar
@param len the maximum number of bytes to read from data
@return an object that represents the scalar value
*/
static Value parse_scalar(uint8 type, const char *data, size_t len) {
switch (type) {
case JSONB_TYPE_LITERAL:
if (len < 1) return err(); /* purecov: inspected */
switch (static_cast<uint8>(*data)) {
case JSONB_NULL_LITERAL:
return Value(Value::LITERAL_NULL);
case JSONB_TRUE_LITERAL:
return Value(Value::LITERAL_TRUE);
case JSONB_FALSE_LITERAL:
return Value(Value::LITERAL_FALSE);
default:
return err(); /* purecov: inspected */
}
case JSONB_TYPE_INT16:
if (len < 2) return err(); /* purecov: inspected */
return Value(Value::INT, sint2korr(data));
case JSONB_TYPE_INT32:
if (len < 4) return err(); /* purecov: inspected */
return Value(Value::INT, sint4korr(data));
case JSONB_TYPE_INT64:
if (len < 8) return err(); /* purecov: inspected */
return Value(Value::INT, sint8korr(data));
case JSONB_TYPE_UINT16:
if (len < 2) return err(); /* purecov: inspected */
return Value(Value::UINT, uint2korr(data));
case JSONB_TYPE_UINT32:
if (len < 4) return err(); /* purecov: inspected */
return Value(Value::UINT, uint4korr(data));
case JSONB_TYPE_UINT64:
if (len < 8) return err(); /* purecov: inspected */
return Value(Value::UINT, uint8korr(data));
case JSONB_TYPE_DOUBLE: {
if (len < 8) return err(); /* purecov: inspected */
return Value(float8get(data));
}
case JSONB_TYPE_STRING: {
uint32 str_len;
uint8 n;
if (read_variable_length(data, len, &str_len, &n))
return err(); /* purecov: inspected */
if (len < n + str_len) return err(); /* purecov: inspected */
return Value(data + n, str_len);
}
case JSONB_TYPE_OPAQUE: {
/*
There should always be at least one byte, which tells the field
type of the opaque value.
*/
if (len < 1) return err(); /* purecov: inspected */
// The type is encoded as a uint8 that maps to an enum_field_types.
const uint8 type_byte = static_cast<uint8>(*data);
const enum_field_types field_type =
static_cast<enum_field_types>(type_byte);
// Then there's the length of the value.
uint32 val_len;
uint8 n;
if (read_variable_length(data + 1, len - 1, &val_len, &n))
return err(); /* purecov: inspected */
if (len < 1 + n + val_len) return err(); /* purecov: inspected */
return Value(field_type, data + 1 + n, val_len);
}