File: item_json_func.h

package info (click to toggle)
mysql-8.0 8.0.44-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,272,892 kB
  • sloc: cpp: 4,685,345; ansic: 412,712; pascal: 108,395; java: 83,641; perl: 30,221; cs: 27,067; sql: 26,594; python: 21,816; sh: 17,285; yacc: 17,169; php: 11,522; xml: 7,388; javascript: 7,083; makefile: 1,793; lex: 1,075; awk: 670; asm: 520; objc: 183; ruby: 97; lisp: 86
file content (1254 lines) | stat: -rw-r--r-- 42,010 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
#ifndef ITEM_JSON_FUNC_INCLUDED
#define ITEM_JSON_FUNC_INCLUDED

/* Copyright (c) 2015, 2025, 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 <assert.h>
#include <sys/types.h>

#include <cstddef>
#include <cstdint>
#include <memory>
#include <utility>  // std::forward

#include "m_ctype.h"

#include "my_inttypes.h"
#include "my_time.h"
#include "mysql/udf_registration_types.h"
#include "mysql_com.h"
#include "mysql_time.h"
#include "prealloced_array.h"      // Prealloced_array
#include "sql-common/json_path.h"  // Json_path
#include "sql/enum_query_type.h"
#include "sql/field.h"
#include "sql/item.h"
#include "sql/item_cmpfunc.h"
#include "sql/item_func.h"
#include "sql/item_strfunc.h"    // Item_str_func
#include "sql/mem_root_array.h"  // Mem_root_array
#include "sql/parse_location.h"  // POS
#include "sql/psi_memory_key.h"  // key_memory_JSON
#include "sql_string.h"

class Json_schema_validator;
class Json_array;
class Json_dom;
class Json_scalar_holder;
class Json_wrapper;
class PT_item_list;
class THD;
class my_decimal;
enum Cast_target : unsigned char;
enum class Json_on_response_type : uint16;
struct Cast_type;
struct TABLE;

/** For use by JSON_CONTAINS_PATH() and JSON_SEARCH() */
enum enum_one_or_all_type {
  ooa_one,
  ooa_all,
  ooa_null,
  ooa_error,
  ooa_uninitialized
};

/**
  Path cache for JSON functions. Caches parsed path
  objects for arguments which are string literals.
  Maintains a vector of path objects and an array of
  ints which map path argument numbers to slots in
  the array.
*/
class Json_path_cache {
 private:
  /// Holder for path strings.
  String m_path_value;

  /// List of paths.
  Prealloced_array<Json_path, 8> m_paths;

  /// Enum that tells the status of a cell in m_paths.
  enum class enum_path_status : uint8 {
    UNINITIALIZED,
    OK_NOT_NULL,
    OK_NULL,
  };

  /// Struct that points to a cell in m_paths and tells its status.
  struct Path_cell {
    enum_path_status m_status = enum_path_status::UNINITIALIZED;
    size_t m_index = 0;
  };

  /// Map argument indexes to indexes into m_paths.
  Mem_root_array<Path_cell> m_arg_idx_to_vector_idx;

 public:
  Json_path_cache(THD *thd, uint size);
  ~Json_path_cache();

  /**
    Parse a path expression if necessary. Does nothing if the path
    expression is constant and it has already been parsed. Assumes that
    we've already verified that the path expression is not null. Raises an
    error if the path expression is syntactically incorrect. Raises an
    error if the path expression contains wildcard tokens but is not
    supposed to. Otherwise puts the parsed path onto the
    path vector.

    @param[in]  thd              THD handle
    @param[in]  args             Array of args to a JSON function
    @param[in]  arg_idx          Index of the path_expression in args
    @param[in]  forbid_wildcards True if the path shouldn't contain * or **

    @returns false on success (valid path or NULL), true on error
  */
  bool parse_and_cache_path(const THD *thd, Item **args, uint arg_idx,
                            bool forbid_wildcards);

  /**
    Return an already parsed path expression.

    @param[in]  arg_idx   Index of the path_expression in the JSON function args

    @returns the already parsed path, possibly NULL
  */
  const Json_path *get_path(uint arg_idx) const;

  /**
    Reset the cache for re-use when a statement is re-executed.
  */
  void reset_cache();
};

/* JSON function support  */

/**
  Base class for all item functions that a return JSON value
*/
class Item_json_func : public Item_func {
  /// Can this function type be used in partial update?
  virtual bool can_use_in_partial_update() const { return false; }

 protected:
  /// String used when reading JSON binary values or JSON text values.
  String m_value;
  /// String used for converting JSON text values to utf8mb4 charset.
  String m_conversion_buffer;
  /// String used for converting a JSON value to text in val_str().
  String m_string_buffer;

  // Cache for constant path expressions
  Json_path_cache m_path_cache;

  /**
    Target column for partial update, if this function is used in an
    update statement and partial update can be used.
  */
  const Field_json *m_partial_update_column = nullptr;

 public:
  /**
    Construct an Item_json_func instance.
    @param thd   THD handle
    @param parent_args  arguments to forward to Item_func's constructor
  */
  template <typename... Args>
  Item_json_func(THD *thd, Args &&...parent_args)
      : Item_func(std::forward<Args>(parent_args)...),
        m_path_cache(thd, arg_count) {
    set_data_type_json();
  }

