-
Notifications
You must be signed in to change notification settings - Fork 4k
/
Copy pathitem_json_func.cc
5049 lines (4351 loc) · 162 KB
/
item_json_func.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 */
// JSON function items.
#include "sql/item_json_func.h"
#include <assert.h>
#include <algorithm> // std::fill
#include <cstring>
#include <limits>
#include <memory>
#include <new>
#include <string>
#include <utility>
#include <vector>
#include "decimal.h"
#include "field_types.h" // enum_field_types
#include "lex_string.h"
#include "my_alloc.h"
#include "my_dbug.h"
#include "my_sys.h"
#include "mysql/mysql_lex_string.h"
#include "mysql/strings/m_ctype.h"
#include "mysqld_error.h"
#include "prealloced_array.h" // Prealloced_array
#include "scope_guard.h"
#include "sql-common/json_diff.h"
#include "sql-common/json_dom.h"
#include "sql-common/json_path.h"
#include "sql-common/json_schema.h"
#include "sql-common/json_syntax_check.h"
#include "sql-common/my_decimal.h"
#include "sql/current_thd.h" // current_thd
#include "sql/debug_sync.h"
#include "sql/error_handler.h"
#include "sql/field.h"
#include "sql/field_common_properties.h"
#include "sql/item_cmpfunc.h" // Item_func_like
#include "sql/item_create.h"
#include "sql/parser_yystype.h"
#include "sql/psi_memory_key.h" // key_memory_JSON
#include "sql/sql_class.h" // THD
#include "sql/sql_const.h"
#include "sql/sql_error.h"
#include "sql/sql_exception_handler.h" // handle_std_exception
#include "sql/sql_time.h" // field_type_to_timestamp_type
#include "sql/system_variables.h"
#include "sql/table.h"
#include "sql/table_function.h"
#include "sql/thd_raii.h"
#include "sql/thr_malloc.h"
#include "sql_string.h" // stringcmp
#include "string_with_len.h"
#include "template_utils.h" // down_cast
class PT_item_list;
/** Helper routines */
bool ensure_utf8mb4(const String &val, String *buf, const char **resptr,
size_t *reslength, bool require_string) {
const CHARSET_INFO *cs = val.charset();
if (cs == &my_charset_bin) {
if (require_string)
my_error(ER_INVALID_JSON_CHARSET, MYF(0), my_charset_bin.csname);
return true;
}
const char *s = val.ptr();
size_t ss = val.length();
if (my_charset_same(cs, &my_charset_utf8mb4_bin) ||
my_charset_same(cs, &my_charset_utf8mb3_bin) ||
!std::strcmp(cs->csname, "ascii")) {
/*
Character data is directly converted to JSON if the character
set is utf8mb4 or a subset.
*/
} else { // If not, we convert, possibly with loss (best effort).
uint dummy_errors;
if (buf->copy(val.ptr(), val.length(), val.charset(),
&my_charset_utf8mb4_bin, &dummy_errors)) {
return true; /* purecov: inspected */
}
assert(buf->charset() == &my_charset_utf8mb4_bin);
s = buf->ptr();
ss = buf->length();
}
*resptr = s;
*reslength = ss;
return false;
}
/**
Parse a JSON dom out of an argument to a JSON function.
@param[in] res Pointer to string value of arg.
@param[in,out] dom If non-null, we want any text parsed DOM
returned at the location pointed to
@param[in] require_str_or_json If true, generate an error if other types
used as input
@param[in] error_handler Pointer to a function that should handle
reporting of parsing error.
@param[in] depth_handler Pointer to a function that should handle error
occurred when depth is exceeded.
@returns false if the arg parsed as valid JSON, true otherwise
*/
bool parse_json(const String &res, Json_dom_ptr *dom, bool require_str_or_json,
const JsonParseErrorHandler &error_handler,
const JsonErrorHandler &depth_handler) {
char buff[MAX_FIELD_WIDTH];
String utf8_res(buff, sizeof(buff), &my_charset_utf8mb4_bin);
const char *safep; // contents of res, possibly converted
size_t safe_length; // length of safep
if (ensure_utf8mb4(res, &utf8_res, &safep, &safe_length,
require_str_or_json)) {
return true;
}
if (!dom) {
assert(!require_str_or_json);
return !is_valid_json_syntax(safep, safe_length, nullptr, nullptr,
depth_handler);
}
*dom = Json_dom::parse(safep, safe_length, error_handler, depth_handler);
return *dom == nullptr;
}
enum_json_diff_status apply_json_diffs(Field_json *field,
const Json_diff_vector *diffs) {
DBUG_TRACE;
// Cannot apply a diff to NULL.
if (field->is_null()) return enum_json_diff_status::REJECTED;
DBUG_EXECUTE_IF("simulate_oom_in_apply_json_diffs", {
DBUG_SET("+d,simulate_out_of_memory");
DBUG_SET("-d,simulate_oom_in_apply_json_diffs");
});
Json_wrapper doc;
if (field->val_json(&doc))
return enum_json_diff_status::ERROR; /* purecov: inspected */
doc.dbug_print("apply_json_diffs: before-doc", JsonDepthErrorHandler);
// Should we collect logical diffs while applying them?
const bool collect_logical_diffs =
field->table->is_logical_diff_enabled(field);
// Should we try to perform the update in place using binary diffs?
bool binary_inplace_update = field->table->is_binary_diff_enabled(field);
StringBuffer<STRING_BUFFER_USUAL_SIZE> buffer;
for (const Json_diff &diff : *diffs) {
Json_wrapper val = diff.value();
auto &path = diff.path();
if (path.leg_count() == 0) {
/*
Cannot replace the root (then a full update will be used
instead of creating a diff), or insert the root, or remove the
root, so reject this diff.
*/
return enum_json_diff_status::REJECTED;
}
if (collect_logical_diffs)
field->table->add_logical_diff(field, path, diff.operation(), &val);
if (binary_inplace_update) {
if (diff.operation() == enum_json_diff_operation::REPLACE) {
bool partially_updated = false;
bool replaced_path = false;
if (doc.attempt_binary_update(field, path, &val, false, &buffer,
&partially_updated, &replaced_path))
return enum_json_diff_status::ERROR; /* purecov: inspected */
if (partially_updated) {
if (!replaced_path) return enum_json_diff_status::REJECTED;
DBUG_EXECUTE_IF("rpl_row_jsondiff_binarydiff", {
const char act[] =
"now SIGNAL signal.rpl_row_jsondiff_binarydiff_created";
assert(opt_debug_sync_timeout > 0);
assert(!debug_sync_set_action(current_thd, STRING_WITH_LEN(act)));
};);
continue;
}
} else if (diff.operation() == enum_json_diff_operation::REMOVE) {
Json_wrapper_vector hits(key_memory_JSON);
bool found_path = false;
if (doc.binary_remove(field, path, &buffer, &found_path))
return enum_json_diff_status::ERROR; /* purecov: inspected */
if (!found_path) return enum_json_diff_status::REJECTED;
continue;
}
// Couldn't update in place, so try full update.
binary_inplace_update = false;
field->table->disable_binary_diffs_for_current_row(field);
}
Json_dom *dom = doc.to_dom();
if (doc.to_dom() == nullptr)
return enum_json_diff_status::ERROR; /* purecov: inspected */
enum_json_diff_status res = apply_json_diff(diff, dom);
// If the diff was not applied successfully exit with the error status,
// otherwise continue to the next diff
if (res == enum_json_diff_status::ERROR ||
res == enum_json_diff_status::REJECTED) {
return res;
} else {
continue;
}
}
if (field->store_json(&doc) != TYPE_OK)
return enum_json_diff_status::ERROR; /* purecov: inspected */
return enum_json_diff_status::SUCCESS;
}
/**
Get correct blob type of given Field.
A helper function for get_normalized_field_type().
@param arg the field to get blob type of
@returns
correct blob type
*/
static enum_field_types get_real_blob_type(const Field *arg) {
assert(arg);
return blob_type_from_pack_length(arg->pack_length() -
portable_sizeof_char_ptr);
}
/**
Get correct blob type of given Item.
A helper function for get_normalized_field_type().
@param arg the item to get blob type of
@returns
correct blob type
*/
static enum_field_types get_real_blob_type(const Item *arg) {
assert(arg);
/*
TINYTEXT, TEXT, MEDIUMTEXT, and LONGTEXT have type
MYSQL_TYPE_BLOB. We want to treat them like strings. We check
the collation to see if the blob is really a string.
*/
if (arg->collation.collation != &my_charset_bin) return MYSQL_TYPE_VARCHAR;
if (arg->type() == Item::FIELD_ITEM)
return get_real_blob_type((down_cast<const Item_field *>(arg))->field);
return arg->data_type();
}
/**
Get the field type of an item. This function returns the same value
as arg->data_type() in most cases, but in some cases it may return
another field type in order to ensure that the item gets handled the
same way as items of a different type.
*/
static enum_field_types get_normalized_field_type(const Item *arg) {
const enum_field_types ft = arg->data_type();
switch (ft) {
case MYSQL_TYPE_TINY_BLOB:
case MYSQL_TYPE_BLOB:
case MYSQL_TYPE_MEDIUM_BLOB:
case MYSQL_TYPE_LONG_BLOB:
return get_real_blob_type(arg);
default:
break;
}
return ft;
}
bool get_json_object_member_name(const THD *thd, Item *arg_item, String *value,
String *utf8_res, const char **safep,
size_t *safe_length) {
String *const res = arg_item->val_str(value);
if (thd->is_error()) return true;
if (arg_item->null_value) {
my_error(ER_JSON_DOCUMENT_NULL_KEY, MYF(0));
return true;
}
if (ensure_utf8mb4(*res, utf8_res, safep, safe_length, true)) {
return true;
}
return false;
}
/**
A helper method that checks whether or not the given argument can be converted
to JSON. The function only checks the type of the given item, and doesn't do
any parsing or further checking of the item.
@param item The item to be checked
@retval true The item is possibly convertible to JSON
@retval false The item is not convertible to JSON
*/
static bool is_convertible_to_json(const Item *item) {
const enum_field_types field_type = get_normalized_field_type(item);
switch (field_type) {
case MYSQL_TYPE_NULL:
case MYSQL_TYPE_JSON:
return true;
case MYSQL_TYPE_STRING:
case MYSQL_TYPE_VAR_STRING:
case MYSQL_TYPE_VARCHAR:
case MYSQL_TYPE_BLOB:
case MYSQL_TYPE_LONG_BLOB:
case MYSQL_TYPE_MEDIUM_BLOB:
case MYSQL_TYPE_TINY_BLOB:
if (item->type() == Item::FIELD_ITEM) {
const Item_field *fi = down_cast<const Item_field *>(item);
const Field *field = fi->field;
if (field->is_flag_set(ENUM_FLAG) || field->is_flag_set(SET_FLAG)) {
return false;
}
}
return true;
default:
return false;
}
}
/**
Checks if an Item is of a type that is convertible to JSON. An error is raised
if it is not convertible.
*/
static bool check_convertible_to_json(const Item *item, int argument_number,
const char *function_name) {
if (!is_convertible_to_json(item)) {
my_error(ER_INVALID_TYPE_FOR_JSON, MYF(0), argument_number, function_name);
return true;
}
return false;
}
/**
Helper method for Item_func_json_* methods. Check if a JSON item or
JSON text is valid and, for the latter, optionally construct a DOM
tree (i.e. only if valid).
@param[in] args Item_func::args alias
@param[in] arg_idx Index (0-based) of argument into the args array
@param[out] value Alias for @code Item_func_json_*::m_value @endcode
@param[in] func_name Name of the user-invoked JSON_ function
@param[in,out] dom If non-null, we want any text parsed DOM
returned at the location pointed to
@param[in] require_str_or_json
If true, generate an error if other types used
as input
@param[out] valid true if a valid JSON value was found (or NULL),
else false
@returns true iff syntax error *and* dom != null, else false
*/
static bool json_is_valid(Item **args, uint arg_idx, String *value,
const char *func_name, Json_dom_ptr *dom,
bool require_str_or_json, bool *valid) {
Item *const arg_item = args[arg_idx];
const enum_field_types field_type = get_normalized_field_type(arg_item);
if (!is_convertible_to_json(arg_item)) {
if (require_str_or_json) {
*valid = false;
my_error(ER_INVALID_TYPE_FOR_JSON, MYF(0), arg_idx + 1, func_name);
return true;
}
*valid = false;
return false;
} else if (field_type == MYSQL_TYPE_NULL) {
if (arg_item->update_null_value()) return true;
assert(arg_item->null_value);
*valid = true;
return false;
} else if (field_type == MYSQL_TYPE_JSON) {
Json_wrapper w;
// Also sets the null_value flag
*valid = !arg_item->val_json(&w);
return !*valid;
} else {
String *const res = arg_item->val_str(value);
if (current_thd->is_error()) return true;
if (arg_item->null_value) {
*valid = true;
return false;
}
bool parse_error = false;
const bool failure = parse_json(
*res, dom, require_str_or_json,
[&parse_error, arg_idx, func_name](const char *parse_err,
size_t err_offset) {
my_error(ER_INVALID_JSON_TEXT_IN_PARAM, MYF(0), arg_idx + 1,
func_name, parse_err, err_offset, "");
parse_error = true;
},
JsonDepthErrorHandler);
*valid = !failure;
return parse_error;
}
}
bool parse_path(const String &path_value, bool forbid_wildcards,
Json_path *json_path) {
const char *path_chars = path_value.ptr();
size_t path_length = path_value.length();
StringBuffer<STRING_BUFFER_USUAL_SIZE> res(&my_charset_utf8mb4_bin);
if (ensure_utf8mb4(path_value, &res, &path_chars, &path_length, true)) {
return true;
}
// OK, we have a string encoded in utf-8. Does it parse?
size_t bad_idx = 0;
if (parse_path(path_length, path_chars, json_path, &bad_idx)) {
/*
Issue an error message. The last argument is no longer used, but kept to
avoid changing error message format.
*/
my_error(ER_INVALID_JSON_PATH, MYF(0), bad_idx, "");
return true;
}
if (forbid_wildcards && json_path->can_match_many()) {
my_error(ER_INVALID_JSON_PATH_WILDCARD, MYF(0));
return true;
}
return false;
}
/**
Parse a oneOrAll argument.
@param[in] candidate The string to compare to "one" or "all"
@param[in] func_name The name of the calling function
@returns ooa_one, ooa_all, or ooa_error, based on the match
*/
static enum_one_or_all_type parse_one_or_all(const String *candidate,
const char *func_name) {
/*
First convert the candidate to utf8mb4.
A buffer of four bytes is enough to hold the candidate in the common
case ("one" or "all" + terminating NUL character).
We can ignore conversion errors here. If a conversion error should
happen, the converted string will contain a question mark, and we will
correctly raise an error later because no string with a question mark
will match "one" or "all".
*/
StringBuffer<4> utf8str;
uint errors;
if (utf8str.copy(candidate->ptr(), candidate->length(), candidate->charset(),
&my_charset_utf8mb4_bin, &errors))
return ooa_error; /* purecov: inspected */
const char *str = utf8str.c_ptr_safe();
if (!my_strcasecmp(&my_charset_utf8mb4_general_ci, str, "all"))
return ooa_all;
if (!my_strcasecmp(&my_charset_utf8mb4_general_ci, str, "one"))
return ooa_one;
my_error(ER_JSON_BAD_ONE_OR_ALL_ARG, MYF(0), func_name);
return ooa_error;
}
/**
Parse and cache a (possibly constant) oneOrAll argument.
@param[in] thd THD handle.
@param[in] arg The oneOrAll arg passed to the JSON function.
@param[in] cached_ooa Previous result of parsing this arg.
@param[in] func_name The name of the calling JSON function.
@returns ooa_one, ooa_all, ooa_null or ooa_error, based on the match
*/
static enum_one_or_all_type parse_and_cache_ooa(
const THD *thd, Item *arg, enum_one_or_all_type *cached_ooa,
const char *func_name) {
if (arg->const_for_execution()) {
if (*cached_ooa != ooa_uninitialized) {
return *cached_ooa;
}
}
StringBuffer<16> buffer; // larger than common case: three characters + '\0'
String *const one_or_all = arg->val_str(&buffer);
if (thd->is_error()) {
*cached_ooa = ooa_error;
} else if (arg->null_value) {
*cached_ooa = ooa_null;
} else {
*cached_ooa = parse_one_or_all(one_or_all, func_name);
}
return *cached_ooa;
}
/** Json_path_cache */
Json_path_cache::Json_path_cache(THD *thd, uint size)
: m_paths(key_memory_JSON), m_arg_idx_to_vector_idx(thd->mem_root, size) {
reset_cache();
}
Json_path_cache::~Json_path_cache() = default;
bool Json_path_cache::parse_and_cache_path(const THD *thd, Item **args,
uint arg_idx,
bool forbid_wildcards) {
Item *arg = args[arg_idx];
const bool is_constant = arg->const_for_execution();
Path_cell &cell = m_arg_idx_to_vector_idx[arg_idx];
if (is_constant && cell.m_status != enum_path_status::UNINITIALIZED) {
// nothing to do if it has already been parsed
assert(cell.m_status == enum_path_status::OK_NOT_NULL ||
cell.m_status == enum_path_status::OK_NULL);
return false;
}
if (cell.m_status == enum_path_status::UNINITIALIZED) {
cell.m_index = m_paths.size();
if (m_paths.emplace_back(key_memory_JSON))
return true; /* purecov: inspected */
} else {
// re-parsing a non-constant path for the next row
m_paths[cell.m_index].clear();
}
const String *path_value = arg->val_str(&m_path_value);
if (thd->is_error()) return true;
if (arg->null_value) {
cell.m_status = enum_path_status::OK_NULL;
return false;
}
if (parse_path(*path_value, forbid_wildcards, &m_paths[cell.m_index]))
return true;
cell.m_status = enum_path_status::OK_NOT_NULL;
return false;
}
const Json_path *Json_path_cache::get_path(uint arg_idx) const {
const Path_cell &cell = m_arg_idx_to_vector_idx[arg_idx];
if (cell.m_status != enum_path_status::OK_NOT_NULL) {
return nullptr;
}
return &m_paths[cell.m_index];
}
void Json_path_cache::reset_cache() {
std::fill(m_arg_idx_to_vector_idx.begin(), m_arg_idx_to_vector_idx.end(),
Path_cell());
m_paths.clear();
}
/** JSON_*() support methods */
void Item_json_func::cleanup() {
Item_func::cleanup();
m_path_cache.reset_cache();
}
longlong Item_func_json_valid::val_int() {
assert(fixed);
try {
bool ok;
if (json_is_valid(args, 0, &m_value, func_name(), nullptr, false, &ok)) {
return error_int();
}
null_value = args[0]->null_value;
if (null_value || !ok) return 0;
return 1;
} catch (...) {
/* purecov: begin inspected */
handle_std_exception(func_name());
return error_int();
/* purecov: end */
}
}
static bool evaluate_constant_json_schema(
THD *thd, Item *json_schema, Json_schema_validator *cached_schema_validator,
Item **ref) {
assert(is_convertible_to_json(json_schema));
const char *func_name = down_cast<const Item_func *>(*ref)->func_name();
if (json_schema->const_item()) {
String schema_buffer;
String *schema_string = json_schema->val_str(&schema_buffer);
if (thd->is_error()) return true;
if (json_schema->null_value) {
*ref = new (thd->mem_root) Item_null((*ref)->item_name);
if (*ref == nullptr) return true;
} else {
const JsonSchemaDefaultErrorHandler error_handler(func_name);
if (cached_schema_validator->initialize(
thd->mem_root, schema_string->ptr(), schema_string->length(),
error_handler, JsonDepthErrorHandler)) {
return true;
}
}
}
return false;
}
bool Item_func_json_schema_valid::fix_fields(THD *thd, Item **ref) {
if (Item_bool_func::fix_fields(thd, ref)) return true;
// Both arguments must have types that are convertible to JSON.
for (uint i = 0; i < arg_count; ++i)
if (check_convertible_to_json(args[i], i + 1, func_name())) return true;
return evaluate_constant_json_schema(thd, args[0], &m_cached_schema_validator,
ref);
}
void Item_func_json_schema_valid::cleanup() { Item_bool_func::cleanup(); }
Item_func_json_schema_valid::Item_func_json_schema_valid(const POS &pos,
Item *a, Item *b)
: Item_bool_func(pos, a, b) {}
Item_func_json_schema_valid::~Item_func_json_schema_valid() = default;
static bool do_json_schema_validation(
const THD *thd, Item *json_schema, Item *json_document,
const char *func_name, const Json_schema_validator &cached_schema_validator,
bool *null_value, bool *validation_result,
Json_schema_validation_report *validation_report) {
assert(is_convertible_to_json(json_document));
String document_buffer;
String *document_string = json_document->val_str(&document_buffer);
if (thd->is_error()) return true;
if (json_document->null_value) {
*null_value = true;
return false;
}
if (cached_schema_validator.is_initialized()) {
assert(json_schema->const_item());
const JsonSchemaDefaultErrorHandler error_handler(func_name);
if (cached_schema_validator.is_valid(
document_string->ptr(), document_string->length(), error_handler,
JsonDepthErrorHandler, validation_result, validation_report)) {
return true;
}
} else {
// Fields that are a part of constant tables (i.e. primary key lookup) are
// not reported as constant items during fix fields. So while we won't set
// up the cached schema validator during fix_fields, the item will appear as
// const here, and thus failing the assertion if we don't take constant
// tables into account.
assert(!json_schema->const_item() ||
(json_schema->real_item()->type() == Item::FIELD_ITEM &&
down_cast<const Item_field *>(json_schema->real_item())
->m_table_ref->table->const_table));
assert(is_convertible_to_json(json_schema));
String schema_buffer;
String *schema_string = json_schema->val_str(&schema_buffer);
if (thd->is_error()) return true;
if (json_schema->null_value) {
*null_value = true;
return false;
}
const JsonSchemaDefaultErrorHandler error_handler(func_name);
if (is_valid_json_schema(document_string->ptr(), document_string->length(),
schema_string->ptr(), schema_string->length(),
error_handler, JsonDepthErrorHandler,
validation_result, validation_report)) {
return true;
}
}
*null_value = false;
return false;
}
bool Item_func_json_schema_valid::val_bool() {
assert(fixed);
bool validation_result = false;
if (m_in_check_constraint_exec_ctx) {
Json_schema_validation_report validation_report;
if (do_json_schema_validation(current_thd, args[0], args[1], func_name(),
m_cached_schema_validator, &null_value,
&validation_result, &validation_report)) {
return error_bool();
}
if (!null_value && !validation_result) {
my_error(ER_JSON_SCHEMA_VALIDATION_ERROR_WITH_DETAILED_REPORT, MYF(0),
validation_report.human_readable_reason().c_str());
}
} else {
if (do_json_schema_validation(current_thd, args[0], args[1], func_name(),
m_cached_schema_validator, &null_value,
&validation_result, nullptr)) {
return error_bool();
}
}
assert(is_nullable() || !null_value);
return validation_result;
}
bool Item_func_json_schema_validation_report::fix_fields(THD *thd, Item **ref) {
if (Item_json_func::fix_fields(thd, ref)) return true;
// Both arguments must have types that are convertible to JSON.
for (uint i = 0; i < arg_count; ++i)
if (check_convertible_to_json(args[i], i + 1, func_name())) return true;
return evaluate_constant_json_schema(thd, args[0], &m_cached_schema_validator,
ref);
}
void Item_func_json_schema_validation_report::cleanup() {
Item_json_func::cleanup();
}
Item_func_json_schema_validation_report::
Item_func_json_schema_validation_report(THD *thd, const POS &pos,
PT_item_list *a)
: Item_json_func(thd, pos, a) {}
Item_func_json_schema_validation_report::
~Item_func_json_schema_validation_report() = default;
bool Item_func_json_schema_validation_report::val_json(Json_wrapper *wr) {
assert(fixed);
bool validation_result = false;
Json_schema_validation_report validation_report;
if (do_json_schema_validation(current_thd, args[0], args[1], func_name(),
m_cached_schema_validator, &null_value,
&validation_result, &validation_report)) {
return error_json();
}
assert(is_nullable() || !null_value);
std::unique_ptr<Json_object> result(new (std::nothrow) Json_object());
if (result == nullptr) return error_json(); // OOM
Json_boolean *json_validation_result =
new (std::nothrow) Json_boolean(validation_result);
if (result->add_alias("valid", json_validation_result)) return error_json();
if (!validation_result) {
Json_string *json_human_readable_reason = new (std::nothrow)
Json_string(validation_report.human_readable_reason());
if (result->add_alias("reason", json_human_readable_reason))
return error_json(); // OOM
Json_string *json_schema_location =
new (std::nothrow) Json_string(validation_report.schema_location());
if (result->add_alias("schema-location", json_schema_location))
return error_json(); // OOM
Json_string *json_schema_failed_keyword = new (std::nothrow)
Json_string(validation_report.schema_failed_keyword());
if (result->add_alias("schema-failed-keyword", json_schema_failed_keyword))
return error_json(); // OOM
Json_string *json_document_location =
new (std::nothrow) Json_string(validation_report.document_location());
if (result->add_alias("document-location", json_document_location))
return error_json(); // OOM
}
*wr = Json_wrapper(std::move(result));
return false;
}
typedef Prealloced_array<size_t, 16> Sorted_index_array;
void Item_func_json_contains::cleanup() {
Item_int_func::cleanup();
m_path_cache.reset_cache();
}
longlong Item_func_json_contains::val_int() {
assert(fixed);
THD *const thd = current_thd;
try {
Json_wrapper doc_wrapper;
// arg 0 is the document
if (get_json_wrapper(args, 0, &m_doc_value, func_name(), &doc_wrapper) ||
args[0]->null_value) {
return error_int();
}
Json_wrapper containee_wr;
// arg 1 is the possible containee
if (get_json_wrapper(args, 1, &m_doc_value, func_name(), &containee_wr) ||
args[1]->null_value) {
return error_int();
}
if (arg_count == 3) {
// path is specified
if (m_path_cache.parse_and_cache_path(thd, args, 2, true))
return error_int();
const Json_path *path = m_path_cache.get_path(2);
if (path == nullptr) {
return error_int();
}
Json_wrapper_vector v(key_memory_JSON);
if (doc_wrapper.seek(*path, path->leg_count(), &v, true, false))
return error_int(); /* purecov: inspected */
if (v.size() == 0) {
return error_int();
}
bool ret;
if (json_wrapper_contains(v[0], containee_wr, &ret))
return error_int(); /* purecov: inspected */
null_value = false;
return ret;
} else {
bool ret;
if (json_wrapper_contains(doc_wrapper, containee_wr, &ret))
return error_int(); /* purecov: inspected */
null_value = false;
return ret;
}
} catch (...) {
/* purecov: begin inspected */
handle_std_exception(func_name());
return error_int();
/* purecov: end */
}
}
void Item_func_json_contains_path::cleanup() {
Item_int_func::cleanup();
m_path_cache.reset_cache();
m_cached_ooa = ooa_uninitialized;
}
longlong Item_func_json_contains_path::val_int() {
assert(fixed);
longlong result = 0;
null_value = false;
Json_wrapper wrapper;
Json_wrapper_vector hits(key_memory_JSON);
try {
// arg 0 is the document
if (get_json_wrapper(args, 0, &m_doc_value, func_name(), &wrapper) ||
args[0]->null_value) {
return error_int();
}
// arg 1 is the oneOrAll flag
bool require_all;
const THD *const thd = current_thd;
switch (parse_and_cache_ooa(thd, args[1], &m_cached_ooa, func_name())) {
case ooa_all: {
require_all = true;
break;
}
case ooa_one: {
require_all = false;
break;
}
case ooa_null: {
null_value = true;
return 0;
}
default: {
return error_int();
}
}
// the remaining args are paths
for (uint32 i = 2; i < arg_count; ++i) {
if (m_path_cache.parse_and_cache_path(thd, args, i, false))
return error_int();
const Json_path *path = m_path_cache.get_path(i);
if (path == nullptr) {
return error_int();
}
hits.clear();
if (wrapper.seek(*path, path->leg_count(), &hits, true, true))
return error_int(); /* purecov: inspected */
if (hits.size() > 0) {
result = 1;
if (!require_all) {
break;
}
} else {
if (require_all) {
result = 0;
break;
}
}
}
} catch (...) {
/* purecov: begin inspected */
handle_std_exception(func_name());
return error_int();
/* purecov: end */
}
return result;
}
bool json_value(Item *arg, Json_wrapper *result, bool *has_value) {
if (arg->data_type() == MYSQL_TYPE_NULL) {
if (arg->update_null_value()) return true;
assert(arg->null_value);
*has_value = true;
return false;
}
// Give up if this is not a JSON value (including typed arrays)
if (arg->data_type() != MYSQL_TYPE_JSON && !arg->returns_array()) {
*has_value = false;
return false;
}
*has_value = true;
const bool error = arg->val_json(result);
return error;