Debian Codegraph @

unittest/gunit/json_dom-t.cc

raw symbols SCIP
1 /* Copyright (c) 2015, 2026, Oracle and/or its affiliates.
2
3 This program is free software; you can redistribute it and/or modify
4 it under the terms of the GNU General Public License, version 2.0,
5 as published by the Free Software Foundation.
6
7 This program is designed to work with certain software (including
8 but not limited to OpenSSL) that is licensed under separate terms,
9 as designated in a particular file or component or in included license
10 documentation. The authors of MySQL hereby grant you an additional
11 permission to link the program and your derivative works with the
12 separately licensed software that they have either included with
13 the program or referenced in the documentation.
14
15 This program is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU General Public License, version 2.0, for more details.
19
20 You should have received a copy of the GNU General Public License
21 along with this program; if not, write to the Free Software
22 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
23
24 #include <gtest/gtest.h>
25 #include <cstring>
26 #include <memory>
27
28 #include "base64.h"
29 #include "my_byteorder.h"
30 #include "my_inttypes.h"
31 #include "sql-common/json_binary.h"
32 #include "sql-common/json_dom.h"
33 #include "sql-common/json_path.h"
34 #include "sql/json_diff.h"
35 #include "sql/my_decimal.h"
36 #include "sql/sql_class.h"
37 #include "sql/sql_time.h"
38 #include "sql_string.h"
39 #include "template_utils.h" // down_cast
40 #include "unittest/gunit/base_mock_field.h"
41 #include "unittest/gunit/benchmark.h"
42 #include "unittest/gunit/fake_table.h"
43 #include "unittest/gunit/mysys_util.h"
44 #include "unittest/gunit/test_utils.h"
45
46 /**
47 Test Json_dom class hierarchy API, cf. json_dom.h
48 */
49 namespace json_dom_unittest {
50
51 class JsonDomTest : public ::testing::Test {
52 protected:
53 Base_mock_field_json m_field{};
54 Fake_TABLE *m_table;
55 void SetUp() override {
56 initializer.SetUp();
57 m_table = new Fake_TABLE(&m_field);
58 m_field.make_writable();
59 m_table->in_use = thd();
60 }
61 void TearDown() override {
62 m_table->cleanup_partial_update();
63 delete m_table;
64 initializer.TearDown();
65 }
66 my_testing::Server_initializer initializer;
67 THD *thd() const { return initializer.thd(); }
68 };
69
70 /**
71 Format a Json_dom object to JSON text using Json_wrapper's
72 to_string functionality.
73
74 @param d The DOM object to be formatted
75 */
76 static std::string format(const Json_dom &d) {
77 String buffer;
78 Json_wrapper w(d.clone());
79 EXPECT_FALSE(
80 w.to_string(&buffer, true, "format", [] { ASSERT_TRUE(false); }));
81
82 return std::string(buffer.ptr(), buffer.length());
83 }
84
85 static std::string format(const Json_dom *ptr) { return format(*ptr); }
86
87 static std::string format(const Json_dom_ptr &ptr) { return format(*ptr); }
88
89 /**
90 Parse a JSON text and return its DOM representation.
91 @param json_text null-terminated string of JSON text
92 @return a DOM representing the JSON document
93 */
94 static Json_dom_ptr parse_json(const char *json_text) {
95 auto dom = Json_dom::parse(
96 json_text, std::strlen(json_text), [](const char *, size_t) {},
97 [] { ASSERT_TRUE(false); });
98 EXPECT_FALSE(dom == nullptr);
99 return dom;
100 }
101
102 /**
103 Parse a JSON path.
104 @param json_path the JSON path text to parse
105 @return the parsed path
106 */
107 static Json_path parse_path(const char *json_path) {
108 Json_path path(key_memory_JSON);
109 size_t bad_index;
110 EXPECT_FALSE(parse_path(std::strlen(json_path), json_path, &path, &bad_index,
111 [] { ASSERT_TRUE(false); }))
112 << "bad index: " << bad_index;
113 return path;
114 }
115
116 TEST_F(JsonDomTest, BasicTest) {
117 String buffer;
118 /* string scalar */
119 const std::string std_s("abc");
120 Json_string s(std_s);
121 EXPECT_EQ(std_s, s.value());
122 EXPECT_EQ(enum_json_type::J_STRING, s.json_type());
123 EXPECT_TRUE(s.is_scalar());
124 EXPECT_EQ(1U, s.depth());
125 EXPECT_FALSE(s.is_number());
126 EXPECT_EQ(std::string("\"abc\""), format(s));
127
128 /*
129 Escaping in strings, cf. ECMA-404 The JSON Data Interchange Format
130 */
131 Json_array a;
132 /* double quote and backslash */
133 Json_string js1(std::string("a\"b\\c"));
134 a.append_clone(&js1);
135 EXPECT_EQ(std::string("[\"a\\\"b\\\\c\"]"), format(a));
136
137 a.clear();
138 /* Printable control characters */
139 Json_string js2(std::string("a\b\f\n\r\tb"));
140 a.append_clone(&js2);
141 EXPECT_EQ(7U, static_cast<Json_string *>(a[0])->size());
142 EXPECT_EQ(std::string("[\"a\\b\\f\\n\\r\\tb\"]"), format(a));
143
144 a.clear();
145 /* Unprintable control characters and non-ASCII Unicode characters */
146 Json_string js3(
147 std::string("丳\x13"
148 "丽\x3"));
149 a.append_clone(&js3);
150 EXPECT_EQ(std::string("[\"丳\\u0013丽\\u0003\"]"), format(a));
151
152 /* boolean scalar */
153 const Json_boolean jb(true);
154 EXPECT_EQ(enum_json_type::J_BOOLEAN, jb.json_type());
155 EXPECT_EQ(true, jb.value());
156 EXPECT_EQ(std::string("true"), format(jb));
157
158 /* Integer scalar */
159 const Json_int ji(-123);
160 EXPECT_EQ(enum_json_type::J_INT, ji.json_type());
161 EXPECT_EQ(-123, ji.value());
162 EXPECT_EQ(std::string("-123"), format(ji));
163
164 const Json_int max_32_int(2147483647);
165 EXPECT_EQ(std::string("2147483647"), format(max_32_int));
166
167 const Json_int max_64_int(9223372036854775807LL);
168 EXPECT_EQ(std::string("9223372036854775807"), format(max_64_int));
169
170 const Json_uint max_64_uint(18446744073709551615ULL);
171 EXPECT_EQ(enum_json_type::J_UINT, max_64_uint.json_type());
172 EXPECT_EQ(std::string("18446744073709551615"), format(max_64_uint));
173
174 /* Double scalar */
175 const Json_double jdb(-123.45);
176 EXPECT_EQ(enum_json_type::J_DOUBLE, jdb.json_type());
177 EXPECT_EQ(-123.45, jdb.value());
178 EXPECT_EQ(std::string("-123.45"), format(jdb));
179
180 /* Simple array with strings */
181 a.clear();
182 EXPECT_EQ(enum_json_type::J_ARRAY, a.json_type());
183 EXPECT_FALSE(a.is_scalar());
184 EXPECT_EQ(0U, a.size());
185 Json_string js4(std::string("val1"));
186 a.append_clone(&js4);
187 Json_string js5(std::string("val2"));
188 a.append_clone(&js5);
189 EXPECT_EQ(2U, a.size());
190 EXPECT_EQ(std::string("[\"val1\", \"val2\"]"), format(a));
191 EXPECT_EQ(2U, a.depth());
192 Json_dom *elt0 = a[0];
193 Json_dom *elt1 = a[a.size() - 1];
194 EXPECT_EQ(std::string("\"val1\""), format(elt0));
195 EXPECT_EQ(std::string("\"val2\""), format(elt1));
196
197 /* Simple object with string values, iterator and array cloning */
198 Json_object o;
199 EXPECT_EQ(enum_json_type::J_OBJECT, o.json_type());
200 EXPECT_FALSE(a.is_scalar());
201 EXPECT_EQ(0U, o.cardinality());
202 Json_null null;
203 EXPECT_EQ(enum_json_type::J_NULL, null.json_type());
204 o.add_clone(std::string("key1"), &null);
205 o.add_clone(std::string("key2"), &a);
206
207 const std::string key_expected[] = {std::string("key1"), std::string("key2")};
208 const std::string value_expected[] = {std::string("null"),
209 std::string("[\"val1\", \"val2\"]")};
210
211 int idx = 0;
212
213 for (Json_object::const_iterator i = o.begin(); i != o.end(); ++i) {
214 EXPECT_EQ(key_expected[idx], i->first);
215 EXPECT_EQ(value_expected[idx], format(i->second));
216 idx++;
217 }
218
219 /* Test uniqueness of keys */
220 Json_string js6(std::string("js6"));
221 o.add_clone("key1", &js6);
222 EXPECT_EQ(2U, o.cardinality());
223 EXPECT_EQ(std::string("{\"key1\": \"js6\", \"key2\": [\"val1\", \"val2\"]}"),
224 format(o));
225 EXPECT_EQ(3U, o.depth());
226 o.add_clone("key1", &null);
227 EXPECT_EQ(std::string("{\"key1\": null, \"key2\": [\"val1\", \"val2\"]}"),
228 format(o));
229
230 /* Nested array inside object and object inside array,
231 * and object cloning
232 */
233 Json_array level3;
234 level3.append_clone(&o);
235 Json_int ji2(123);
236 level3.insert_clone(0U, &ji2);
237 EXPECT_EQ(std::string("[123, {\"key1\": null, \"key2\": "
238 "[\"val1\", \"val2\"]}]"),
239 format(level3));
240 EXPECT_EQ(4U, level3.depth());
241
242 /* Array access: index */
243 Json_dom *const elt = level3[1];
244 EXPECT_EQ(std::string("{\"key1\": null, \"key2\": "
245 "[\"val1\", \"val2\"]}"),
246 format(elt));
247
248 /* Object access: key look-up */
249 EXPECT_EQ(enum_json_type::J_OBJECT, elt->json_type());
250 Json_object *const object_elt = down_cast<Json_object *>(elt);
251 EXPECT_TRUE(object_elt != nullptr);
252 const Json_dom *const elt2 = object_elt->get(std::string("key1"));
253 EXPECT_EQ(std::string("null"), format(elt2));
254
255 /* Clear object. */
256 object_elt->clear();
257 EXPECT_EQ(0U, object_elt->cardinality());
258
259 /* Array remove element */
260 EXPECT_TRUE(level3.remove(1));
261 EXPECT_EQ(std::string("[123]"), format(level3));
262 EXPECT_FALSE(level3.remove(level3.size()));
263 EXPECT_EQ(std::string("[123]"), format(level3));
264
265 /* Decimal scalar, including cloning */
266 my_decimal m;
267 EXPECT_FALSE(double2my_decimal(0, 3.14, &m));
268
269 const Json_decimal jd(m);
270 EXPECT_EQ(enum_json_type::J_DECIMAL, jd.json_type());
271 EXPECT_TRUE(jd.is_number());
272 EXPECT_TRUE(jd.is_scalar());
273 const my_decimal m_out = *jd.value();
274 double m_d;
275 double m_out_d;
276
277 decimal2double(&m, &m_d);
278 decimal2double(&m_out, &m_out_d);
279 EXPECT_EQ(m_d, m_out_d);
280
281 a.append_clone(&jd);
282 EXPECT_EQ(std::string("[\"val1\", \"val2\", 3.14]"), format(a));
283 EXPECT_EQ(std::string("[\"val1\", \"val2\", 3.14]"), format(a.clone()));
284
285 /* Array insert beyond end appends at end */
286 a.clear();
287 a.insert_alias(0, create_dom_ptr<Json_int>(0));
288 a.insert_alias(2, create_dom_ptr<Json_int>(2));
289 EXPECT_EQ(std::string("[0, 2]"), format(a));
290 a.clear();
291 a.insert_alias(0, create_dom_ptr<Json_int>(0));
292 a.insert_alias(1, create_dom_ptr<Json_int>(1));
293 EXPECT_EQ(std::string("[0, 1]"), format(a));
294
295 /* Array clear, null type, boolean literals, including cloning */
296 a.clear();
297 Json_null jn;
298 Json_boolean jbf(false);
299 Json_boolean jbt(true);
300 a.append_clone(&jn);
301 a.append_clone(&jbf);
302 a.append_clone(&jbt);
303 EXPECT_EQ(std::string("[null, false, true]"), format(a));
304 EXPECT_EQ(std::string("[null, false, true]"), format(a.clone()));
305
306 /* DATETIME scalar */
307 MYSQL_TIME dt;
308 std::memset(&dt, 0, sizeof dt);
309 MYSQL_TIME_STATUS status;
310 EXPECT_FALSE(str_to_datetime(&my_charset_utf8mb4_bin, "19990412", 8, &dt,
311 (my_time_flags_t)0, &status));
312 const Json_datetime scalar(dt, MYSQL_TYPE_DATETIME);
313 EXPECT_EQ(enum_json_type::J_DATETIME, scalar.json_type());
314
315 const MYSQL_TIME *dt_out = scalar.value();
316
317 EXPECT_FALSE(std::memcmp(&dt, dt_out, sizeof(MYSQL_TIME)));
318 EXPECT_EQ(std::string("\"1999-04-12\""), format(scalar));
319
320 a.clear();
321 a.append_clone(&scalar);
322 EXPECT_EQ(std::string("[\"1999-04-12\"]"), format(a));
323
324 EXPECT_FALSE(str_to_datetime(&my_charset_utf8mb4_bin,
325 "14-11-15 12.04.55.123456", 24, &dt,
326 (my_time_flags_t)0, &status));
327
328 Json_datetime scalar2(dt, MYSQL_TYPE_DATETIME);
329 EXPECT_EQ(std::string("\"2014-11-15 12:04:55.123456\""), format(scalar2));
330
331 /* Opaque type storage scalar */
332 const uint32 i = 0xCAFEBABE;
333 char i_as_char[4];
334 int4store(i_as_char, i);
335 Json_opaque opaque(MYSQL_TYPE_TINY_BLOB, i_as_char, sizeof(i_as_char));
336 EXPECT_EQ(enum_json_type::J_OPAQUE, opaque.json_type());
337 EXPECT_EQ(i, uint4korr(opaque.value()));
338 EXPECT_EQ(MYSQL_TYPE_TINY_BLOB, opaque.type());
339 EXPECT_EQ(sizeof(i_as_char), opaque.size());
340 EXPECT_EQ(std::string("\"base64:type249:vrr+yg==\""), format(opaque));
341
342 const char *encoded = "vrr+yg==";
343 char *buff = new char[static_cast<size_t>(
344 base64_needed_decoded_length(static_cast<int>(std::strlen(encoded))))];
345 EXPECT_EQ(4, base64_decode(encoded, std::strlen(encoded), buff, nullptr, 0));
346 EXPECT_EQ(0xCAFEBABE, uint4korr(buff));
347 delete[] buff;
348
349 /* Build DOM from JSON text using rapdjson */
350 const char *sample_doc =
351 "{\"abc\": 3, \"foo\": [1, 2, {\"foo\": 3.24}, null]}";
352 auto dom = parse_json(sample_doc);
353 EXPECT_EQ(4U, dom->depth());
354 EXPECT_EQ(std::string(sample_doc), format(dom));
355
356 const char *sample_array = "[3, {\"abc\": \"\\u0000inTheText\"}]";
357 dom = parse_json(sample_array);
358 EXPECT_EQ(3U, dom->depth());
359 EXPECT_EQ(std::string(sample_array), format(dom));
360
361 const char *sample_scalar_doc = "2";
362 dom = parse_json(sample_scalar_doc);
363 EXPECT_EQ(std::string(sample_scalar_doc), format(dom));
364
365 const char *max_uint_scalar = "18446744073709551615";
366 dom = parse_json(max_uint_scalar);
367 EXPECT_EQ(std::string(max_uint_scalar), format(dom));
368
369 /*
370 Test that duplicate keys are eliminated, and that the returned
371 keys are in the expected order (sorted on length before
372 contents).
373 */
374 const char *sample_object =
375 "{\"key1\":1, \"key2\":2, \"key1\":3, "
376 "\"key1\\u0000x\":4, \"key1\\u0000y\":5, \"a\":6, \"ab\":7, \"b\":8, "
377 "\"\":9, \"\":10}";
378 const std::string expected[8][2] = {
379 {"", "10"},
380 {"a", "6"},
381 {"b", "8"},
382 {"ab", "7"},
383 {"key1", "3"},
384 {"key2", "2"},
385 {std::string("key1\0x", 6), "4"},
386 {std::string("key1\0y", 6), "5"},
387 };
388 dom = parse_json(sample_object);
389 const Json_object *obj = down_cast<const Json_object *>(dom.get());
390 EXPECT_EQ(8U, obj->cardinality());
391 idx = 0;
392
393 for (Json_object::const_iterator it = obj->begin(); it != obj->end(); ++it) {
394 EXPECT_EQ(expected[idx][0], it->first);
395 EXPECT_EQ(expected[idx][1], format(it->second));
396 idx++;
397 }
398
399 EXPECT_EQ(8, idx);
400
401 /* Try to build DOM for JSON text using rapidjson on invalid text
402 Included so we test error recovery
403 */
404 const char *half_object_item = "{\"label\": ";
405 dom = Json_dom::parse(
406 half_object_item, std::strlen(half_object_item),
407 [](const char *, size_t) {}, [] { ASSERT_TRUE(false); });
408 EXPECT_EQ(nullptr, dom);
409
410 const char *half_array_item = "[1,";
411 dom = Json_dom::parse(
412 half_array_item, std::strlen(half_array_item),
413 [](const char *, size_t) {}, [] { ASSERT_TRUE(false); });
414 EXPECT_EQ(nullptr, dom);
415 }
416
417 /*
418 Test that special characters are escaped when a Json_string is
419 converted to text, so that it is possible to parse the resulting
420 string. The JSON parser requires all characters in the range [0x00,
421 0x1F] and the characters " (double-quote) and \ (backslash) to be
422 escaped.
423 */
424 TEST_F(JsonDomTest, EscapeSpecialChars) {
425 // Create a JSON string with all characters in the range [0, 127].
426 char input[128];
427 for (size_t i = 0; i < sizeof(input); ++i) input[i] = static_cast<char>(i);
428 const Json_string str(input, sizeof(input));
429
430 // Now convert that value from JSON to text and back to JSON.
431 Json_dom_ptr dom = parse_json(format(str).c_str());
432 EXPECT_EQ(enum_json_type::J_STRING, dom->json_type());
433
434 // Expect to get the same string back, including all the special characters.
435 const Json_string *str2 = down_cast<const Json_string *>(dom.get());
436 EXPECT_EQ(str.value(), str2->value());
437 }
438
439 void vet_wrapper_length(const THD *thd, const char *text,
440 size_t expected_length) {
441 Json_wrapper dom_wrapper(parse_json(text));
442
443 EXPECT_EQ(expected_length, dom_wrapper.length())
444 << "Wrapped DOM: " << text << "\n";
445
446 String serialized_form;
447 EXPECT_FALSE(
448 json_binary::serialize(thd, dom_wrapper.to_dom(), &serialized_form));
449 json_binary::Value binary = json_binary::parse_binary(
450 serialized_form.ptr(), serialized_form.length());
451 Json_wrapper binary_wrapper(binary);
452
453 json_binary::Value::enum_type binary_type = binary.type();
454
455 if ((binary_type == json_binary::Value::ARRAY) ||
456 (binary_type == json_binary::Value::OBJECT)) {
457 EXPECT_EQ(expected_length, binary.element_count())
458 << "BINARY: " << text << " and data = " << binary.get_data() << "\n";
459 }
460 EXPECT_EQ(expected_length, binary_wrapper.length())
461 << "Wrapped BINARY: " << text << "\n";
462 }
463
464 TEST_F(JsonDomTest, WrapperTest) {
465 // Constructors, assignment, copy constructors, aliasing
466 Json_dom *d = new (std::nothrow) Json_null();
467 Json_wrapper w(d);
468 const THD *thd = this->thd();
469 EXPECT_EQ(w.to_dom(), d);
470 Json_wrapper w_2(w);
471 EXPECT_NE(w.to_dom(), w_2.to_dom()); // deep copy
472
473 Json_wrapper w_2b;
474 EXPECT_TRUE(w_2b.empty());
475 w_2b = w;
476 EXPECT_NE(w.to_dom(), w_2b.to_dom()); // deep copy
477
478 w.set_alias(); // d is now "free" again
479 Json_wrapper w_3(w);
480 EXPECT_EQ(w.to_dom(), w_3.to_dom()); // alias copy
481 w_3 = w;
482 EXPECT_EQ(w.to_dom(), w_3.to_dom()); // alias copy
483
484 Json_wrapper w_4(d); // give d a new owner
485 Json_wrapper w_5;
486 w_5 = std::move(w_4); // takes over d
487 EXPECT_EQ(w_4.to_dom(), w_5.to_dom());
488
489 Json_wrapper w_6;
490 EXPECT_EQ(enum_json_type::J_ERROR, w_6.type());
491 EXPECT_EQ(nullptr, w_6.to_dom());
492 EXPECT_EQ(nullptr, w_6.clone_dom());
493 EXPECT_EQ(0U, w_6.length());
494
495 Json_dom *i = new (std::nothrow) Json_int(1);
496 Json_wrapper w_7(i);
497 w_5 = std::move(w_7); // should deallocate w_5's original
498
499 // scalars
500 vet_wrapper_length(thd, "false", 1);
501 vet_wrapper_length(thd, "true", 1);
502 vet_wrapper_length(thd, "null", 1);
503 vet_wrapper_length(thd, "1.1", 1);
504 vet_wrapper_length(thd, "\"hello world\"", 1);
505
506 // objects
507 vet_wrapper_length(thd, "{}", 0);
508 vet_wrapper_length(thd, "{ \"a\" : 100 }", 1);
509 vet_wrapper_length(thd, "{ \"a\" : 100, \"b\" : 200 }", 2);
510
511 // arrays
512 vet_wrapper_length(thd, "[]", 0);
513 vet_wrapper_length(thd, "[ 100 ]", 1);
514 vet_wrapper_length(thd, "[ 100, 200 ]", 2);
515
516 // nested objects
517 vet_wrapper_length(thd, "{ \"a\" : 100, \"b\" : { \"c\" : 300 } }", 2);
518
519 // nested arrays
520 vet_wrapper_length(thd, "[ 100, [ 200, 300 ] ]", 2);
521 }
522
523 void vet_merge(const char *left_text, const char *right_text,
524 std::string expected) {
525 Json_dom_ptr result_dom =
526 merge_doms(parse_json(left_text), parse_json(right_text));
527 EXPECT_EQ(expected, format(*result_dom));
528 }
529
530 TEST_F(JsonDomTest, MergeTest) {
531 // merge 2 scalars
532 {
533 SCOPED_TRACE("");
534 vet_merge("1", "true", "[1, true]");
535 }
536
537 // merge a scalar with an array
538 {
539 SCOPED_TRACE("");
540 vet_merge("1", "[true, false]", "[1, true, false]");
541 }
542
543 // merge an array with a scalar
544 {
545 SCOPED_TRACE("");
546 vet_merge("[true, false]", "1", "[true, false, 1]");
547 }
548
549 // merge a scalar with an object
550 {
551 SCOPED_TRACE("");
552 vet_merge("1", "{\"a\": 2}", "[1, {\"a\": 2}]");
553 }
554
555 // merge an object with a scalar
556 {
557 SCOPED_TRACE("");
558 vet_merge("{\"a\": 2}", "1", "[{\"a\": 2}, 1]");
559 }
560
561 // merge 2 arrays
562 {
563 SCOPED_TRACE("");
564 vet_merge("[1, 2]", "[3, 4]", "[1, 2, 3, 4]");
565 }
566
567 // merge 2 objects
568 {
569 SCOPED_TRACE("");
570 vet_merge("{\"a\": 1, \"b\": 2 }", "{\"c\": 3, \"d\": 4 }",
571 "{\"a\": 1, \"b\": 2, \"c\": 3, \"d\": 4}");
572 }
573
574 // merge an array with an object
575 {
576 SCOPED_TRACE("");
577 vet_merge("[1, 2]", "{\"c\": 3, \"d\": 4 }",
578 "[1, 2, {\"c\": 3, \"d\": 4}]");
579 }
580
581 // merge an object with an array
582 {
583 SCOPED_TRACE("");
584 vet_merge("{\"c\": 3, \"d\": 4 }", "[1, 2]",
585 "[{\"c\": 3, \"d\": 4}, 1, 2]");
586 }
587
588 // merge two objects which share a key. scalar + scalar
589 {
590 SCOPED_TRACE("");
591 vet_merge("{\"a\": 1, \"b\": 2 }", "{\"b\": 3, \"d\": 4 }",
592 "{\"a\": 1, \"b\": [2, 3], \"d\": 4}");
593 }
594
595 // merge two objects which share a key. scalar + array
596 {
597 SCOPED_TRACE("");
598 vet_merge("{\"a\": 1, \"b\": 2 }", "{\"b\": [3, 4], \"d\": 4 }",
599 "{\"a\": 1, \"b\": [2, 3, 4], \"d\": 4}");
600 }
601
602 // merge two objects which share a key. array + scalar
603 {
604 SCOPED_TRACE("");
605 vet_merge("{\"a\": 1, \"b\": [2, 3] }", "{\"b\": 4, \"d\": 4 }",
606 "{\"a\": 1, \"b\": [2, 3, 4], \"d\": 4}");
607 }
608
609 // merge two objects which share a key. scalar + object
610 {
611 SCOPED_TRACE("");
612 vet_merge("{\"a\": 1, \"b\": 2 }",
613 "{\"b\": {\"e\": 7, \"f\": 8}, \"d\": 4 }",
614 "{\"a\": 1, \"b\": [2, {\"e\": 7, \"f\": 8}], \"d\": 4}");
615 }
616
617 // merge two objects which share a key. object + scalar
618 {
619 SCOPED_TRACE("");
620 vet_merge("{\"b\": {\"e\": 7, \"f\": 8}, \"d\": 4 }",
621 "{\"a\": 1, \"b\": 2 }",
622 "{\"a\": 1, \"b\": [{\"e\": 7, \"f\": 8}, 2], \"d\": 4}");
623 }
624
625 // merge two objects which share a key. array + array
626 {
627 SCOPED_TRACE("");
628 vet_merge("{\"a\": 1, \"b\": [2, 9] }", "{\"b\": [10, 11], \"d\": 4 }",
629 "{\"a\": 1, \"b\": [2, 9, 10, 11], \"d\": 4}");
630 }
631
632 // merge two objects which share a key. array + object
633 {
634 SCOPED_TRACE("");
635 vet_merge("{\"a\": 1, \"b\": [2, 9] }",
636 "{\"b\": {\"e\": 7, \"f\": 8}, \"d\": 4 }",
637 "{\"a\": 1, \"b\": [2, 9, {\"e\": 7, \"f\": 8}], \"d\": 4}");
638 }
639
640 // merge two objects which share a key. object + array
641 {
642 SCOPED_TRACE("");
643 vet_merge("{\"b\": {\"e\": 7, \"f\": 8}, \"d\": 4 }",
644 "{\"a\": 1, \"b\": [2, 9] }",
645 "{\"a\": 1, \"b\": [{\"e\": 7, \"f\": 8}, 2, 9], \"d\": 4}");
646 }
647
648 // merge two objects which share a key. object + object
649 {
650 SCOPED_TRACE("");
651 vet_merge("{\"b\": {\"e\": 7, \"f\": 8}, \"d\": 4 }",
652 "{\"a\": 1, \"b\": {\"e\": 20, \"g\": 21 } }",
653 "{\"a\": 1, \"b\": {\"e\": [7, 20], \"f\": 8, \"g\": 21}, "
654 "\"d\": 4}");
655 }
656 }
657
658 /// Create a JSON path for accessing an array element at the given position.
659 static Json_path array_accessor(size_t idx) {
660 Json_path path(key_memory_JSON);
661 path.append(Json_path_leg(idx));
662 return path;
663 }
664
665 /**
666 Verify that applying the given binary diffs on the original binary
667 value produces a binary string identical to the updated binary value.
668
669 @param field the column that is updated
670 @param diffs the binary diffs to apply
671 @param original the original binary data
672 @param updated the updated binary data
673 */
674 static void verify_binary_diffs(Field_json *field,
675 const Binary_diff_vector *diffs,
676 const String &original, const String &updated) {
677 SCOPED_TRACE("verify_binary_diffs");
678 EXPECT_EQ(original.length(), updated.length());
679 std::unique_ptr<char[]> buffer(new char[original.length()]);
680 std::memcpy(buffer.get(), original.ptr(), original.length());
681 const Binary_diff *prev = nullptr;
682 for (const auto &diff : *diffs) {
683 EXPECT_LE(diff.offset(), original.length());
684 EXPECT_LE(diff.offset() + diff.length(), original.length());
685 std::memcpy(buffer.get() + diff.offset(), diff.new_data(field),
686 diff.length());
687 /*
688 The diff vector should be ordered on offset and not have any overlapping
689 or adjacent areas.
690 */
691 if (prev != nullptr) {
692 EXPECT_LT(prev->offset() + prev->length(), diff.offset());
693 }
694 prev = &diff;
695 }
696 EXPECT_EQ(0, std::memcmp(buffer.get(), updated.ptr(), updated.length()));
697 }
698
699 /**
700 Tests for Json_wrapper::attempt_binary_update().
701 */
702 TEST_F(JsonDomTest, AttemptBinaryUpdate) {
703 auto dom = parse_json("[\"abc\", 123, \"def\", -70000]");
704
705 String buffer;
706 EXPECT_FALSE(json_binary::serialize(thd(), dom.get(), &buffer));
707
708 json_binary::Value binary =
709 json_binary::parse_binary(buffer.ptr(), buffer.length());
710
711 EXPECT_FALSE(m_table->mark_column_for_partial_update(&m_field));
712 EXPECT_FALSE(m_table->setup_partial_update(true));
713
714 // Verify that the table interface for partial update works.
715 EXPECT_TRUE(m_table->has_binary_diff_columns());
716 EXPECT_TRUE(m_table->is_marked_for_partial_update(&m_field));
717 EXPECT_TRUE(m_table->is_binary_diff_enabled(&m_field));
718 EXPECT_NE(nullptr, m_table->get_binary_diffs(&m_field));
719 m_table->disable_binary_diffs_for_current_row(&m_field);
720 EXPECT_FALSE(m_table->has_binary_diff_columns());
721 EXPECT_TRUE(m_table->is_marked_for_partial_update(&m_field));
722 EXPECT_FALSE(m_table->is_binary_diff_enabled(&m_field));
723 EXPECT_EQ(nullptr, m_table->get_binary_diffs(&m_field));
724 m_table->clear_partial_update_diffs();
725 EXPECT_TRUE(m_table->has_binary_diff_columns());
726 EXPECT_TRUE(m_table->is_marked_for_partial_update(&m_field));
727 EXPECT_TRUE(m_table->is_binary_diff_enabled(&m_field));
728 EXPECT_NE(nullptr, m_table->get_binary_diffs(&m_field));
729
730 const Binary_diff_vector *diffs = m_table->get_binary_diffs(&m_field);
731 EXPECT_TRUE(diffs != nullptr);
732 EXPECT_EQ(0U, diffs->size());
733
734 // Not enough space for a four-character string anywhere in the array.
735 for (size_t i = 0; i < 4; ++i) {
736 SCOPED_TRACE("");
737 Json_wrapper doc(binary);
738 EXPECT_EQ(TYPE_OK, m_field.store_json(&doc));
739 Json_wrapper jstr(new (std::nothrow) Json_string("abcd"));
740 m_table->clear_partial_update_diffs();
741 auto path = array_accessor(i);
742 String shadow;
743 bool success = true;
744 bool replaced = true;
745 EXPECT_FALSE(doc.attempt_binary_update(&m_field, path, &jstr, true, &shadow,
746 &success, &replaced));
747 EXPECT_FALSE(success);
748 EXPECT_FALSE(replaced);
749 EXPECT_EQ(0U, diffs->size());
750 EXPECT_EQ(0, doc.compare(Json_wrapper(binary)));
751 EXPECT_EQ(0U, m_table->get_logical_diffs(&m_field)->size());
752 }
753
754 // Enough space for an inlinable value anywhere in the array.
755 for (size_t i = 0; i < 4; ++i) {
756 SCOPED_TRACE("");
757 Json_wrapper doc(binary);
758 EXPECT_EQ(TYPE_OK, m_field.store_json(&doc));
759 EXPECT_FALSE(m_field.val_json(&doc));
760 Json_wrapper jint(new (std::nothrow) Json_int(456));
761 m_table->clear_partial_update_diffs();
762 auto path = array_accessor(i);
763 String shadow;
764 bool success = false;
765 bool replaced = false;
766 EXPECT_FALSE(doc.attempt_binary_update(&m_field, path, &jint, true, &shadow,
767 &success, &replaced));
768 EXPECT_TRUE(success);
769 EXPECT_TRUE(replaced);
770 EXPECT_EQ(1U, diffs->size());
771
772 Json_array_ptr array(down_cast<Json_array *>(dom->clone().release()));
773 array->remove(i);
774 array->insert_clone(i, jint.to_dom());
775 EXPECT_EQ(0, doc.compare(Json_wrapper(std::move(array))));
776
777 EXPECT_EQ(TYPE_OK, m_field.store_json(&doc));
778 verify_binary_diffs(&m_field, diffs, buffer, shadow);
779 }
780
781 // Enough space for a four-byte integer only on $[0], $[2] and $[3].
782 for (size_t i = 0; i < 4; ++i) {
783 SCOPED_TRACE("");
784 Json_wrapper doc(binary);
785 EXPECT_EQ(TYPE_OK, m_field.store_json(&doc));
786 EXPECT_FALSE(m_field.val_json(&doc));
787 Json_wrapper jint(new (std::nothrow) Json_uint(80000));
788 m_table->clear_partial_update_diffs();
789 auto path = array_accessor(i);
790 String shadow;
791 bool success = false;
792 bool replaced = false;
793 EXPECT_FALSE(doc.attempt_binary_update(&m_field, path, &jint, true, &shadow,
794 &success, &replaced));
795 EXPECT_EQ(i != 1, success);
796 if (!success) {
797 EXPECT_FALSE(replaced);
798 EXPECT_EQ(0U, diffs->size());
799 EXPECT_EQ(0U, m_table->get_logical_diffs(&m_field)->size());
800 continue;
801 }
802 EXPECT_TRUE(replaced);
803 EXPECT_EQ(2U, diffs->size()) << i;
804
805 Json_array_ptr array(down_cast<Json_array *>(dom->clone().release()));
806 array->remove(i);
807 array->insert_clone(i, jint.to_dom());
808 EXPECT_EQ(0, doc.compare(Json_wrapper(std::move(array))));
809
810 EXPECT_EQ(TYPE_OK, m_field.store_json(&doc));
811 verify_binary_diffs(&m_field, diffs, buffer, shadow);
812 }
813
814 {
815 SCOPED_TRACE("");
816 Json_wrapper doc(binary);
817 EXPECT_EQ(TYPE_OK, m_field.store_json(&doc));
818 EXPECT_FALSE(m_field.val_json(&doc));
819 Json_wrapper jint(new (std::nothrow) Json_int(456));
820 m_table->clear_partial_update_diffs();
821 String shadow;
822 auto path = array_accessor(100);
823
824 /*
825 Partial update is not performed with a non-existing path when JSON_SET
826 semantics are used.
827 */
828 bool success = false;
829 bool replaced = false;
830 EXPECT_FALSE(doc.attempt_binary_update(&m_field, path, &jint, false,
831 &shadow, &success, &replaced));
832 EXPECT_FALSE(success);
833 EXPECT_FALSE(replaced);
834 EXPECT_EQ(0U, diffs->size());
835 EXPECT_EQ(0U, m_table->get_logical_diffs(&m_field)->size());
836
837 /*
838 JSON_REPLACE is a no-op if a non-existing path is given, so expect
839 partial update to be successful.
840 */
841 EXPECT_FALSE(doc.attempt_binary_update(&m_field, path, &jint, true, &shadow,
842 &success, &replaced));
843 EXPECT_TRUE(success);
844 EXPECT_FALSE(replaced);
845 EXPECT_EQ(0U, diffs->size());
846 EXPECT_EQ(0, doc.compare(Json_wrapper(binary)));
847 EXPECT_EQ(0U, m_table->get_logical_diffs(&m_field)->size());
848
849 /*
850 If we replace the top-level document (empty path), we do a full update.
851 Expect the attempt to do partial update to fail.
852 */
853 EXPECT_FALSE(
854 doc.attempt_binary_update(&m_field, Json_path(PSI_NOT_INSTRUMENTED),
855 &jint, false, &shadow, &success, &replaced));
856 EXPECT_FALSE(success);
857 EXPECT_FALSE(replaced);
858 }
859
860 {
861 SCOPED_TRACE("");
862 m_table->clear_partial_update_diffs();
863 Json_wrapper doc(binary);
864 EXPECT_EQ(TYPE_OK, m_field.store_json(&doc));
865 EXPECT_FALSE(m_field.val_json(&doc));
866 auto array = down_cast<Json_array *>(dom->clone().release());
867 Json_wrapper array_wrapper(array);
868 String shadow;
869 // Replace all elements with short strings which fit at the old location.
870 Json_wrapper jstr(new (std::nothrow) Json_string("x"));
871 for (size_t i = 0; i < 4; ++i) {
872 auto path = array_accessor(i);
873 bool success = false;
874 bool replaced = false;
875 EXPECT_FALSE(doc.attempt_binary_update(&m_field, path, &jstr, false,
876 &shadow, &success, &replaced));
877 EXPECT_TRUE(success);
878 EXPECT_TRUE(replaced);
879 array->remove(i);
880 array->insert_clone(i, jstr.to_dom());
881 EXPECT_EQ(0, doc.compare(array_wrapper));
882
883 EXPECT_EQ(TYPE_OK, m_field.store_json(&doc));
884 verify_binary_diffs(&m_field, diffs, buffer, shadow);
885 }
886 /*
887 We expect one diff for the first element (type/offset unchanged, data
888 changed), two diffs for the second element (type/offset changed, data
889 changed), one diff for the third element (type/offset unchanged, data
890 changed), and two diffs for the fourth element (type/offset changed, data
891 changed).
892
893 However, the first, third, fourth and fifth diff are touching adjacent
894 areas and are merged into a single diff. So there are three diffs.
895 */
896 EXPECT_EQ(3U, diffs->size());
897 }
898 }
899
900 /**
901 Test attempt_binary_update() with all types.
902 */
903 TEST_F(JsonDomTest, AttemptBinaryUpdate_AllTypes) {
904 // Make the table ready for partial update.
905 EXPECT_FALSE(m_table->mark_column_for_partial_update(&m_field));
906 EXPECT_FALSE(m_table->setup_partial_update(true));
907
908 my_decimal decimal;
909 EXPECT_FALSE(double2my_decimal(0, 3.14, &decimal));
910
911 MYSQL_TIME dt;
912 std::memset(&dt, 0, sizeof(dt));
913 MYSQL_TIME_STATUS status;
914 EXPECT_FALSE(str_to_datetime(&my_charset_utf8mb4_bin, "20170223", 8, &dt,
915 static_cast<my_time_flags_t>(0), &status));
916
917 MYSQL_TIME tm;
918 std::memset(&dt, 0, sizeof(tm));
919 EXPECT_FALSE(str_to_time(&my_charset_utf8mb4_bin, "17:28:25", 8, &tm,
920 static_cast<my_time_flags_t>(0), &status));
921
922 Json_dom *doms[] = {
923 new (std::nothrow) Json_null,
924 new (std::nothrow) Json_boolean(true),
925 new (std::nothrow) Json_boolean(false),
926 new (std::nothrow) Json_int(0),
927 new (std::nothrow) Json_int(1000),
928 new (std::nothrow) Json_int(100000),
929 new (std::nothrow) Json_int(100000000),
930 new (std::nothrow) Json_uint(0),
931 new (std::nothrow) Json_uint(1000),
932 new (std::nothrow) Json_uint(100000),
933 new (std::nothrow) Json_uint(100000000),
934 new (std::nothrow) Json_double(3.14),
935 new (std::nothrow) Json_string(""),
936 new (std::nothrow) Json_string("xyz"),
937 new (std::nothrow) Json_decimal(decimal),
938 new (std::nothrow) Json_datetime(dt, MYSQL_TYPE_DATETIME),
939 new (std::nothrow) Json_datetime(dt, MYSQL_TYPE_DATE),
940 new (std::nothrow) Json_datetime(dt, MYSQL_TYPE_TIMESTAMP),
941 new (std::nothrow) Json_datetime(tm, MYSQL_TYPE_TIME),
942 new (std::nothrow) Json_opaque(MYSQL_TYPE_BLOB, 5, 'x'),
943 new (std::nothrow) Json_array(),
944 parse_json("[1,2,3]").release(),
945 new (std::nothrow) Json_object(),
946 parse_json("{\"a\":\"b\"}").release(),
947 };
948
949 for (auto dom : doms) {
950 m_table->clear_partial_update_diffs();
951
952 Json_array_ptr original_dom(new (std::nothrow) Json_array);
953 original_dom->append_alias(new (std::nothrow) Json_string(20, 'x'));
954
955 /*
956 Write an array with one element into the JSON column. Make sure the
957 element is large enough to allow partial update with all the values in
958 the doms array.
959 */
960 Json_wrapper doc(original_dom->clone());
961 EXPECT_EQ(TYPE_OK, m_field.store_json(&doc));
962 EXPECT_FALSE(m_field.val_json(&doc));
963
964 StringBuffer<STRING_BUFFER_USUAL_SIZE> original;
965 EXPECT_FALSE(doc.to_binary(thd(), &original));
966
967 Json_wrapper new_value(dom->clone());
968
969 StringBuffer<STRING_BUFFER_USUAL_SIZE> buffer;
970 bool success = false;
971 bool replaced = false;
972
973 // First try with non-existing path and replace logic. Should be a no-op.
974 EXPECT_FALSE(doc.attempt_binary_update(&m_field, array_accessor(100),
975 &new_value, true, &buffer, &success,
976 &replaced));
977 EXPECT_TRUE(success);
978 EXPECT_FALSE(replaced);
979 EXPECT_EQ(0U, m_table->get_binary_diffs(&m_field)->size());
980 EXPECT_EQ(0U, m_table->get_logical_diffs(&m_field)->size());
981 m_table->clear_partial_update_diffs();
982
983 // Try with non-existing path and JSON_SET logic. Requires full update.
984 EXPECT_FALSE(doc.attempt_binary_update(&m_field, array_accessor(100),
985 &new_value, false, &buffer, &success,
986 &replaced));
987 EXPECT_FALSE(success);
988 EXPECT_FALSE(replaced);
989 EXPECT_EQ(0U, m_table->get_binary_diffs(&m_field)->size());
990 m_table->clear_partial_update_diffs();
991
992 // Try with a valid path. Expect success.
993 EXPECT_FALSE(doc.attempt_binary_update(&m_field, array_accessor(0),
994 &new_value, true, &buffer, &success,
995 &replaced));
996 EXPECT_TRUE(success);
997 EXPECT_TRUE(replaced);
998 EXPECT_NE(0U, m_table->get_binary_diffs(&m_field)->size());
999
1000 String str;
1001 new_value.to_string(&str, true, "test", [] { ASSERT_TRUE(false); });
1002 // Verify the updated document.
1003 {
1004 Json_array_ptr a(new (std::nothrow) Json_array);
1005 a->append_clone(dom);
1006 EXPECT_EQ(0, doc.compare(Json_wrapper(std::move(a))));
1007 }
1008
1009 // Verify the binary diffs.
1010 EXPECT_EQ(TYPE_OK, m_field.store_json(&doc));
1011 verify_binary_diffs(&m_field, m_table->get_binary_diffs(&m_field), original,
1012 buffer);
1013
1014 delete dom;
1015 }
1016 }
1017
1018 /**
1019 Test attempt_binary_update() with invalid input.
1020 */
1021 TEST_F(JsonDomTest, AttemptBinaryUpdate_Error) {
1022 EXPECT_FALSE(m_table->mark_column_for_partial_update(&m_field));
1023 EXPECT_FALSE(m_table->setup_partial_update(true));
1024 Json_wrapper doc(parse_json("[1,2,3,4]"));
1025 EXPECT_EQ(TYPE_OK, m_field.store_json(&doc));
1026 EXPECT_FALSE(m_field.val_json(&doc));
1027
1028 /*
1029 Create an invalid JSON value, which we will attempt to add to the document.
1030 */
1031 Json_wrapper error;
1032 EXPECT_TRUE(error.empty());
1033 EXPECT_EQ(enum_json_type::J_ERROR, error.type());
1034
1035 // Expect the calls to attempt_binary_update() to fail.
1036 const ErrorHandlerFunctionPointer old_error_handler_hook = error_handler_hook;
1037 error_handler_hook = my_message_sql;
1038 String buffer;
1039 bool success;
1040 bool replaced;
1041 {
1042 my_testing::Mock_error_handler handler(thd(), ER_INVALID_JSON_BINARY_DATA);
1043 EXPECT_TRUE(doc.attempt_binary_update(&m_field, array_accessor(0), &error,
1044 true, &buffer, &success, &replaced));
1045 EXPECT_EQ(1, handler.handle_called());
1046 }
1047 {
1048 my_testing::Mock_error_handler handler(thd(), ER_INVALID_JSON_BINARY_DATA);
1049 EXPECT_TRUE(doc.attempt_binary_update(&m_field, array_accessor(0), &error,
1050 false, &buffer, &success, &replaced));
1051 EXPECT_EQ(1, handler.handle_called());
1052 }
1053 error_handler_hook = old_error_handler_hook;
1054 }
1055
1056 /**
1057 Test that applying a set of diffs on a JSON document gives the expected
1058 return status.
1059 */
1060 void test_apply_json_diffs(Field_json *field, const Json_diff_vector &diffs,
1061 const char *orig_json,
1062 enum_json_diff_status expected_status) {
1063 SCOPED_TRACE("test_apply_json_diffs");
1064 field->table->clear_partial_update_diffs();
1065 if (orig_json == nullptr) {
1066 EXPECT_EQ(TYPE_OK, set_field_to_null(field));
1067 } else {
1068 field->set_notnull();
1069 Json_wrapper doc(parse_json(orig_json).release());
1070 EXPECT_FALSE(field->store_json(&doc));
1071 }
1072 EXPECT_EQ(orig_json == nullptr, field->is_null());
1073 EXPECT_EQ(expected_status, apply_json_diffs(field, &diffs));
1074 }
1075
1076 /**
1077 Test that applying a set of diffs on a JSON document is successful and gives
1078 the expected results.
1079 */
1080 void test_apply_json_diffs(Field_json *field, const Json_diff_vector &diffs,
1081 const char *orig_json, const char *new_json) {
1082 SCOPED_TRACE("test_apply_json_diffs");
1083 test_apply_json_diffs(field, diffs, orig_json,
1084 enum_json_diff_status::SUCCESS);
1085 Json_wrapper doc;
1086 EXPECT_FALSE(field->val_json(&doc));
1087 EXPECT_EQ(0, doc.compare(Json_wrapper(parse_json(new_json).release())));
1088
1089 TABLE *table = field->table;
1090 if (table->is_binary_diff_enabled(field)) {
1091 StringBuffer<STRING_BUFFER_USUAL_SIZE> original;
1092 EXPECT_FALSE(json_binary::serialize(
1093 table->in_use, parse_json(orig_json).get(), &original));
1094 StringBuffer<STRING_BUFFER_USUAL_SIZE> updated;
1095 EXPECT_FALSE(doc.to_binary(table->in_use, &updated));
1096 verify_binary_diffs(field, table->get_binary_diffs(field), original,
1097 updated);
1098 }
1099 }
1100
1101 static void do_apply_json_diffs_tests(Field_json *field) {
1102 Json_diff_vector diffs(
1103 Json_diff_vector::allocator_type(field->table->in_use->mem_root));
1104
1105 const auto expect_rejected = [field, &diffs](const char *json_text) {
1106 SCOPED_TRACE("");
1107 test_apply_json_diffs(field, diffs, json_text,
1108 enum_json_diff_status::REJECTED);
1109 };
1110
1111 const auto expect_success = [field, &diffs](const char *orig_json,
1112 const char *new_json) {
1113 SCOPED_TRACE("");
1114 test_apply_json_diffs(field, diffs, orig_json, new_json);
1115 };
1116
1117 {
1118 SCOPED_TRACE("");
1119 diffs.clear();
1120 expect_success("[1,2,3]", "[1,2,3]");
1121 expect_rejected(nullptr);
1122 }
1123
1124 {
1125 SCOPED_TRACE("");
1126 diffs.clear();
1127 diffs.add_diff(parse_path("$.a"), enum_json_diff_operation::REPLACE,
1128 create_dom_ptr<Json_int>(3));
1129 expect_success("{\"a\": 1, \"b\": 2}", "{\"a\": 3, \"b\": 2}");
1130 expect_rejected("{\"b\": 2}");
1131 expect_rejected("[1,2,3]");
1132 expect_rejected("123");
1133 expect_rejected(nullptr);
1134 }
1135
1136 {
1137 SCOPED_TRACE("");
1138 diffs.clear();
1139 diffs.add_diff(parse_path("$.a[1]"), enum_json_diff_operation::REPLACE,
1140 create_dom_ptr<Json_int>(3));
1141 expect_success("{\"a\": [1,2], \"b\": 2}", "{\"a\":[1,3], \"b\": 2}");
1142 expect_rejected("{\"a\": 2}");
1143 expect_rejected("{\"b\": 2}");
1144 expect_rejected("{\"a\": {\"b\":2}}");
1145 expect_rejected("[1,2,3]");
1146 expect_rejected("123");
1147 expect_rejected(nullptr);
1148 }
1149
1150 {
1151 SCOPED_TRACE("");
1152 diffs.clear();
1153 diffs.add_diff(parse_path("$.a[2]"), enum_json_diff_operation::INSERT,
1154 create_dom_ptr<Json_int>(3));
1155 expect_success("{\"a\":[]}", "{\"a\":[3]}");
1156 expect_success("{\"a\":[1]}", "{\"a\":[1,3]}");
1157 expect_success("{\"a\":[1,2]}", "{\"a\":[1,2,3]}");
1158 expect_success("{\"a\":[1,2,4]}", "{\"a\":[1,2,3,4]}");
1159 expect_rejected("{\"a\": 1, \"b\": 2}");
1160 expect_rejected("[]");
1161 expect_rejected(nullptr);
1162 }
1163
1164 {
1165 SCOPED_TRACE("");
1166 diffs.clear();
1167 diffs.add_diff(parse_path("$.a.b"), enum_json_diff_operation::INSERT,
1168 create_dom_ptr<Json_int>(3));
1169 expect_success("{\"a\":{\"c\":1}}", "{\"a\":{\"b\":3,\"c\":1}}");
1170 expect_rejected("{}");
1171 expect_rejected("[]");
1172 expect_rejected("{\"a\":{\"b\":1}}");
1173 expect_rejected(nullptr);
1174 }
1175
1176 {
1177 SCOPED_TRACE("");
1178 diffs.clear();
1179 diffs.add_diff(parse_path("$.a.b"), enum_json_diff_operation::REMOVE);
1180 expect_success("{\"a\":{\"b\":3,\"c\":1}}", "{\"a\":{\"c\":1}}");
1181 expect_rejected("{}");
1182 expect_rejected("[]");
1183 expect_rejected(nullptr);
1184 }
1185
1186 {
1187 SCOPED_TRACE("");
1188 diffs.clear();
1189 diffs.add_diff(parse_path("$[2]"), enum_json_diff_operation::REMOVE);
1190 expect_success("[1,2,3,4]", "[1,2,4]");
1191 expect_success("[1,2,3]", "[1,2]");
1192 expect_rejected("[1,2]");
1193 expect_rejected("[]");
1194 expect_rejected("{}");
1195 expect_rejected(nullptr);
1196 }
1197
1198 {
1199 SCOPED_TRACE("");
1200 diffs.clear();
1201 diffs.add_diff(parse_path("$[2]"), enum_json_diff_operation::REMOVE);
1202 diffs.add_diff(parse_path("$[3]"), enum_json_diff_operation::REMOVE);
1203 expect_success("[1,2,3,4,5,6]", "[1,2,4,6]");
1204 expect_rejected("[1,2,3,4]");
1205 expect_rejected("[]");
1206 expect_rejected(nullptr);
1207 }
1208
1209 {
1210 SCOPED_TRACE("");
1211 diffs.clear();
1212 diffs.add_diff(parse_path("$[2][3]"), enum_json_diff_operation::REMOVE);
1213 expect_success("[1,2,[3,4,5,6,7]]", "[1,2,[3,4,5,7]]");
1214 expect_rejected("[]");
1215 expect_rejected("[1,2,3,4,5,6]");
1216 expect_rejected(nullptr);
1217 }
1218
1219 {
1220 SCOPED_TRACE("");
1221 diffs.clear();
1222 diffs.add_diff(parse_path("$[0][0]"), enum_json_diff_operation::REMOVE);
1223 expect_success("[[1]]", "[[]]");
1224 expect_success("[[1,2,3],4,5]", "[[2,3],4,5]");
1225 expect_rejected("[1]");
1226 expect_rejected("{\"a\":1}");
1227 expect_rejected("[{\"a\":1}]");
1228 expect_rejected(nullptr);
1229 }
1230
1231 {
1232 SCOPED_TRACE("");
1233 for (auto op :
1234 {enum_json_diff_operation::REPLACE, enum_json_diff_operation::INSERT,
1235 enum_json_diff_operation::REMOVE}) {
1236 diffs.clear();
1237 diffs.add_diff(parse_path("$"), op, create_dom_ptr<Json_int>(1));
1238 expect_rejected("[1,2,3]");
1239 expect_rejected(nullptr);
1240 }
1241 }
1242 }
1243
1244 TEST_F(JsonDomTest, ApplyJsonDiffs) { do_apply_json_diffs_tests(&m_field); }
1245
1246 TEST_F(JsonDomTest, ApplyJsonDiffs_CollectBinaryDiffs) {
1247 EXPECT_FALSE(m_table->mark_column_for_partial_update(&m_field));
1248 EXPECT_FALSE(m_table->setup_partial_update(true));
1249 do_apply_json_diffs_tests(&m_field);
1250 }
1251
1252 /**
1253 Run a microbenchmarks that tests how fast Json_wrapper::seek() is on
1254 a wrapper that wraps a Json_dom.
1255
1256 @param num_iterations the number of iterations to run
1257 @param path the JSON path to search for
1258 @param need_only_one true if the search should stop after the first match
1259 @param expected_matches the number of expected matches
1260 */
1261 static void benchmark_dom_seek(size_t num_iterations, const Json_path &path,
1262 bool need_only_one, size_t expected_matches) {
1263 StopBenchmarkTiming();
1264
1265 Json_object o;
1266 for (size_t i = 0; i < 1000; ++i)
1267 o.add_alias(std::to_string(i), new (std::nothrow) Json_object());
1268
1269 Json_wrapper wr(&o);
1270 wr.set_alias();
1271
1272 StartBenchmarkTiming();
1273
1274 for (size_t i = 0; i < num_iterations; ++i) {
1275 Json_wrapper_vector hits(PSI_NOT_INSTRUMENTED);
1276 wr.seek(path, path.leg_count(), &hits, true, need_only_one);
1277 EXPECT_EQ(expected_matches, hits.size());
1278 }
1279
1280 StopBenchmarkTiming();
1281 }
1282
1283 /**
1284 Microbenchmark which tests how fast a lookup with an ellipsis is in
1285 a wrapper that wraps a Json_dom.
1286 */
1287 static void BM_JsonDomSearchEllipsis(size_t num_iterations) {
1288 benchmark_dom_seek(num_iterations, parse_path("$**.\"432\""), false, 1);
1289 }
1290 BENCHMARK(BM_JsonDomSearchEllipsis)
1291
1292 /**
1293 Microbenchmark which tests how fast a lookup with an ellipsis is in
1294 a wrapper that wraps a Json_dom, with the `need_only_one` flag set.
1295 */
1296 static void BM_JsonDomSearchEllipsis_OnlyOne(size_t num_iterations) {
1297 benchmark_dom_seek(num_iterations, parse_path("$**.\"432\""), true, 1);
1298 }
1299 BENCHMARK(BM_JsonDomSearchEllipsis_OnlyOne)
1300
1301 /**
1302 Microbenchmark which tests how fast a lookup of a JSON object member
1303 is in a wrapper that wraps a Json_dom.
1304 */
1305 static void BM_JsonDomSearchKey(size_t num_iterations) {
1306 benchmark_dom_seek(num_iterations, parse_path("$.\"432\""), false, 1);
1307 }
1308 BENCHMARK(BM_JsonDomSearchKey)
1309
1310 /**
1311 Microbenchmark for Json_dom::parse(const json_binary::Value &v).
1312
1313 @param num_iterations the number of iterations to run
1314 @param json_text the string to be parsed(after being converted to binary)
1315 */
1316 static void benchmark_dom_parse(size_t num_iterations, const char *json_text) {
1317 StopBenchmarkTiming();
1318 my_testing::Server_initializer initializer;
1319 initializer.SetUp();
1320
1321 auto dom = parse_json(json_text);
1322
1323 String buffer;
1324 EXPECT_FALSE(json_binary::serialize(initializer.thd(), dom.get(), &buffer));
1325
1326 json_binary::Value binary =
1327 json_binary::parse_binary(buffer.ptr(), buffer.length());
1328
1329 StartBenchmarkTiming();
1330 for (size_t i = 0; i < num_iterations; ++i) {
1331 Json_dom_ptr ptr = Json_dom::parse(binary);
1332 assert(ptr);
1333 }
1334
1335 StopBenchmarkTiming();
1336 }
1337
1338 /**
1339 Microbenchmark that tests Json_dom::parse(const json_binary::Value &v)
1340 with a deep JSON value
1341
1342 @param num_iterations the number of iterations to run
1343 */
1344 static void BM_JsonDomParseDeep(size_t num_iterations) {
1345 benchmark_dom_parse(num_iterations,
1346 "[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[["
1347 "[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[["
1348 R"({"key":123})"
1349 "]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]"
1350 "]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]");
1351 }
1352 BENCHMARK(BM_JsonDomParseDeep)
1353
1354 /**
1355 Microbenchmark that tests Json_dom::parse(const json_binary::Value &v)
1356 with a shallow JSON value
1357
1358 @param num_iterations the number of iterations to run
1359 */
1360 static void BM_JsonDomParseShallow(size_t num_iterations) {
1361 benchmark_dom_parse(num_iterations, R"([{"key":123}])");
1362 }
1363 BENCHMARK(BM_JsonDomParseShallow)
1364
1365 /**
1366 Run a microbenchmarks that tests how fast Json_wrapper::seek() is on
1367 a wrapper that wraps a binary JSON value.
1368
1369 @param num_iterations the number of iterations to run
1370 @param path the JSON path to search for
1371 @param need_only_one true if the search should stop after the first match
1372 @param expected_matches the number of expected matches
1373 */
1374 static void benchmark_binary_seek(size_t num_iterations, const Json_path &path,
1375 bool need_only_one, size_t expected_matches) {
1376 StopBenchmarkTiming();
1377
1378 Json_object o;
1379 for (size_t i = 0; i < 1000; ++i)
1380 o.add_alias(std::to_string(i), new (std::nothrow) Json_object());
1381
1382 my_testing::Server_initializer initializer;
1383 initializer.SetUp();
1384
1385 String buffer;
1386 EXPECT_FALSE(json_binary::serialize(initializer.thd(), &o, &buffer));
1387 json_binary::Value val =
1388 json_binary::parse_binary(buffer.ptr(), buffer.length());
1389
1390 StartBenchmarkTiming();
1391
1392 for (size_t i = 0; i < num_iterations; ++i) {
1393 Json_wrapper wr(val);
1394 Json_wrapper_vector hits(PSI_NOT_INSTRUMENTED);
1395 wr.seek(path, path.leg_count(), &hits, true, need_only_one);
1396 EXPECT_EQ(expected_matches, hits.size());
1397 }
1398
1399 StopBenchmarkTiming();
1400
1401 initializer.TearDown();
1402 }
1403
1404 /**
1405 Microbenchmark which tests how fast a lookup with an ellipsis is in
1406 a Json_wrapper which wraps a binary JSON value.
1407 */
1408 static void BM_JsonBinarySearchEllipsis(size_t num_iterations) {
1409 benchmark_binary_seek(num_iterations, parse_path("$**.\"432\""), false, 1);
1410 }
1411 BENCHMARK(BM_JsonBinarySearchEllipsis)
1412
1413 /**
1414 Microbenchmark which tests how fast a lookup with an ellipsis is in
1415 a Json_wrapper which wraps a binary JSON value, with the `need_only_one`
1416 flag set.
1417 */
1418 static void BM_JsonBinarySearchEllipsis_OnlyOne(size_t num_iterations) {
1419 benchmark_binary_seek(num_iterations, parse_path("$**.\"432\""), true, 1);
1420 }
1421 BENCHMARK(BM_JsonBinarySearchEllipsis_OnlyOne)
1422
1423 /**
1424 Microbenchmark which tests how fast a lookup of a JSON object member
1425 is in a Json_wrapper which wraps a binary JSON value.
1426 */
1427 static void BM_JsonBinarySearchKey(size_t num_iterations) {
1428 benchmark_binary_seek(num_iterations, parse_path("$.\"432\""), false, 1);
1429 }
1430 BENCHMARK(BM_JsonBinarySearchKey)
1431
1432 /**
1433 Microbenchmark which tests the performance of
1434 Json_wrapper::to_string() when it's called on a JSON string value
1435 with no special characters that need quoting.
1436 */
1437 static void BM_JsonStringToString_Plain(size_t num_iterations) {
1438 StopBenchmarkTiming();
1439
1440 my_testing::Server_initializer initializer;
1441 initializer.SetUp();
1442
1443 const Json_string str("This is a plain string with no special characters!");
1444 const Json_wrapper wr(str.clone());
1445 const size_t quoted_length = str.size() + 2;
1446
1447 StartBenchmarkTiming();
1448
1449 for (size_t i = 0; i < num_iterations; ++i) {
1450 String buf;
1451 wr.to_string(&buf, true, "test", [] { ASSERT_TRUE(false); });
1452 EXPECT_EQ(quoted_length, buf.length());
1453 }
1454
1455 StopBenchmarkTiming();
1456
1457 initializer.TearDown();
1458 }
1459 BENCHMARK(BM_JsonStringToString_Plain)
1460
1461 /**
1462 Microbenchmark which tests the performance of
1463 Json_wrapper::to_string() when it's called on a JSON string value
1464 which contains some special characters that need quoting.
1465 */
1466 static void BM_JsonStringToString_SpecialChars(size_t num_iterations) {
1467 StopBenchmarkTiming();
1468
1469 my_testing::Server_initializer initializer;
1470 initializer.SetUp();
1471
1472 const Json_string str("This\nstring\nspans\nmultiple\nlines.\f\nabc\x1Dxyz");
1473 const Json_wrapper wr(str.clone());
1474
1475 StartBenchmarkTiming();
1476
1477 for (size_t i = 0; i < num_iterations; ++i) {
1478 String buf;
1479 wr.to_string(&buf, true, "test", [] { ASSERT_TRUE(false); });
1480 EXPECT_LT(str.size(), buf.length());
1481 }
1482
1483 StopBenchmarkTiming();
1484
1485 initializer.TearDown();
1486 }
1487 BENCHMARK(BM_JsonStringToString_SpecialChars)
1488
1489 /**
1490 Microbenchmark which tests the performance of
1491 Json_wrapper::to_string() when it's called on a JSON object with
1492 nested values.
1493 */
1494 static void BM_JsonObjectToString(size_t num_iterations) {
1495 StopBenchmarkTiming();
1496
1497 my_testing::Server_initializer initializer;
1498 initializer.SetUp();
1499
1500 const Json_wrapper wr(
1501 parse_json("{\"name\": \"John Doe\", \"age\": 42, "
1502 "\"points\": [1, 3.14e0, 2.7, null], "
1503 "\"id\": \"xyzxyzxyzxyz\"}"));
1504
1505 StartBenchmarkTiming();
1506
1507 for (size_t i = 0; i < num_iterations; ++i) {
1508 String buf;
1509 wr.to_string(&buf, true, "test", [] { ASSERT_TRUE(false); });
1510 EXPECT_LT(0U, buf.length());
1511 }
1512
1513 StopBenchmarkTiming();
1514
1515 initializer.TearDown();
1516 }
1517 BENCHMARK(BM_JsonObjectToString)
1518
1519 /**
1520 Tests the performance of Json_wrapper::to_string() when it's called
1521 on a JSON array with boolean elements.
1522 */
1523 static void BM_JsonBooleanArrayToString(size_t num_iterations) {
1524 StopBenchmarkTiming();
1525
1526 my_testing::Server_initializer initializer;
1527 initializer.SetUp();
1528
1529 Json_array_ptr array = create_dom_ptr<Json_array>();
1530 for (size_t i = 0; i < 1000; ++i) {
1531 array->append_alias(create_dom_ptr<Json_boolean>(i % 2 == 0));
1532 }
1533 Json_wrapper wrapper(std::move(array));
1534
1535 StartBenchmarkTiming();
1536
1537 for (size_t i = 0; i < num_iterations; ++i) {
1538 String buf;
1539 wrapper.to_string(&buf, true, "test", [] { ASSERT_TRUE(false); });
1540 EXPECT_LT(0U, buf.length());
1541 }
1542
1543 StopBenchmarkTiming();
1544
1545 initializer.TearDown();
1546 }
1547 BENCHMARK(BM_JsonBooleanArrayToString)
1548
1549 /**
1550 Tests the performance of Json_wrapper::to_string() when it's called
1551 on a JSON array with double elements.
1552 */
1553 static void BM_JsonDoubleArrayToString(size_t num_iterations) {
1554 StopBenchmarkTiming();
1555
1556 my_testing::Server_initializer initializer;
1557 initializer.SetUp();
1558
1559 Json_array_ptr array = create_dom_ptr<Json_array>();
1560 for (size_t i = 0; i < 1000; ++i) {
1561 array->append_alias(create_dom_ptr<Json_double>(i));
1562 }
1563 Json_wrapper wrapper(std::move(array));
1564
1565 StartBenchmarkTiming();
1566
1567 for (size_t i = 0; i < num_iterations; ++i) {
1568 String buf;
1569 wrapper.to_string(&buf, true, "test", [] { ASSERT_TRUE(false); });
1570 EXPECT_LT(0U, buf.length());
1571 }
1572
1573 StopBenchmarkTiming();
1574
1575 initializer.TearDown();
1576 }
1577 BENCHMARK(BM_JsonDoubleArrayToString)
1578
1579 /**
1580 Tests the performance of Json_wrapper::to_string() when it's called
1581 on a JSON array with decimal elements.
1582 */
1583 static void BM_JsonDecimalArrayToString(size_t num_iterations) {
1584 StopBenchmarkTiming();
1585
1586 my_testing::Server_initializer initializer;
1587 initializer.SetUp();
1588
1589 Json_array_ptr array = create_dom_ptr<Json_array>();
1590 for (size_t i = 0; i < 1000; ++i) {
1591 my_decimal decimal;
1592 EXPECT_FALSE(double2my_decimal(0, i, &decimal));
1593 array->append_alias(create_dom_ptr<Json_decimal>(decimal));
1594 }
1595 Json_wrapper wrapper(std::move(array));
1596
1597 StartBenchmarkTiming();
1598
1599 for (size_t i = 0; i < num_iterations; ++i) {
1600 String buf;
1601 wrapper.to_string(&buf, true, "test", [] { ASSERT_TRUE(false); });
1602 EXPECT_LT(0U, buf.length());
1603 }
1604
1605 StopBenchmarkTiming();
1606
1607 initializer.TearDown();
1608 }
1609 BENCHMARK(BM_JsonDecimalArrayToString)
1610
1611 /**
1612 Tests the performance of Json_wrapper::to_string() when it's called
1613 on a JSON array with date elements.
1614 */
1615 static void BM_JsonDateArrayToString(size_t num_iterations) {
1616 StopBenchmarkTiming();
1617
1618 my_testing::Server_initializer initializer;
1619 initializer.SetUp();
1620
1621 Json_array_ptr array = create_dom_ptr<Json_array>();
1622 MysqlTime date(2018, 11, 20, 0, 0, 0, 0, false, MYSQL_TIMESTAMP_DATE);
1623 for (size_t i = 0; i < 1000; ++i) {
1624 array->append_alias(create_dom_ptr<Json_datetime>(date, MYSQL_TYPE_DATE));
1625 }
1626 Json_wrapper wrapper(std::move(array));
1627
1628 StartBenchmarkTiming();
1629
1630 for (size_t i = 0; i < num_iterations; ++i) {
1631 String buf;
1632 wrapper.to_string(&buf, true, "test", [] { ASSERT_TRUE(false); });
1633 EXPECT_LT(0U, buf.length());
1634 }
1635
1636 StopBenchmarkTiming();
1637
1638 initializer.TearDown();
1639 }
1640 BENCHMARK(BM_JsonDateArrayToString)
1641
1642 /**
1643 Tests the performance of Json_wrapper_object_iterator when iterating
1644 over a JSON object in the DOM representation.
1645 */
1646 static void BM_JsonWrapperObjectIteratorDOM(size_t num_iterations) {
1647 StopBenchmarkTiming();
1648
1649 my_testing::Server_initializer initializer;
1650 initializer.SetUp();
1651
1652 Json_object object;
1653 for (size_t i = 0; i < 1000; ++i) {
1654 object.add_alias("JSON object member number " + std::to_string(i),
1655 create_dom_ptr<Json_null>());
1656 }
1657
1658 Json_wrapper wrapper(&object);
1659 wrapper.set_alias();
1660
1661 StartBenchmarkTiming();
1662
1663 for (size_t i = 0; i < num_iterations; ++i) {
1664 for (const auto &it : Json_object_wrapper(wrapper)) {
1665 EXPECT_NE(0U, it.first.length);
1666 EXPECT_EQ(enum_json_type::J_NULL, it.second.type());
1667 }
1668 }
1669
1670 StopBenchmarkTiming();
1671
1672 initializer.TearDown();
1673 }
1674 BENCHMARK(BM_JsonWrapperObjectIteratorDOM)
1675
1676 /**
1677 Tests the performance of Json_wrapper_object_iterator when iterating
1678 over a JSON object in the binary representation.
1679 */
1680 static void BM_JsonWrapperObjectIteratorBinary(size_t num_iterations) {
1681 StopBenchmarkTiming();
1682
1683 my_testing::Server_initializer initializer;
1684 initializer.SetUp();
1685
1686 Json_object dom_object;
1687 for (size_t i = 0; i < 1000; ++i) {
1688 dom_object.add_alias("JSON object member number " + std::to_string(i),
1689 create_dom_ptr<Json_null>());
1690 }
1691
1692 String serialized_object;
1693 EXPECT_FALSE(json_binary::serialize(initializer.thd(), &dom_object,
1694 &serialized_object));
1695 Json_wrapper wrapper(json_binary::parse_binary(serialized_object.ptr(),
1696 serialized_object.length()));
1697 EXPECT_EQ(enum_json_type::J_OBJECT, wrapper.type());
1698
1699 StartBenchmarkTiming();
1700
1701 for (size_t i = 0; i < num_iterations; ++i) {
1702 for (const auto &it : Json_object_wrapper(wrapper)) {
1703 EXPECT_NE(0U, it.first.length);
1704 EXPECT_EQ(enum_json_type::J_NULL, it.second.type());
1705 }
1706 }
1707
1708 StopBenchmarkTiming();
1709
1710 initializer.TearDown();
1711 }
1712 BENCHMARK(BM_JsonWrapperObjectIteratorBinary)
1713
1714 } // namespace json_dom_unittest