  bool resolve_type(THD *) override {
    set_nullable(true);
    return false;
  }
  enum Item_result result_type() const override { return STRING_RESULT; }
  String *val_str(String *arg) override;
  bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override;
  bool get_time(MYSQL_TIME *ltime) override;
  longlong val_int() override;
  double val_real() override;
  my_decimal *val_decimal(my_decimal *decimal_value) override;

  void cleanup() override;

  Item_result cast_to_int_type() const override { return INT_RESULT; }

  /**
    Does this function call support partial update of the given JSON column?

    JSON_SET, JSON_REPLACE and JSON_REMOVE support partial update of a JSON
    column if the JSON column is the first argument of the function call, or if
    the first argument is a sequence of nested JSON_SET, JSON_REPLACE and
    JSON_REMOVE calls in which the JSON column is the first argument of the
    inner function call.

    For example, this expression can be used to partially update column
    `json_col`:

        JSON_SET(JSON_REPLACE(json_col, path1, val1), path2, val2)
  */
  bool supports_partial_update(const Field_json *field) const override;

  /**
    Mark this expression as used in partial update. Should only be
    called if #supports_partial_update returns true.
  */
  void mark_for_partial_update(const Field_json *field);
};

bool sql_scalar_to_json(Item *arg, const char *calling_function, String *value,
                        String *tmp, Json_wrapper *wr,
                        Json_scalar_holder *scalar, bool scalar_string);

/**
  Return the JSON value of the argument in a wrapper.

  Handles arguments with type JSON, including array objects (which do
  not report type JSON but rather the type of individual elements).

  Does not handle literals.
  See also get_json_wrapper.

  @param[in]     arg      the argument
  @param[in,out] result   the JSON value wrapper
  @param[out]    has_value true if argument was handled, false otherwise
                           undefined when error
*/
bool json_value(Item *arg, Json_wrapper *result, bool *has_value);

/**
  Return the JSON value of the argument in a wrapper. Abstracts whether
  the value comes from a field or a function or a valid JSON text.

  @param[in]  args          the arguments
  @param[in]  arg_idx       the argument index
  @param[out] str           the string buffer
  @param[in]  func_name     the name of the function we are executing
  @param[out] wrapper       the JSON value wrapper
  @returns false if we found a value or NULL, true if not.
*/
bool get_json_wrapper(Item **args, uint arg_idx, String *str,
                      const char *func_name, Json_wrapper *wrapper);

/**
  Convert Json values or MySQL values to JSON.

  @param[in]     args       arguments to function
  @param[in]     arg_idx    the index of the argument to process
  @param[in]     calling_function    name of the calling function
  @param[in,out] value      working area (if the returned Json_wrapper points
                            to a binary value rather than a DOM, this string
                            will end up holding the binary representation, and
                            it must stay alive until the wrapper is destroyed
                            or converted from binary to DOM)
  @param[in,out] tmp        temporary scratch space for converting strings to
                            the correct charset; only used if accept_string is
                            true and conversion is needed
  @param[in,out] wr         the result wrapper
  @param[in,out] scalar     pointer to pre-allocated memory that can be
                            borrowed by the result wrapper if the result is a
                            scalar. If the pointer is NULL, memory for a
                            scalar result will be allocated on the heap.
  @param[in]                accept_string
                            if true, accept MySQL strings as JSON strings
                            by converting them to UTF8, else emit an error
  @returns false if we found a value or NULL, true otherwise
*/
bool get_json_atom_wrapper(Item **args, uint arg_idx,
                           const char *calling_function, String *value,
                           String *tmp, Json_wrapper *wr,
                           Json_scalar_holder *scalar, bool accept_string);

/**
  Check a non-empty val for character set. If it has character set
  my_charset_binary, signal error and return false. Else, try to convert to
  my_charset_utf8mb4_bin. If this fails, signal error and return true, else
  return false.

  @param[in]     val       the string to be checked
  @param[in,out] buf       buffer to hold the converted string
  @param[out]    resptr    the resulting, possibly converted string,
                           only set if no error
  @param[out]    reslength the length of resptr
  @param[in]     require_string
                           If true, give error messages if binary string. If we
                           see a conversion error (space), we give error
                           notwithstanding this parameter value

  @returns True if the string could not be converted. False on success.
*/
bool ensure_utf8mb4(const String &val, String *buf, const char **resptr,
                    size_t *reslength, bool require_string);

/**
  Represents the JSON function JSON_VALID( <value> )
*/
class Item_func_json_valid final : public Item_int_func {
  String m_value;

 public:
  Item_func_json_valid(const POS &pos, Item *a) : Item_int_func(pos, a) {}

  const char *func_name() const override { return "json_valid"; }

  bool is_bool_func() const override { return true; }

  longlong val_int() override;

  bool resolve_type(THD *thd) override {
    if (param_type_is_default(thd, 0, 1, MYSQL_TYPE_JSON)) return true;
    set_nullable(true);
    return false;
  }
};

/**
  Represents the JSON function JSON_SCHEMA_VALID( <json schema>, <json doc> )
*/
class Item_func_json_schema_valid final : public Item_bool_func {
 public:
  Item_func_json_schema_valid(const POS &pos, Item *a, Item *b);
  ~Item_func_json_schema_valid() override;

  const char *func_name() const override { return "json_schema_valid"; }

  bool val_bool() override;

  longlong val_int() override { return val_bool() ? 1 : 0; }

  bool fix_fields(THD *, Item **) override;

  void cleanup() override;

 private:
  // Wrap the object in a unique_ptr so that the relevant rapidjson destructors
  // are called.
  unique_ptr_destroy_only<const Json_schema_validator>
      m_cached_schema_validator;
};

/**
  Represents the JSON function
  JSON_SCHEMA_VALIDATION_REPORT( <json schema>, <json doc> )
*/
class Item_func_json_schema_validation_report final : public Item_json_func {
 public:
  Item_func_json_schema_validation_report(THD *thd, const POS &pos,
                                          PT_item_list *a);
  ~Item_func_json_schema_validation_report() override;

  const char *func_name() const override {
    return "json_schema_validation_report";
  }

  bool val_json(Json_wrapper *wr) override;

  bool resolve_type(THD *thd) override {
    if (param_type_is_default(thd, 0, 1, MYSQL_TYPE_JSON)) return true;
    set_nullable(true);
    return false;
  }

  bool fix_fields(THD *, Item **) override;

  void cleanup() override;

 private:
  // Wrap the object in a unique_ptr so that the relevant rapidjson destructors
  // are called.
  unique_ptr_destroy_only<const Json_schema_validator>
      m_cached_schema_validator;
};

/**
  Represents the JSON function JSON_CONTAINS()
*/
class Item_func_json_contains final : public Item_int_func {
  String m_doc_value;
  Json_path_cache m_path_cache;

 public:
  Item_func_json_contains(THD *thd, const POS &pos, PT_item_list *a)
      : Item_int_func(pos, a), m_path_cache(thd, arg_count) {}

  const char *func_name() const override { return "json_contains"; }
  enum Functype functype() const override { return JSON_CONTAINS; }
  optimize_type select_optimize(const THD *) override { return OPTIMIZE_KEY; }
  bool gc_subst_analyzer(uchar **) override { return true; }

  bool is_bool_func() const override { return true; }

  longlong val_int() override;

  bool resolve_type(THD *thd) override {
    if (param_type_is_default(thd, 0, 1, MYSQL_TYPE_JSON)) return true;
    if (param_type_is_default(thd, 1, 3)) return true;
    set_nullable(true);
    return false;
  }

  /** Cleanup between executions of the statement */
  void cleanup() override;

  enum_const_item_cache can_cache_json_arg(Item *arg) override {
    return (arg == args[0] || arg == args[1]) ? CACHE_JSON_VALUE : CACHE_NONE;
  }
};

/**
  Represents the JSON function JSON_CONTAINS_PATH()
*/
class Item_func_json_contains_path final : public Item_int_func {
  String m_doc_value;
  enum_one_or_all_type m_cached_ooa;

  // Cache for constant path expressions
  Json_path_cache m_path_cache;

 public:
  Item_func_json_contains_path(THD *thd, const POS &pos, PT_item_list *a)
      : Item_int_func(pos, a),
        m_cached_ooa(ooa_uninitialized),
        m_path_cache(thd, arg_count) {}

  const char *func_name() const override { return "json_contains_path"; }

  bool is_bool_func() const override { return true; }

  longlong val_int() override;

  bool resolve_type(THD *thd) override {
    if (param_type_is_default(thd, 0, 1, MYSQL_TYPE_JSON)) return true;
    if (param_type_is_default(thd, 1, -1)) return true;
    set_nullable(true);
    return false;
  }

  /** Cleanup between executions of the statement */
  void cleanup() override;

  enum_const_item_cache can_cache_json_arg(Item *arg) override {
    return (arg == args[0]) ? CACHE_JSON_VALUE : CACHE_NONE;
  }
};

/**
  Represents the JSON function JSON_TYPE
*/
class Item_func_json_type : public Item_str_func {
  String m_value;

 public:
  Item_func_json_type(const POS &pos, Item *a) : Item_str_func(pos, a) {}

  const char *func_name() const override { return "json_type"; }

  bool resolve_type(THD *) override;

  String *val_str(String *) override;
};

/**
  Represents a "CAST( <value> AS JSON )" coercion.
*/
class Item_typecast_json final : public Item_json_func {
  typedef Item_json_func super;

 public:
  Item_typecast_json(THD *thd, const POS &pos, Item *a)
      : Item_json_func(thd, pos, a) {}

  bool resolve_type(THD *thd) override {
    if (Item_json_func::resolve_type(thd)) return true;
    return args[0]->propagate_type(thd, MYSQL_TYPE_JSON, false, true);
  }

  void print(const THD *thd, String *str,
             enum_query_type query_type) const override;
  const char *func_name() const override { return "cast_as_json"; }
  const char *cast_type() const { return "json"; }
  bool val_json(Json_wrapper *wr) override;
};

/**
  Represents the JSON function JSON_LENGTH()
*/
class Item_func_json_length final : public Item_int_func {
  String m_doc_value;

 public:
  Item_func_json_length(const POS &pos, Item *doc) : Item_int_func(pos, doc) {}

  bool resolve_type(THD *thd) override {
    if (param_type_is_default(thd, 0, 1, MYSQL_TYPE_JSON)) return true;
    if (param_type_is_default(thd, 1, 2)) return true;
    set_nullable(true);
    return false;
  }

  const char *func_name() const override { return "json_length"; }

  longlong val_int() override;
};

/**
  Represents the JSON function JSON_DEPTH()
*/
class Item_func_json_depth final : public Item_int_func {
  String m_doc_value;

 public:
  Item_func_json_depth(const POS &pos, Item *a) : Item_int_func(pos, a) {}

  const char *func_name() const override { return "json_depth"; }

  bool resolve_type(THD *thd) override {
    if (param_type_is_default(thd, 0, 1, MYSQL_TYPE_JSON)) return true;
    set_nullable(true);
    return false;
  }

  longlong val_int() override;
};

/**
  Represents the JSON function JSON_KEYS()
*/
class Item_func_json_keys : public Item_json_func {
  String m_doc_value;

 public:
  Item_func_json_keys(THD *thd, const POS &pos, Item *a)
      : Item_json_func(thd, pos, a) {}

  Item_func_json_keys(THD *thd, const POS &pos, Item *a, Item *b)
      : Item_json_func(thd, pos, a, b) {}

  const char *func_name() const override { return "json_keys"; }

  bool resolve_type(THD *thd) override {
    if (Item_json_func::resolve_type(thd)) return true;
    if (param_type_is_default(thd, 0, 1, MYSQL_TYPE_JSON)) return true;
    if (param_type_is_default(thd, 1, 2)) return true;
    return false;
  }

  bool val_json(Json_wrapper *wr) override;
};

/**
  Represents the JSON function JSON_EXTRACT()
*/
class Item_func_json_extract final : public Item_json_func {
  String m_doc_value;

 public:
  Item_func_json_extract(THD *thd, const POS &pos, PT_item_list *a)
      : Item_json_func(thd, pos, a) {}

  Item_func_json_extract(THD *thd, const POS &pos, Item *a, Item *b)
      : Item_json_func(thd, pos, a, b) {}

  const char *func_name() const override { return "json_extract"; }

  bool resolve_type(THD *thd) override {
    if (Item_json_func::resolve_type(thd)) return true;
    if (param_type_is_default(thd, 0, 1, MYSQL_TYPE_JSON)) return true;
    if (param_type_is_default(thd, 1, -1)) return true;
    return false;
  }

  bool val_json(Json_wrapper *wr) override;

  bool eq(const Item *item, bool binary_cmp) const override;
};

/// Base class for all the functions that take a JSON document as the first
/// argument and one of more pairs of a JSON path and a value to insert into the
/// JSON document, and returns the modified JSON document.
class Item_func_modify_json_in_path : public Item_json_func {
 protected:
  template <typename... Args>
  explicit Item_func_modify_json_in_path(Args &&...parent_args)
      : Item_json_func(std::forward<Args>(parent_args)...) {
    // The function does not necessarily return NULL when an argument is NULL.
    // It returns NULL only if the first argument is NULL, or if one of the JSON
    // path arguments is null. The set of tables for which the function is
    // null-rejecting, is calculated in resolve_type() and possibly updated in
    // update_used_tables().
    null_on_null = false;
  }
  String m_doc_value;

 public:
  bool resolve_type(THD *thd) final;
  void update_used_tables() final;

 private:
  /// Calculates the set of tables to return from not_used_tables(). The
  /// returned value is cached by resolve_type() and update_used_tables().
  table_map calculate_not_null_tables() const;
};

/**
  Represents the JSON function JSON_ARRAY_APPEND()
*/
class Item_func_json_array_append final : public Item_func_modify_json_in_path {
 public:
  Item_func_json_array_append(THD *thd, const POS &pos, PT_item_list *a)
      : Item_func_modify_json_in_path(thd, pos, a) {}

  const char *func_name() const override { return "json_array_append"; }

  bool val_json(Json_wrapper *wr) override;
};

/**
  Represents the JSON function JSON_INSERT()
*/
class Item_func_json_insert : public Item_func_modify_json_in_path {
 public:
  Item_func_json_insert(THD *thd, const POS &pos, PT_item_list *a)
      : Item_func_modify_json_in_path(thd, pos, a) {}

  const char *func_name() const override { return "json_insert"; }

  bool val_json(Json_wrapper *wr) override;
};

/**
  Represents the JSON function JSON_ARRAY_INSERT()
*/
class Item_func_json_array_insert final : public Item_func_modify_json_in_path {
 public:
  Item_func_json_array_insert(THD *thd, const POS &pos, PT_item_list *a)
      : Item_func_modify_json_in_path(thd, pos, a) {}

  const char *func_name() const override { return "json_array_insert"; }

  bool val_json(Json_wrapper *wr) override;
};

/**
  Common base class for JSON_SET() and JSON_REPLACE().
*/
class Item_func_json_set_replace : public Item_func_modify_json_in_path {
  /// True if this is JSON_SET, false if it is JSON_REPLACE.
  const bool m_json_set;
  Json_path_clone m_path;
  bool can_use_in_partial_update() const override { return true; }

 protected:
  template <typename... Args>
  explicit Item_func_json_set_replace(bool json_set, Args &&...parent_args)
      : Item_func_modify_json_in_path(std::forward<Args>(parent_args)...),
        m_json_set(json_set),
        m_path(key_memory_JSON) {}

 public:
  bool val_json(Json_wrapper *wr) override;
};

/**
  Represents the JSON function JSON_SET()
*/
class Item_func_json_set final : public Item_func_json_set_replace {
 public:
  template <typename... Args>
  explicit Item_func_json_set(Args &&...parent_args)
      : Item_func_json_set_replace(true, std::forward<Args>(parent_args)...) {}

  const char *func_name() const override { return "json_set"; }
};

/**
  Represents the JSON function JSON_REPLACE()
*/
class Item_func_json_replace final : public Item_func_json_set_replace {
 public:
  template <typename... Args>
  explicit Item_func_json_replace(Args &&...parent_args)
      : Item_func_json_set_replace(false, std::forward<Args>(parent_args)...) {}

  const char *func_name() const override { return "json_replace"; }
};

/**
  Represents the JSON function JSON_ARRAY()
*/
class Item_func_json_array final : public Item_json_func {
 public:
  template <typename... Args>
  explicit Item_func_json_array(Args &&...parent_args)
      : Item_json_func(std::forward<Args>(parent_args)...) {
    // Does not return NULL on NULL input. A NULL argument is interpreted as the
    // JSON null literal.
    null_on_null = false;
  }

  const char *func_name() const override { return "json_array"; }

  bool resolve_type(THD *thd) override {
    if (Item_json_func::resolve_type(thd)) return true;
    if (param_type_is_default(thd, 0, -1)) return true;
    return false;
  }

  bool val_json(Json_wrapper *wr) override;
};

/**
  Represents the JSON function JSON_OBJECT()
*/
class Item_func_json_row_object final : public Item_json_func {
  String tmp_key_value;

 public:
  Item_func_json_row_object(THD *thd, const POS &pos, PT_item_list *a)
      : Item_json_func(thd, pos, a) {
    // Does not return NULL on NULL input. If a key argument is NULL, an error
    // is raised. If a value argument is NULL, it is interpreted as the JSON
    // null literal.
    null_on_null = false;
  }

  const char *func_name() const override { return "json_object"; }

  bool resolve_type(THD *thd) override {
    if (Item_json_func::resolve_type(thd)) return true;
    if (param_type_is_default(thd, 0, -1)) return true;
    return false;
  }

  bool val_json(Json_wrapper *wr) override;
};

/**
  Represents the JSON function JSON_SEARCH()
*/
class Item_func_json_search : public Item_json_func {
  String m_doc_value;
  enum_one_or_all_type m_cached_ooa;

  // LIKE machinery
  Item_string *m_source_string_item;
  Item_func_like *m_like_node;

 public:
  /**
    Construct a JSON_SEARCH() node.

    @param parent_args arguments to pass to Item_json_func's constructor
  */
  template <typename... Args>
  Item_func_json_search(Args &&...parent_args)
      : Item_json_func(std::forward<Args>(parent_args)...),
        m_cached_ooa(ooa_uninitialized) {}

  const char *func_name() const override { return "json_search"; }

  bool val_json(Json_wrapper *wr) override;

  /**
    Bind logic for the JSON_SEARCH() node.
  */
  bool fix_fields(THD *, Item **) override;

  bool resolve_type(THD *thd) override {
    if (Item_json_func::resolve_type(thd)) return true;
    if (param_type_is_default(thd, 0, 1, MYSQL_TYPE_JSON)) return true;
    if (param_type_is_default(thd, 1, -1)) return true;
    return false;
  }

  void cleanup() override;
};

/**
  Represents the JSON function JSON_REMOVE()
*/
class Item_func_json_remove : public Item_json_func {
  String m_doc_value;
  bool can_use_in_partial_update() const override { return true; }

 public:
  template <typename... Args>
  Item_func_json_remove(Args &&...parent_args)
      : Item_json_func(std::forward<Args>(parent_args)...) {}

  const char *func_name() const override { return "json_remove"; }

  bool resolve_type(THD *thd) override {
    if (Item_json_func::resolve_type(thd)) return true;
    if (param_type_is_default(thd, 0, 1, MYSQL_TYPE_JSON)) return true;
    if (param_type_is_default(thd, 1, -1)) return true;
    return false;
  }

  bool val_json(Json_wrapper *wr) override;
};

/**
  Represents the JSON function JSON_MERGE_PRESERVE.
*/
class Item_func_json_merge_preserve : public Item_json_func {
 public:
  Item_func_json_merge_preserve(THD *thd, const POS &pos, PT_item_list *a)
      : Item_json_func(thd, pos, a) {}

  const char *func_name() const override { return "json_merge_preserve"; }

  bool resolve_type(THD *thd) override {
    if (Item_json_func::resolve_type(thd)) return true;
    if (param_type_is_default(thd, 0, -1, MYSQL_TYPE_JSON)) return true;
    return false;
  }

  bool val_json(Json_wrapper *wr) override;
};

/**
  Represents the JSON function JSON_MERGE. It is a deprecated alias
  for JSON_MERGE_PRESERVE.
*/
class Item_func_json_merge : public Item_func_json_merge_preserve {
 public:
  Item_func_json_merge(THD *thd, const POS &pos, PT_item_list *a);

  bool is_deprecated() const override { return true; }
};

/**
  Represents the JSON function JSON_MERGE_PATCH.
*/
class Item_func_json_merge_patch : public Item_json_func {
 public:
  Item_func_json_merge_patch(THD *thd, const POS &pos, PT_item_list *a)
      : Item_json_func(thd, pos, a) {}

  const char *func_name() const override { return "json_merge_patch"; }

  bool resolve_type(THD *thd) override {
    if (Item_json_func::resolve_type(thd)) return true;
    if (param_type_is_default(thd, 0, -1, MYSQL_TYPE_JSON)) return true;
    return false;
  }

  bool val_json(Json_wrapper *wr) override;
};

/**
  Represents the JSON function JSON_QUOTE()
*/
class Item_func_json_quote : public Item_str_func {
  String m_value;

 public:
  Item_func_json_quote(const POS &pos, PT_item_list *a)
      : Item_str_func(pos, a) {}

  const char *func_name() const override { return "json_quote"; }

  bool resolve_type(THD *thd) override {
    if (param_type_is_default(thd, 0, -1)) return true;
    set_nullable(true);

    /*
     Any interior character could be replaced by a 6 character
     escape sequence. Plus we will add 2 framing quote characters.
    */
    uint32 max_char_length = (6 * args[0]->max_char_length()) + 2;
    set_data_type_string(max_char_length, &my_charset_utf8mb4_bin);
    return false;
  }

  String *val_str(String *tmpspace) override;
};

/**
  Represents the JSON function JSON_UNQUOTE()
*/
class Item_func_json_unquote : public Item_str_func {
  String m_value;
  String m_conversion_buffer;

 public:
  Item_func_json_unquote(const POS &pos, PT_item_list *a)
      : Item_str_func(pos, a) {}

  Item_func_json_unquote(const POS &pos, Item *a) : Item_str_func(pos, a) {}

  const char *func_name() const override { return "json_unquote"; }

  enum Functype functype() const override { return JSON_UNQUOTE_FUNC; }

  bool resolve_type(THD *thd) override {
    if (param_type_is_default(thd, 0, -1)) return true;
    set_nullable(true);
    set_data_type_string(args[0]->max_char_length(), &my_charset_utf8mb4_bin);
    return false;
  }

  String *val_str(String *str) override;
};

/**
  Represents the JSON_PRETTY function.
*/
class Item_func_json_pretty final : public Item_str_func {
 public:
  Item_func_json_pretty(const POS &pos, Item *a) : Item_str_func(pos, a) {}

  const char *func_name() const override { return "json_pretty"; }

  bool resolve_type(THD *thd) override {
    if (param_type_is_default(thd, 0, -1, MYSQL_TYPE_JSON)) return true;
    set_data_type_string(MAX_BLOB_WIDTH, &my_charset_utf8mb4_bin);
    return false;
  }

  String *val_str(String *str) override;
};

/**
  Class that represents the function JSON_STORAGE_SIZE.
*/
class Item_func_json_storage_size final : public Item_int_func {
 public:
  Item_func_json_storage_size(const POS &pos, Item *a)
      : Item_int_func(pos, a) {}
  const char *func_name() const override { return "json_storage_size"; }

  bool resolve_type(THD *thd) override {
    if (param_type_is_default(thd, 0, -1, MYSQL_TYPE_JSON)) return true;
    if (Item_int_func::resolve_type(thd)) return true;
    set_nullable(true);
    return false;
  }

  longlong val_int() override;
};

/**
  Class that represents the function JSON_STORAGE_FREE.
*/
class Item_func_json_storage_free final : public Item_int_func {
 public:
  Item_func_json_storage_free(const POS &pos, Item *a)
      : Item_int_func(pos, a) {}
  const char *func_name() const override { return "json_storage_free"; }

  bool resolve_type(THD *thd) override {
    if (param_type_is_default(thd, 0, -1, MYSQL_TYPE_JSON)) return true;
    return false;
  }

  longlong val_int() override;
};

/**
  Class that represents CAST(<expr> AS <type> ARRAY)
*/

class Item_func_array_cast final : public Item_func {
  /// Type to cast to
  Cast_target cast_type;
  /**
    Whether use of CAST(.. AS .. ARRAY) is allowed

    Currently use of CAST(.. AS .. ARRAY) is limited only to CREATE
    TABLE/INDEX. In all other cases an error is thrown. This flag is set to
    true only for allowed cases to ensure allowed function usage.
  */
  bool m_is_allowed{false};

  /**
    An array used by #save_in_field_inner() to store the result of an array cast
    operation. It is cached in the Item in order to avoid the need for
    reallocation on each row.
  */
  unique_ptr_destroy_only<Json_array> m_result_array;

 public:
  Item_func_array_cast(const POS &pos, Item *a, Cast_target type, uint len_arg,
                       uint dec_arg, const CHARSET_INFO *cs_arg);
  ~Item_func_array_cast() override;
  const char *func_name() const override { return "cast_as_array"; }
  enum Functype functype() const override { return TYPECAST_FUNC; }
  bool returns_array() const override { return true; }
  bool val_json(Json_wrapper *wr) override;
  void print(const THD *thd, String *str,
             enum_query_type query_type) const override;
  enum Item_result result_type() const override;
  bool resolve_type(THD *) override;
  Field *tmp_table_field(TABLE *table) override;
  bool fix_fields(THD *thd, Item **ref) override;
  void cleanup() override;
  void allow_array_cast() override { m_is_allowed = true; }
  type_conversion_status save_in_field_inner(Field *field,
                                             bool no_conversions) override;
  // Regular val_x() funcs shouldn't be called
  /* purecov: begin inspected */
  longlong val_int() override {
    assert(false);
    return 0;
  }
  String *val_str(String *) override {
    assert(false);
    return nullptr;
  }
  my_decimal *val_decimal(my_decimal *) override {
    assert(false);
    return nullptr;
  }
  double val_real() override {
    assert(false);
    return 0;
  }
  bool get_date(MYSQL_TIME *, my_time_flags_t) override {
    assert(false);
    return true;
  }
  bool get_time(MYSQL_TIME *) override {
    assert(false);
    return true;
  }
  /* purecov: end */
};

class Item_func_json_overlaps : public Item_bool_func {
 public:
  Item_func_json_overlaps(const POS &pos, Item *a, Item *b)
      : Item_bool_func(pos, a, b) {}
  const char *func_name() const override { return "json_overlaps"; }
  enum Functype functype() const override { return JSON_OVERLAPS; }
  bool gc_subst_analyzer(uchar **) override { return true; }
  optimize_type select_optimize(const THD *) override { return OPTIMIZE_KEY; }
  longlong val_int() override;
  Item *key_item() const override;
  enum_const_item_cache can_cache_json_arg(Item *arg) override {
    return (arg == args[0] || arg == args[1]) ? CACHE_JSON_VALUE : CACHE_NONE;
  }
};

class Item_func_member_of : public Item_bool_func {
 public:
  Item_func_member_of(const POS &pos, Item *a, Item *b)
      : Item_bool_func(pos, a, b) {}
  const char *func_name() const override { return "member of"; }
  enum Functype functype() const override { return MEMBER_OF_FUNC; }
  bool resolve_type(THD *thd) override {
    if (param_type_is_default(thd, 0, 2, MYSQL_TYPE_JSON)) return true;
    args[0]->mark_json_as_scalar();
    return false;
  }
  bool gc_subst_analyzer(uchar **) override { return true; }
  optimize_type select_optimize(const THD *) override { return OPTIMIZE_KEY; }
  longlong val_int() override;
  void print(const THD *thd, String *str,
             enum_query_type query_type) const override;
  Item *key_item() const override { return args[1]; }
  enum_const_item_cache can_cache_json_arg(Item *arg) override {
    return (arg == args[1]) ? CACHE_JSON_VALUE
                            : ((arg == args[0]) ? CACHE_JSON_ATOM : CACHE_NONE);
  }
};

/**
  Class implementing the JSON_VALUE function.

  Functionality-wise it's a combination of CAST, JSON_UNQUOTE and JSON_EXTRACT,
  but with additional functionality for flexible handling of empty values and
  conversion errors.
*/
class Item_func_json_value final : public Item_func {
 public:
  Item_func_json_value(const POS &pos, Item *arg, Item *path,
                       const Cast_type &cast_type, unsigned length,
                       unsigned precision, Json_on_response_type on_empty_type,
                       Item *on_empty_default,
                       Json_on_response_type on_error_type,
                       Item *on_error_default);
  ~Item_func_json_value() override;
  const char *func_name() const override { return "json_value"; }
  enum Item_result result_type() const override;
  bool resolve_type(THD *) override;
  bool fix_fields(THD *thd, Item **ref) override;
  void print(const THD *thd, String *str,
             enum_query_type query_type) const override;
  bool eq(const Item *item, bool binary_cmp) const override;
  bool val_json(Json_wrapper *wr) override;
  String *val_str(String *buffer) override;
  double val_real() override;
  longlong val_int() override;
  my_decimal *val_decimal(my_decimal *value) override;
  bool get_date(MYSQL_TIME *ltime, my_time_flags_t flags) override;
  bool get_time(MYSQL_TIME *ltime) override;

 private:
  /// Represents a default value given in JSON_VALUE's DEFAULT xxx ON EMPTY or
  /// DEFAULT xxx ON ERROR clause.
  struct Default_value;

  /// Parsed path.
  Json_path m_path_json;
  /// Type of the ON EMPTY clause.
  Json_on_response_type m_on_empty;
  /// Type of the ON ERROR clause.
  Json_on_response_type m_on_error;
  /// The default value for ON EMPTY (if not ERROR or NULL ON EMPTY).
  unique_ptr_destroy_only<Default_value> m_default_empty;
  /// The default value for ON EMPTY (if not ERROR or NULL ON EMPTY).
  unique_ptr_destroy_only<Default_value> m_default_error;
  /// The target data type.
  Cast_target m_cast_target;

  /**
    Creates a Json_value_default object representing the default value given in
    a DEFAULT xxx ON EMPTY clause or a DEFAULT xxx ON ERROR clause.

    @param thd       the current session
    @param item      the Item that represents the default value expression
    @return a pointer to the created object on success, nullptr on error
  */
  unique_ptr_destroy_only<Default_value> create_json_value_default(THD *thd,
                                                                   Item *item);

  /**
    Extracts the JSON value at the given path.

    @param[out] json the extracted JSON value, if the path matched exactly
      one value; empty otherwise
    @param[out] return_default the default value to return if a
      DEFAULT ... ON EMPTY or DEFAULT ... ON ERROR clause was invoked,
      or nullptr if no DEFAULT clause was invoked
    @return true if an error was raised, false otherwise
  */
  bool extract_json_value(Json_wrapper *json,
                          const Default_value **return_default);

  /// Implements val_int() for RETURNING SIGNED and RETURNING UNSIGNED.
  int64_t extract_integer_value();
  /// Implements val_int() for RETURNING YEAR
  int64_t extract_year_value();
  /// Implements get_date() for RETURNING DATE.
  bool extract_date_value(MYSQL_TIME *ltime);
  /// Implements get_time() for RETURNING TIME.
  bool extract_time_value(MYSQL_TIME *ltime);
  /// Implements get_date() for RETURNING DATETIME.
  bool extract_datetime_value(MYSQL_TIME *ltime);
  /// Implements val_decimal() for RETURNING DECIMAL.
  my_decimal *extract_decimal_value(my_decimal *value);
  /// Implements val_str() for RETURNING CHAR and RETURNING BINARY.
  String *extract_string_value(String *buffer);
  /// Implements val_real() for RETURNING FLOAT/REAL/DOUBLE.
  double extract_real_value();
};

/**
  Turn a GEOMETRY value into a JSON value per the GeoJSON specification
  revision 1.0. This method is implemented in item_geofunc.cc.

  @param[in,out] wr The wrapper to be stuffed with the JSON value.
  @param[in]     swkb The source GEOMETRY value.
  @param[in]     calling_function Name of user-invoked function (for errors)
  @param[in]     max_decimal_digits See the user documentation for ST_AsGeoJSON.
  @param[in]     add_bounding_box See the user documentation for ST_AsGeoJSON.
  @param[in]     add_short_crs_urn See the user documentation for ST_AsGeoJSON.
  @param[in]     add_long_crs_urn See the user documentation for ST_AsGeoJSON.
  @param[in,out] geometry_srid Spatial Reference System Identifier to be filled
  in.

  @return false if the conversion succeeds, true otherwise
*/
bool geometry_to_json(Json_wrapper *wr, String *swkb,
                      const char *calling_function, int max_decimal_digits,
                      bool add_bounding_box, bool add_short_crs_urn,
                      bool add_long_crs_urn, uint32 *geometry_srid);

/**
  Convert a value represented with an Item to a JSON value

  @param[in]     item      the input value, may be any data type
  @param[in]     func_name for error reporting
  @param[in,out] wr        the result wrapper for the JSON value

  @return false if success, true if error
*/
bool convert_value_to_json(Item *item, const char *func_name, Json_wrapper *wr);
/**
  Convert JSON values or MySQL values to JSON. Converts SQL NULL
  to the JSON null literal.

  @param[in]     args       arguments to function
  @param[in]     arg_idx    the index of the argument to process
  @param[in]     calling_function    name of the calling function
  @param[in,out] value      working area (if the returned Json_wrapper points
                            to a binary value rather than a DOM, this string
                            will end up holding the binary representation, and
                            it must stay alive until the wrapper is destroyed
                            or converted from binary to DOM)
  @param[in,out] tmp        temporary scratch space for converting strings to
                            the correct charset; only used if accept_string is
                            true and conversion is needed
  @param[in,out] wr         the result wrapper
  @returns false if we found a value or NULL, true otherwise
*/
bool get_atom_null_as_null(Item **args, uint arg_idx,
                           const char *calling_function, String *value,
                           String *tmp, Json_wrapper *wr);

/**
  Gets a JSON object member name from an Item. An error is raised if
  the Item evaluates to NULL, or if it cannot be converted to a
  utf8mb4 string.

  @param[in]  thd         THD handle
  @param[in]  arg_item    An argument Item
  @param[out] value       Where to materialize the arg_item's string value
  @param[out] utf8_res    Buffer for use by ensure_utf8mb4.
  @param[out] safep       String pointer after any relevant conversion
  @param[out] safe_length Corresponding string length

  @returns true if the Item is not a utf8mb4 string
*/
bool get_json_object_member_name(const THD *thd, Item *arg_item, String *value,
                                 String *utf8_res, const char **safep,
                                 size_t *safe_length);
using Json_dom_ptr = std::unique_ptr<Json_dom>;

bool parse_json(const String &res, Json_dom_ptr *dom, bool require_str_or_json,
                const JsonParseErrorHandler &error_handler,
                const JsonDocumentDepthHandler &depth_handler);

typedef Prealloced_array<size_t, 16> Sorted_index_array;
bool sort_and_remove_dups(const Json_wrapper &orig, Sorted_index_array *v);

bool save_json_to_field(THD *thd, Field *field, const Json_wrapper *w,
                        bool no_error);
#endif /* ITEM_JSON_FUNC_INCLUDED */