Debian Codegraph @

unittest/gunit/json_binary-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 #include <string>
28
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/error_handler.h"
34 #include "sql/sql_class.h"
35 #include "sql/sql_time.h"
36 #include "sql_string.h"
37 #include "unittest/gunit/benchmark.h"
38 #include "unittest/gunit/test_utils.h"
39
40 namespace json_binary_unittest {
41
42 using namespace json_binary;
43
44 class JsonBinaryTest : public ::testing::Test {
45 protected:
46 void SetUp() override { initializer.SetUp(); }
47 void TearDown() override { initializer.TearDown(); }
48 my_testing::Server_initializer initializer;
49 THD *thd() const { return initializer.thd(); }
50 };
51
52 /**
53 Get a copy of the string value represented by val.
54 */
55 static std::string get_string(const Value &val) {
56 return std::string(val.get_data(), val.get_data_length());
57 }
58
59 static my_decimal create_decimal(double d) {
60 my_decimal dec;
61 EXPECT_EQ(E_DEC_OK, double2my_decimal(E_DEC_FATAL_ERROR, d, &dec));
62 return dec;
63 }
64
65 static Json_dom_ptr parse_json(const char *json_text) {
66 auto dom = Json_dom::parse(
67 json_text, strlen(json_text), [](const char *, size_t) {},
68 [] { ASSERT_TRUE(false); });
69 EXPECT_NE(nullptr, dom);
70 return dom;
71 }
72
73 TEST_F(JsonBinaryTest, BasicTest) {
74 std::string std_string;
75 Json_dom_ptr dom = parse_json("false");
76 String buf;
77 EXPECT_FALSE(serialize(thd(), dom.get(), &buf));
78 Value val1 = parse_binary(buf.ptr(), buf.length());
79 EXPECT_TRUE(val1.is_valid());
80 EXPECT_EQ(Value::LITERAL_FALSE, val1.type());
81 EXPECT_FALSE(val1.to_std_string(&std_string, [] { ASSERT_TRUE(false); }));
82 EXPECT_STREQ("false", std_string.c_str());
83 EXPECT_FALSE(
84 val1.to_pretty_std_string(&std_string, [] { ASSERT_TRUE(false); }));
85 EXPECT_STREQ("false", std_string.c_str());
86
87 dom = parse_json("-123");
88 EXPECT_FALSE(serialize(thd(), dom.get(), &buf));
89 Value val2 = parse_binary(buf.ptr(), buf.length());
90 EXPECT_TRUE(val2.is_valid());
91 EXPECT_EQ(Value::INT, val2.type());
92 EXPECT_EQ(-123LL, val2.get_int64());
93 EXPECT_FALSE(val2.to_std_string(&std_string, [] { ASSERT_TRUE(false); }));
94 EXPECT_STREQ("-123", std_string.c_str());
95 EXPECT_FALSE(
96 val2.to_pretty_std_string(&std_string, [] { ASSERT_TRUE(false); }));
97 EXPECT_STREQ("-123", std_string.c_str());
98
99 dom = parse_json("3.14");
100 EXPECT_FALSE(serialize(thd(), dom.get(), &buf));
101 Value val3 = parse_binary(buf.ptr(), buf.length());
102 EXPECT_TRUE(val3.is_valid());
103 EXPECT_EQ(Value::DOUBLE, val3.type());
104 EXPECT_EQ(3.14, val3.get_double());
105
106 dom = parse_json("18446744073709551615");
107 EXPECT_FALSE(serialize(thd(), dom.get(), &buf));
108 Value val4 = parse_binary(buf.ptr(), buf.length());
109 EXPECT_TRUE(val4.is_valid());
110 EXPECT_EQ(Value::UINT, val4.type());
111 EXPECT_EQ(18446744073709551615ULL, val4.get_uint64());
112
113 dom = parse_json("\"abc\"");
114 EXPECT_FALSE(serialize(thd(), dom.get(), &buf));
115 Value val5 = parse_binary(buf.ptr(), buf.length());
116 EXPECT_TRUE(val5.is_valid());
117 EXPECT_EQ(Value::STRING, val5.type());
118 EXPECT_EQ("abc", get_string(val5));
119
120 dom = parse_json("[ 1, 2, 3 ]");
121 EXPECT_FALSE(serialize(thd(), dom.get(), &buf));
122 Value val6 = parse_binary(buf.ptr(), buf.length());
123 EXPECT_TRUE(val6.is_valid());
124 EXPECT_EQ(Value::ARRAY, val6.type());
125 EXPECT_FALSE(val6.large_format());
126 EXPECT_EQ(3U, val6.element_count());
127 for (int i = 0; i < 3; i++) {
128 Value v = val6.element(i);
129 EXPECT_EQ(Value::INT, v.type());
130 EXPECT_EQ(i + 1, v.get_int64());
131 }
132 EXPECT_EQ(Value::ERROR, val6.element(3).type());
133 EXPECT_FALSE(val6.to_std_string(&std_string, [] { ASSERT_TRUE(false); }));
134 EXPECT_STREQ("[1, 2, 3]", std_string.c_str());
135 EXPECT_FALSE(
136 val6.to_pretty_std_string(&std_string, [] { ASSERT_TRUE(false); }));
137 EXPECT_STREQ("[\n 1,\n 2,\n 3\n]", std_string.c_str());
138
139 dom = parse_json("[ 1, [ \"a\", [ 3.14 ] ] ]");
140 EXPECT_FALSE(serialize(thd(), dom.get(), &buf));
141 // Top-level doc is an array of size 2.
142 Value val7 = parse_binary(buf.ptr(), buf.length());
143 EXPECT_TRUE(val7.is_valid());
144 EXPECT_EQ(Value::ARRAY, val7.type());
145 EXPECT_EQ(2U, val7.element_count());
146 // First element is the integer 1.
147 Value v7_1 = val7.element(0);
148 EXPECT_TRUE(v7_1.is_valid());
149 EXPECT_EQ(Value::INT, v7_1.type());
150 EXPECT_EQ(1, v7_1.get_int64());
151 // The second element is a nested array of size 2.
152 Value v7_2 = val7.element(1);
153 EXPECT_TRUE(v7_2.is_valid());
154 EXPECT_EQ(Value::ARRAY, v7_2.type());
155 EXPECT_EQ(2U, v7_2.element_count());
156 // The first element of the nested array is the string "a".
157 Value v7_3 = v7_2.element(0);
158 EXPECT_TRUE(v7_3.is_valid());
159 EXPECT_EQ(Value::STRING, v7_3.type());
160 EXPECT_EQ("a", get_string(v7_3));
161 // The second element of the nested array is yet another array.
162 Value v7_4 = v7_2.element(1);
163 EXPECT_TRUE(v7_4.is_valid());
164 EXPECT_EQ(Value::ARRAY, v7_4.type());
165 // The second nested array has one element, the double 3.14.
166 EXPECT_EQ(1U, v7_4.element_count());
167 Value v7_5 = v7_4.element(0);
168 EXPECT_TRUE(v7_5.is_valid());
169 EXPECT_EQ(Value::DOUBLE, v7_5.type());
170 EXPECT_EQ(3.14, v7_5.get_double());
171 EXPECT_FALSE(val7.to_std_string(&std_string, [] { ASSERT_TRUE(false); }));
172 EXPECT_STREQ("[1, [\"a\", [3.14]]]", std_string.c_str());
173
174 dom = parse_json("{\"key\" : \"val\"}");
175 EXPECT_FALSE(serialize(thd(), dom.get(), &buf));
176 Value val8 = parse_binary(buf.ptr(), buf.length());
177 EXPECT_TRUE(val8.is_valid());
178 EXPECT_EQ(Value::OBJECT, val8.type());
179 EXPECT_FALSE(val8.large_format());
180 EXPECT_EQ(1U, val8.element_count());
181 Value val8_k = val8.key(0);
182 EXPECT_TRUE(val8_k.is_valid());
183 EXPECT_EQ(Value::STRING, val8_k.type());
184 EXPECT_EQ("key", get_string(val8_k));
185 Value val8_v = val8.element(0);
186 EXPECT_TRUE(val8_v.is_valid());
187 EXPECT_EQ(Value::STRING, val8_v.type());
188 EXPECT_EQ("val", get_string(val8_v));
189 EXPECT_EQ(Value::ERROR, val8.key(1).type());
190 EXPECT_EQ(Value::ERROR, val8.element(1).type());
191 EXPECT_FALSE(
192 val8.to_pretty_std_string(&std_string, [] { ASSERT_TRUE(false); }));
193 EXPECT_STREQ("{\n \"key\": \"val\"\n}", std_string.c_str());
194
195 Value v8_v1 = val8.lookup("key");
196 EXPECT_EQ(Value::STRING, v8_v1.type());
197 EXPECT_TRUE(v8_v1.is_valid());
198 EXPECT_EQ("val", get_string(v8_v1));
199
200 dom = parse_json("{ \"a\" : \"b\", \"c\" : [ \"d\" ] }");
201 EXPECT_FALSE(serialize(thd(), dom.get(), &buf));
202 Value val9 = parse_binary(buf.ptr(), buf.length());
203 EXPECT_TRUE(val9.is_valid());
204 EXPECT_EQ(Value::OBJECT, val9.type());
205 EXPECT_EQ(2U, val9.element_count());
206 Value v9_k1 = val9.key(0);
207 EXPECT_EQ(Value::STRING, v9_k1.type());
208 EXPECT_EQ("a", get_string(v9_k1));
209 Value v9_v1 = val9.element(0);
210 EXPECT_EQ(Value::STRING, v9_v1.type());
211 EXPECT_EQ("b", get_string(v9_v1));
212 Value v9_k2 = val9.key(1);
213 EXPECT_EQ(Value::STRING, v9_k2.type());
214 EXPECT_EQ("c", get_string(v9_k2));
215 Value v9_v2 = val9.element(1);
216 EXPECT_EQ(Value::ARRAY, v9_v2.type());
217 EXPECT_EQ(1U, v9_v2.element_count());
218 Value v9_v2_1 = v9_v2.element(0);
219 EXPECT_EQ(Value::STRING, v9_v2_1.type());
220 EXPECT_EQ("d", get_string(v9_v2_1));
221
222 EXPECT_EQ("b", get_string(val9.lookup("a")));
223 Value v9_c = val9.lookup("c");
224 EXPECT_EQ(Value::ARRAY, v9_c.type());
225 EXPECT_EQ(1U, v9_c.element_count());
226 Value v9_c1 = v9_c.element(0);
227 EXPECT_EQ(Value::STRING, v9_c1.type());
228 EXPECT_EQ("d", get_string(v9_c1));
229
230 char blob[4];
231 int4store(blob, 0xCAFEBABEU);
232 Json_opaque opaque(MYSQL_TYPE_TINY_BLOB, blob, 4);
233 EXPECT_FALSE(serialize(thd(), &opaque, &buf));
234 Value val10 = parse_binary(buf.ptr(), buf.length());
235 EXPECT_TRUE(val10.is_valid());
236 EXPECT_EQ(Value::OPAQUE, val10.type());
237 EXPECT_EQ(MYSQL_TYPE_TINY_BLOB, val10.field_type());
238 EXPECT_EQ(4U, val10.get_data_length());
239 EXPECT_EQ(0xCAFEBABEU, uint4korr(val10.get_data()));
240
241 dom = parse_json("[true,false,null,0,\"0\",\"\",{},[]]");
242 EXPECT_FALSE(serialize(thd(), dom.get(), &buf));
243 Value val11 = parse_binary(buf.ptr(), buf.length());
244 EXPECT_TRUE(val11.is_valid());
245 EXPECT_EQ(Value::ARRAY, val11.type());
246 EXPECT_EQ(8U, val11.element_count());
247 EXPECT_EQ(Value::LITERAL_TRUE, val11.element(0).type());
248 EXPECT_EQ(Value::LITERAL_FALSE, val11.element(1).type());
249 EXPECT_EQ(Value::LITERAL_NULL, val11.element(2).type());
250 EXPECT_EQ(Value::INT, val11.element(3).type());
251 EXPECT_EQ(Value::STRING, val11.element(4).type());
252 EXPECT_EQ(Value::STRING, val11.element(5).type());
253 EXPECT_EQ(Value::OBJECT, val11.element(6).type());
254 EXPECT_EQ(Value::ARRAY, val11.element(7).type());
255 EXPECT_EQ(0, val11.element(3).get_int64());
256 EXPECT_EQ("0", get_string(val11.element(4)));
257 EXPECT_EQ("", get_string(val11.element(5)));
258 EXPECT_EQ(0U, val11.element(6).element_count());
259 EXPECT_EQ(0U, val11.element(7).element_count());
260
261 dom = parse_json("{}");
262 EXPECT_FALSE(serialize(thd(), dom.get(), &buf));
263 Value val12 = parse_binary(buf.ptr(), buf.length());
264 EXPECT_TRUE(val12.is_valid());
265 EXPECT_EQ(Value::OBJECT, val12.type());
266 EXPECT_EQ(0U, val12.element_count());
267 EXPECT_EQ(Value::ERROR, val12.lookup("").type());
268 EXPECT_EQ(Value::ERROR, val12.lookup("key").type());
269 EXPECT_FALSE(val12.lookup("no such key").is_valid());
270
271 dom = parse_json("[]");
272 EXPECT_FALSE(serialize(thd(), dom.get(), &buf));
273 Value val13 = parse_binary(buf.ptr(), buf.length());
274 EXPECT_TRUE(val13.is_valid());
275 EXPECT_EQ(Value::ARRAY, val13.type());
276 EXPECT_EQ(0U, val13.element_count());
277
278 dom = parse_json(
279 "{\"key1\":1, \"key2\":2, \"key1\":3, \"key1\\u0000x\":4, "
280 "\"key1\\u0000y\":5, \"a\":6, \"ab\":7, \"b\":8, \"\":9, "
281 "\"\":10}");
282 const std::string expected_keys[] = {"",
283 "a",
284 "b",
285 "ab",
286 "key1",
287 "key2",
288 std::string("key1\0x", 6),
289 std::string("key1\0y", 6)};
290 const int64 expected_values[] = {10, 6, 8, 7, 3, 2, 4, 5};
291 EXPECT_FALSE(serialize(thd(), dom.get(), &buf));
292 Value val14 = parse_binary(buf.ptr(), buf.length());
293 EXPECT_TRUE(val14.is_valid());
294 EXPECT_EQ(Value::OBJECT, val14.type());
295 EXPECT_EQ(8U, val14.element_count());
296 for (size_t i = 0; i < val14.element_count(); i++) {
297 EXPECT_EQ(expected_keys[i], get_string(val14.key(i)));
298
299 Value val = val14.element(i);
300 EXPECT_EQ(Value::INT, val.type());
301 EXPECT_EQ(expected_values[i], val.get_int64());
302
303 Value val_lookup = val14.lookup(expected_keys[i]);
304 EXPECT_EQ(Value::INT, val_lookup.type());
305 EXPECT_EQ(expected_values[i], val_lookup.get_int64());
306 }
307
308 // Store a decimal.
309 my_decimal md = create_decimal(123.45);
310 EXPECT_EQ(5U, md.precision());
311 EXPECT_EQ(2, md.frac);
312
313 Json_decimal jd(md);
314 EXPECT_FALSE(serialize(thd(), &jd, &buf));
315 Value val15 = parse_binary(buf.ptr(), buf.length());
316 EXPECT_TRUE(val15.is_valid());
317 EXPECT_EQ(Value::OPAQUE, val15.type());
318 EXPECT_EQ(MYSQL_TYPE_NEWDECIMAL, val15.field_type());
319
320 my_decimal md_out;
321 EXPECT_FALSE(Json_decimal::convert_from_binary(
322 val15.get_data(), val15.get_data_length(), &md_out));
323 EXPECT_EQ(5U, md_out.precision());
324 EXPECT_EQ(2, md_out.frac);
325 double d_out;
326 EXPECT_EQ(E_DEC_OK, my_decimal2double(E_DEC_FATAL_ERROR, &md_out, &d_out));
327 EXPECT_EQ(123.45, d_out);
328 }
329
330 TEST_F(JsonBinaryTest, EmptyDocument) {
331 /*
332 An empty binary document is interpreted as the JSON null literal.
333 This is a special case to handle NULL values inserted into NOT
334 NULL columns using INSERT IGNORE or similar mechanisms.
335 */
336 Value val = parse_binary("", 0);
337 EXPECT_EQ(Value::LITERAL_NULL, val.type());
338 }
339
340 static MYSQL_TIME create_time() {
341 const char *tstr = "13:14:15.654321";
342 MYSQL_TIME t;
343 MYSQL_TIME_STATUS status;
344 EXPECT_FALSE(
345 str_to_time(&my_charset_utf8mb4_bin, tstr, strlen(tstr), &t, 0, &status));
346 return t;
347 }
348
349 static MYSQL_TIME create_date() {
350 const char *dstr = "20140517";
351 MYSQL_TIME d;
352 MYSQL_TIME_STATUS status;
353 EXPECT_FALSE(str_to_datetime(&my_charset_utf8mb4_bin, dstr, strlen(dstr), &d,
354 0, &status));
355 return d;
356 }
357
358 static MYSQL_TIME create_datetime() {
359 const char *dtstr = "2015-01-15 15:16:17.123456";
360 MYSQL_TIME dt;
361 MYSQL_TIME_STATUS status;
362 EXPECT_FALSE(str_to_datetime(&my_charset_utf8mb4_bin, dtstr, strlen(dtstr),
363 &dt, 0, &status));
364 return dt;
365 }
366
367 /*
368 Test storing of TIME, DATE and DATETIME.
369 */
370 TEST_F(JsonBinaryTest, DateAndTimeTest) {
371 // Create an array that contains a TIME, a DATE and a DATETIME.
372 Json_array array;
373 Json_datetime tt(create_time(), MYSQL_TYPE_TIME);
374 Json_datetime td(create_date(), MYSQL_TYPE_DATE);
375 Json_datetime tdt(create_datetime(), MYSQL_TYPE_DATETIME);
376 array.append_clone(&tt);
377 array.append_clone(&td);
378 array.append_clone(&tdt);
379
380 // Store the array ...
381 String buf;
382 EXPECT_FALSE(serialize(thd(), &array, &buf));
383
384 // ... and read it back.
385 Value val = parse_binary(buf.ptr(), buf.length());
386 EXPECT_TRUE(val.is_valid());
387 EXPECT_EQ(Value::ARRAY, val.type());
388 EXPECT_EQ(3U, val.element_count());
389
390 // The first element should be the TIME "13:14:15.654321".
391 Value t_val = val.element(0);
392 EXPECT_EQ(Value::OPAQUE, t_val.type());
393 EXPECT_EQ(MYSQL_TYPE_TIME, t_val.field_type());
394 const size_t json_datetime_packed_size = Json_datetime::PACKED_SIZE;
395 EXPECT_EQ(json_datetime_packed_size, t_val.get_data_length());
396 MYSQL_TIME t_out;
397 Json_datetime::from_packed(t_val.get_data(), t_val.field_type(), &t_out);
398 EXPECT_EQ(13U, t_out.hour);
399 EXPECT_EQ(14U, t_out.minute);
400 EXPECT_EQ(15U, t_out.second);
401 EXPECT_EQ(654321U, t_out.second_part);
402 EXPECT_FALSE(t_out.neg);
403 EXPECT_EQ(MYSQL_TIMESTAMP_TIME, t_out.time_type);
404
405 // The second element should be the DATE "2014-05-17".
406 Value d_val = val.element(1);
407 EXPECT_EQ(Value::OPAQUE, d_val.type());
408 EXPECT_EQ(MYSQL_TYPE_DATE, d_val.field_type());
409 EXPECT_EQ(json_datetime_packed_size, d_val.get_data_length());
410 MYSQL_TIME d_out;
411 Json_datetime::from_packed(d_val.get_data(), d_val.field_type(), &d_out);
412 EXPECT_EQ(2014U, d_out.year);
413 EXPECT_EQ(5U, d_out.month);
414 EXPECT_EQ(17U, d_out.day);
415 EXPECT_FALSE(d_out.neg);
416 EXPECT_EQ(MYSQL_TIMESTAMP_DATE, d_out.time_type);
417
418 // The third element should be the DATETIME "2015-01-15 15:16:17.123456".
419 Value dt_val = val.element(2);
420 EXPECT_EQ(Value::OPAQUE, dt_val.type());
421 EXPECT_EQ(MYSQL_TYPE_DATETIME, dt_val.field_type());
422 EXPECT_EQ(json_datetime_packed_size, dt_val.get_data_length());
423 MYSQL_TIME dt_out;
424 Json_datetime::from_packed(dt_val.get_data(), dt_val.field_type(), &dt_out);
425 EXPECT_EQ(2015U, dt_out.year);
426 EXPECT_EQ(1U, dt_out.month);
427 EXPECT_EQ(15U, dt_out.day);
428 EXPECT_EQ(15U, dt_out.hour);
429 EXPECT_EQ(16U, dt_out.minute);
430 EXPECT_EQ(17U, dt_out.second);
431 EXPECT_EQ(123456U, dt_out.second_part);
432 EXPECT_FALSE(dt_out.neg);
433 EXPECT_EQ(MYSQL_TIMESTAMP_DATETIME, dt_out.time_type);
434 }
435
436 /*
437 Validate that the contents of an array are as expected. The array
438 should contain values that alternate between literal true, literal
439 false, literal null and the string "a".
440 */
441 void validate_array_contents(const Value &array, size_t expected_size) {
442 EXPECT_EQ(Value::ARRAY, array.type());
443 EXPECT_TRUE(array.is_valid());
444 EXPECT_EQ(expected_size, array.element_count());
445 for (size_t i = 0; i < array.element_count(); i++) {
446 Value val = array.element(i);
447 EXPECT_TRUE(val.is_valid());
448 Value::enum_type t = val.type();
449 if (i % 4 == 0)
450 EXPECT_EQ(Value::LITERAL_TRUE, t);
451 else if (i % 4 == 1)
452 EXPECT_EQ(Value::LITERAL_FALSE, t);
453 else if (i % 4 == 2)
454 EXPECT_EQ(Value::LITERAL_NULL, t);
455 else {
456 EXPECT_EQ(Value::STRING, t);
457 EXPECT_EQ("a", get_string(val));
458 }
459 }
460 }
461
462 /*
463 Test some arrays and objects that exceed 64KB. Arrays and objects
464 are stored in a different format if more than two bytes are required
465 for the internal offsets.
466 */
467 TEST_F(JsonBinaryTest, LargeDocumentTest) {
468 Json_array array;
469 Json_boolean literal_true(true);
470 Json_boolean literal_false(false);
471 Json_null literal_null;
472 Json_string string("a");
473
474 for (int i = 0; i < 20000; i++) {
475 array.append_clone(&literal_true);
476 array.append_clone(&literal_false);
477 array.append_clone(&literal_null);
478 array.append_clone(&string);
479 }
480 EXPECT_EQ(80000U, array.size());
481
482 String buf;
483 EXPECT_FALSE(serialize(thd(), &array, &buf));
484 Value val1 = parse_binary(buf.ptr(), buf.length());
485 EXPECT_TRUE(val1.large_format());
486 {
487 SCOPED_TRACE("");
488 validate_array_contents(val1, array.size());
489 }
490
491 /*
492 Extract the raw binary representation of the large array, and verify
493 that it is valid.
494 */
495 String raw;
496 EXPECT_FALSE(val1.raw_binary(thd(), &raw));
497 {
498 SCOPED_TRACE("");
499 validate_array_contents(parse_binary(raw.ptr(), raw.length()),
500 array.size());
501 }
502
503 Json_array array2;
504 array2.append_clone(&array);
505 array2.append_clone(&array);
506 EXPECT_FALSE(serialize(thd(), &array2, &buf));
507 Value val2 = parse_binary(buf.ptr(), buf.length());
508 EXPECT_TRUE(val2.is_valid());
509 EXPECT_EQ(Value::ARRAY, val2.type());
510 EXPECT_EQ(2U, val2.element_count());
511 {
512 SCOPED_TRACE("");
513 validate_array_contents(val2.element(0), array.size());
514 }
515 {
516 SCOPED_TRACE("");
517 validate_array_contents(val2.element(1), array.size());
518 }
519
520 Json_object object;
521 object.add_clone("a", &array);
522 Json_string s_c("c");
523 object.add_clone("b", &s_c);
524 EXPECT_FALSE(serialize(thd(), &object, &buf));
525 Value val3 = parse_binary(buf.ptr(), buf.length());
526 EXPECT_TRUE(val3.is_valid());
527 EXPECT_TRUE(val3.large_format());
528 EXPECT_EQ(Value::OBJECT, val3.type());
529 EXPECT_EQ(2U, val3.element_count());
530 EXPECT_EQ("a", get_string(val3.key(0)));
531 {
532 SCOPED_TRACE("");
533 validate_array_contents(val3.element(0), array.size());
534 }
535 EXPECT_EQ("b", get_string(val3.key(1)));
536 EXPECT_EQ(Value::STRING, val3.element(1).type());
537 EXPECT_EQ("c", get_string(val3.element(1)));
538
539 {
540 SCOPED_TRACE("");
541 validate_array_contents(val3.lookup("a"), array.size());
542 }
543 EXPECT_EQ("c", get_string(val3.lookup("b")));
544
545 /*
546 Extract the raw binary representation of the large object, and verify
547 that it is valid.
548 */
549 EXPECT_FALSE(val3.raw_binary(thd(), &raw));
550 {
551 SCOPED_TRACE("");
552 Value val_a = parse_binary(raw.ptr(), raw.length()).lookup("a");
553 validate_array_contents(val_a, array.size());
554 }
555
556 /*
557 Bug#23031146: INSERTING 64K SIZE RECORDS TAKE TOO MUCH TIME
558
559 If a big (>64KB) sub-document was located at a deep nesting level,
560 serialization used to be very slow.
561 */
562 {
563 SCOPED_TRACE("");
564 // Wrap "array" in 50 more levels of arrays.
565 constexpr size_t depth = 50;
566 Json_array deeply_nested_array;
567 Json_array *current_array = &deeply_nested_array;
568 for (size_t i = 1; i < depth; i++) {
569 Json_array *a = new (std::nothrow) Json_array();
570 ASSERT_FALSE(current_array->append_alias(a));
571 current_array = a;
572 }
573 current_array->append_clone(&array);
574 // Serialize it. This used to take "forever".
575 ASSERT_FALSE(serialize(thd(), &deeply_nested_array, &buf));
576 // Parse the serialized DOM and verify its contents.
577 Value val = parse_binary(buf.ptr(), buf.length());
578 for (size_t i = 0; i < depth; i++) {
579 ASSERT_EQ(Value::ARRAY, val.type());
580 ASSERT_EQ(1U, val.element_count());
581 val = val.element(0);
582 }
583 validate_array_contents(val, array.size());
584
585 // Now test the same with object.
586 Json_object deeply_nested_object;
587 Json_object *current_object = &deeply_nested_object;
588 for (size_t i = 1; i < depth; i++) {
589 Json_object *o = new (std::nothrow) Json_object();
590 ASSERT_FALSE(current_object->add_alias("key", o));
591 current_object = o;
592 }
593 current_object->add_clone("key", &array);
594 ASSERT_FALSE(serialize(thd(), &deeply_nested_object, &buf));
595 val = parse_binary(buf.ptr(), buf.length());
596 for (size_t i = 0; i < depth; i++) {
597 ASSERT_EQ(Value::OBJECT, val.type());
598 ASSERT_EQ(1U, val.element_count());
599 ASSERT_EQ("key", get_string(val.key(0)));
600 val = val.element(0);
601 }
602 validate_array_contents(val, array.size());
603 }
604 }
605
606 /*
607 Various tests for the Value::raw_binary() function.
608 */
609 TEST_F(JsonBinaryTest, RawBinaryTest) {
610 Json_array array;
611 Json_string as("a string");
612 array.append_clone(&as);
613 Json_int ji(-123);
614 array.append_clone(&ji);
615 Json_uint jui(42);
616 array.append_clone(&jui);
617 Json_double jd(1.5);
618 array.append_clone(&jd);
619 Json_null jn;
620 array.append_clone(&jn);
621 Json_boolean jbt(true);
622 array.append_clone(&jbt);
623 Json_boolean jbf(false);
624 array.append_clone(&jbf);
625 Json_opaque jo(MYSQL_TYPE_BLOB, "abcd", 4);
626 array.append_clone(&jo);
627
628 Json_object object;
629 object.add_clone("key", &jbt);
630 array.append_clone(&object);
631
632 Json_array array2;
633 array2.append_clone(&jbf);
634 array.append_clone(&array2);
635
636 String buf;
637 EXPECT_FALSE(json_binary::serialize(thd(), &array, &buf));
638 Value v1 = parse_binary(buf.ptr(), buf.length());
639
640 String raw;
641 EXPECT_FALSE(v1.raw_binary(thd(), &raw));
642 Value v1_copy = parse_binary(raw.ptr(), raw.length());
643 EXPECT_EQ(Value::ARRAY, v1_copy.type());
644 EXPECT_EQ(array.size(), v1_copy.element_count());
645
646 EXPECT_FALSE(v1.element(0).raw_binary(thd(), &raw));
647 Value v1_0 = parse_binary(raw.ptr(), raw.length());
648 EXPECT_EQ(Value::STRING, v1_0.type());
649 EXPECT_EQ("a string", std::string(v1_0.get_data(), v1_0.get_data_length()));
650
651 EXPECT_FALSE(v1.element(1).raw_binary(thd(), &raw));
652 Value v1_1 = parse_binary(raw.ptr(), raw.length());
653 EXPECT_EQ(Value::INT, v1_1.type());
654 EXPECT_EQ(-123, v1_1.get_int64());
655
656 EXPECT_FALSE(v1.element(2).raw_binary(thd(), &raw));
657 Value v1_2 = parse_binary(raw.ptr(), raw.length());
658 EXPECT_EQ(Value::UINT, v1_2.type());
659 EXPECT_EQ(42U, v1_2.get_uint64());
660
661 EXPECT_FALSE(v1.element(3).raw_binary(thd(), &raw));
662 Value v1_3 = parse_binary(raw.ptr(), raw.length());
663 EXPECT_EQ(Value::DOUBLE, v1_3.type());
664 EXPECT_EQ(1.5, v1_3.get_double());
665
666 EXPECT_FALSE(v1.element(4).raw_binary(thd(), &raw));
667 Value v1_4 = parse_binary(raw.ptr(), raw.length());
668 EXPECT_EQ(Value::LITERAL_NULL, v1_4.type());
669
670 EXPECT_FALSE(v1.element(5).raw_binary(thd(), &raw));
671 Value v1_5 = parse_binary(raw.ptr(), raw.length());
672 EXPECT_EQ(Value::LITERAL_TRUE, v1_5.type());
673
674 EXPECT_FALSE(v1.element(6).raw_binary(thd(), &raw));
675 Value v1_6 = parse_binary(raw.ptr(), raw.length());
676 EXPECT_EQ(Value::LITERAL_FALSE, v1_6.type());
677
678 EXPECT_FALSE(v1.element(7).raw_binary(thd(), &raw));
679 Value v1_7 = parse_binary(raw.ptr(), raw.length());
680 EXPECT_EQ(Value::OPAQUE, v1_7.type());
681 EXPECT_EQ(MYSQL_TYPE_BLOB, v1_7.field_type());
682 EXPECT_EQ("abcd", std::string(v1_7.get_data(), v1_7.get_data_length()));
683
684 EXPECT_FALSE(v1.element(8).raw_binary(thd(), &raw));
685 Value v1_8 = parse_binary(raw.ptr(), raw.length());
686 EXPECT_EQ(Value::OBJECT, v1_8.type());
687 EXPECT_EQ(object.cardinality(), v1_8.element_count());
688 EXPECT_EQ(Value::LITERAL_TRUE, v1_8.lookup("key").type());
689
690 EXPECT_FALSE(v1.element(8).key(0).raw_binary(thd(), &raw));
691 Value v1_8_key = parse_binary(raw.ptr(), raw.length());
692 EXPECT_EQ(Value::STRING, v1_8_key.type());
693 EXPECT_EQ("key",
694 std::string(v1_8_key.get_data(), v1_8_key.get_data_length()));
695
696 EXPECT_FALSE(v1.element(8).element(0).raw_binary(thd(), &raw));
697 Value v1_8_val = parse_binary(raw.ptr(), raw.length());
698 EXPECT_EQ(Value::LITERAL_TRUE, v1_8_val.type());
699
700 EXPECT_FALSE(v1.element(9).raw_binary(thd(), &raw));
701 Value v1_9 = parse_binary(raw.ptr(), raw.length());
702 EXPECT_EQ(Value::ARRAY, v1_9.type());
703 EXPECT_EQ(array2.size(), v1_9.element_count());
704 EXPECT_EQ(Value::LITERAL_FALSE, v1_9.element(0).type());
705
706 EXPECT_FALSE(v1.element(9).element(0).raw_binary(thd(), &raw));
707 Value v1_9_0 = parse_binary(raw.ptr(), raw.length());
708 EXPECT_EQ(Value::LITERAL_FALSE, v1_9_0.type());
709 }
710
711 /*
712 Create a JSON string of the given size, serialize it as a JSON binary, and
713 then deserialize it and verify that we get the same string back.
714 */
715 void serialize_deserialize_string(const THD *thd, size_t size) {
716 SCOPED_TRACE(testing::Message() << "size = " << size);
717 char *str = new char[size];
718 memset(str, 'a', size);
719 Json_string jstr(str, size);
720
721 String buf;
722 EXPECT_FALSE(json_binary::serialize(thd, &jstr, &buf));
723 Value v = parse_binary(buf.ptr(), buf.length());
724 EXPECT_EQ(Value::STRING, v.type());
725 EXPECT_EQ(size, v.get_data_length());
726 EXPECT_EQ(0, memcmp(str, v.get_data(), size));
727
728 delete[] str;
729 }
730
731 /*
732 Test strings of variable length. Test especially around the boundaries
733 where the representation of the string length changes:
734
735 - Strings of length 0-127 use 1 byte length fields.
736 - Strings of length 128-16383 use 2 byte length fields.
737 - Strings of length 16384-2097151 use 3 byte length fields.
738 - Strings of length 2097152-268435455 use 4 byte length fields.
739 - Strings of length 268435456-... use 5 byte length fields.
740
741 We probably don't have enough memory to test the last category here...
742 */
743 TEST_F(JsonBinaryTest, StringLengthTest) {
744 const THD *thd = this->thd();
745 serialize_deserialize_string(thd, 0);
746 serialize_deserialize_string(thd, 1);
747 serialize_deserialize_string(thd, 127);
748 serialize_deserialize_string(thd, 128);
749 serialize_deserialize_string(thd, 16383);
750 serialize_deserialize_string(thd, 16384);
751 serialize_deserialize_string(thd, 2097151);
752 serialize_deserialize_string(thd, 2097152);
753 serialize_deserialize_string(thd, 3000000);
754 }
755
756 /**
757 Error handler which registers if an error has been raised. If an error is
758 raised, it asserts that the error is ER_INVALID_JSON_BINARY_DATA.
759 */
760 class Invalid_binary_handler : public Internal_error_handler {
761 public:
762 Invalid_binary_handler(THD *thd)
763 : m_thd(thd), m_called(false), m_orig_handler(error_handler_hook) {
764 error_handler_hook = my_message_sql;
765 thd->push_internal_handler(this);
766 }
767
768 ~Invalid_binary_handler() override {
769 EXPECT_EQ(this, m_thd->pop_internal_handler());
770 error_handler_hook = m_orig_handler;
771 }
772
773 bool handle_condition(THD *, uint err, const char *,
774 Sql_condition::enum_severity_level *,
775 const char *) override {
776 uint expected = ER_INVALID_JSON_BINARY_DATA;
777 EXPECT_EQ(expected, err);
778 m_called = true;
779 return true;
780 }
781
782 bool is_called() const { return m_called; }
783
784 private:
785 THD *m_thd;
786 bool m_called;
787 ErrorHandlerFunctionPointer m_orig_handler;
788 };
789
790 /**
791 Run various operations on a corrupted binary value, to see that the
792 json_binary library doesn't fall over when encountering a corrupted value.
793 */
794 static void check_corrupted_binary(THD *thd, const char *data, size_t length) {
795 /*
796 A corrupted value may still be valid, so we cannot assert on the return
797 value. Just exercise the code to see that nothing very bad happens.
798 */
799 Value val = parse_binary(data, length);
800 val.is_valid();
801
802 {
803 /*
804 Value::get_free_space() may or may not raise an error. If there is an
805 error, we expect it to be ER_INVALID_JSON_BINARY_DATA.
806 */
807 Invalid_binary_handler handler(thd);
808 size_t space;
809 bool err = val.get_free_space(thd, &space);
810 // If it returns true, an error should have been raised.
811 EXPECT_EQ(err, handler.is_called());
812 }
813
814 /*
815 Call Value::has_space() on every element if it is an array or object.
816 */
817 if (val.type() == Value::ARRAY || val.type() == Value::OBJECT) {
818 for (size_t i = 0; i < val.element_count(); ++i) {
819 size_t offset;
820 val.has_space(i, 100, &offset);
821 }
822 }
823 }
824
825 /**
826 Check that a corrupted binary value doesn't upset the parser in any serious
827 way.
828
829 @param thd THD handle
830 @param dom a JSON DOM from which corrupted binary values are created
831 */
832 static void check_corruption(THD *thd, const Json_dom *dom) {
833 // First create a valid binary representation of the DOM.
834 String buf;
835 EXPECT_FALSE(json_binary::serialize(thd, dom, &buf));
836 EXPECT_TRUE(json_binary::parse_binary(buf.ptr(), buf.length()).is_valid());
837
838 /*
839 Truncated values should always be detected by is_valid(). Except
840 if it's truncated to an empty string, since parse_binary()
841 interprets the empty string as the JSON null literal.
842 */
843 for (size_t i = 1; i < buf.length() - 1; ++i) {
844 EXPECT_FALSE(json_binary::parse_binary(buf.ptr(), i).is_valid());
845 check_corrupted_binary(thd, buf.ptr(), i);
846 }
847
848 /*
849 Test various 1, 2 and 3 byte data corruptions. is_valid() may return true
850 or false (not all corrupted documents are ill-formed), but we should not
851 have any crashes or valgrind/asan warnings.
852 */
853 for (size_t i = 0; i < buf.length(); ++i) {
854 String copy;
855 copy.append(buf);
856 char *data = copy.c_ptr_safe();
857 for (size_t j = 1; j < 3 && i + j < buf.length(); ++j) {
858 memset(data + i, 0x00, j);
859 check_corrupted_binary(thd, data, copy.length());
860 memset(data + i, 0x80, j);
861 check_corrupted_binary(thd, data, copy.length());
862 memset(data + i, 0xff, j);
863 check_corrupted_binary(thd, data, copy.length());
864 }
865 }
866 }
867
868 /**
869 Test that the parser is well-behaved when a binary value is corrupted.
870 */
871 TEST_F(JsonBinaryTest, CorruptedBinaryTest) {
872 Json_array a;
873 a.append_alias(new (std::nothrow) Json_null);
874 a.append_alias(new (std::nothrow) Json_boolean(true));
875 a.append_alias(new (std::nothrow) Json_boolean(false));
876 a.append_alias(new (std::nothrow) Json_uint(0));
877 a.append_alias(new (std::nothrow) Json_uint(123));
878 a.append_alias(new (std::nothrow) Json_uint(123000));
879 a.append_alias(new (std::nothrow) Json_uint(123000000));
880 a.append_alias(new (std::nothrow) Json_int(0));
881 a.append_alias(new (std::nothrow) Json_int(123));
882 a.append_alias(new (std::nothrow) Json_int(123000));
883 a.append_alias(new (std::nothrow) Json_int(123000000));
884 a.append_alias(new (std::nothrow) Json_int(-123000000));
885 a.append_alias(new (std::nothrow) Json_string());
886 a.append_alias(new (std::nothrow) Json_string(300, 'a'));
887 a.append_alias(new (std::nothrow) Json_decimal(create_decimal(3.14)));
888 Json_object *o = new (std::nothrow) Json_object;
889 a.append_alias(o);
890 o->add_clone("a1", &a);
891 o->add_alias("s", new (std::nothrow) Json_opaque(MYSQL_TYPE_BLOB, 32, 'x'));
892 o->add_alias("d", new (std::nothrow) Json_double(3.14));
893 a.append_clone(&a);
894 o->add_clone("a2", &a);
895
896 check_corruption(thd(), &a);
897 for (size_t i = 0; i < a.size(); ++i) {
898 SCOPED_TRACE("");
899 check_corruption(thd(), a[i]);
900 }
901 }
902
903 /// How big is the serialized version of a Json_dom?
904 static size_t binary_size(const THD *thd, const Json_dom *dom) {
905 StringBuffer<256> buf;
906 EXPECT_FALSE(json_binary::serialize(thd, dom, &buf));
907 return buf.length();
908 }
909
910 /// A tuple used by SpaceNeededTest for testing json_binary::space_needed().
911 struct SpaceNeededTuple {
912 /**
913 Constructor for test case with different space requirements in the
914 large and small storage formats.
915 */
916 SpaceNeededTuple(Json_dom *dom, bool result, size_t needed_small,
917 size_t needed_large)
918 : m_value(dom),
919 m_result(result),
920 m_needed_small(needed_small),
921 m_needed_large(needed_large) {}
922 /**
923 Constructor for test case with same space requirement in the large
924 and small storage formats.
925 */
926 SpaceNeededTuple(Json_dom *dom, bool result, size_t needed)
927 : SpaceNeededTuple(dom, result, needed, needed) {}
928 /// The value to pass to space_needed().
929 Json_wrapper m_value;
930 /// The expected return value from the function.
931 bool m_result;
932 /// The expected bytes needed to store the value in the small storage format.
933 size_t m_needed_small;
934 /// The expected bytes needed to store the value in the large storage format.
935 size_t m_needed_large;
936 };
937
938 /// A class used for testing json_binary::space_needed().
939 class SpaceNeededTest : public ::testing::TestWithParam<SpaceNeededTuple> {
940 my_testing::Server_initializer initializer;
941
942 protected:
943 void SetUp() override { initializer.SetUp(); }
944 void TearDown() override { initializer.TearDown(); }
945 THD *thd() const { return initializer.thd(); }
946 };
947
948 /*
949 Define our own PrintTo because Google Test's default implementation causes
950 valgrind warnings for reading uninitialized memory. (It reads every byte of
951 the struct, but the struct contains some uninitialized bytes because of
952 alignment.)
953 */
954 void PrintTo(SpaceNeededTuple const &tuple, std::ostream *os) {
955 *os << '{' << static_cast<uint>(tuple.m_value.type()) << ", "
956 << tuple.m_result << ", " << tuple.m_needed_small << ", "
957 << tuple.m_needed_large << '}';
958 }
959
960 /// Test json_binary::space_needed() for a given input.
961 TEST_P(SpaceNeededTest, SpaceNeeded) {
962 SpaceNeededTuple param = GetParam();
963
964 /*
965 If the large and small storage size differ, it must mean that the
966 value can be inlined in the large storage format.
967 */
968 if (param.m_needed_small != param.m_needed_large) {
969 EXPECT_EQ(0U, param.m_needed_large);
970 }
971
972 size_t needed = 0;
973 if (param.m_result) {
974 for (bool large : {true, false}) {
975 Invalid_binary_handler handler(thd());
976 EXPECT_TRUE(space_needed(thd(), &param.m_value, large, &needed));
977 EXPECT_TRUE(handler.is_called());
978 }
979 return;
980 }
981
982 needed = 0;
983 EXPECT_FALSE(space_needed(thd(), &param.m_value, false, &needed));
984 EXPECT_EQ(param.m_needed_small, needed);
985
986 needed = 0;
987 EXPECT_FALSE(space_needed(thd(), &param.m_value, true, &needed));
988 EXPECT_EQ(param.m_needed_large, needed);
989
990 const auto dom = param.m_value.to_dom();
991
992 if (param.m_needed_small > 0) {
993 /*
994 Not inlined. The size does not include the type byte, so expect
995 one more byte.
996 */
997 EXPECT_EQ(param.m_needed_small + 1, binary_size(thd(), dom));
998 } else {
999 /*
1000 Inlined in the small storage format. Find the difference in size
1001 between an empty array and one with the value added. Expect the
1002 size of a small value entry, which is 3 bytes (1 byte for the
1003 type, 2 bytes for the inlined value).
1004 */
1005 Json_array a;
1006 size_t base_size = binary_size(thd(), &a);
1007 a.append_clone(dom);
1008 size_t full_size = binary_size(thd(), &a);
1009 EXPECT_EQ(base_size + 3, full_size);
1010 }
1011
1012 if (param.m_needed_small > 0 && param.m_needed_large == 0) {
1013 /*
1014 Inlined in the large storage format only. See how much space is
1015 added. Expect the size of a large value entry, which is 5 bytes
1016 (1 byte for the type, 4 bytes for the inlined value).
1017 */
1018 Json_array a;
1019 a.append_alias(new (std::nothrow) Json_string(64 * 1024, 'a'));
1020 size_t base_size = binary_size(thd(), &a);
1021 a.append_clone(dom);
1022 size_t full_size = binary_size(thd(), &a);
1023 EXPECT_EQ(base_size + 5, full_size);
1024 }
1025 }
1026
1027 static const SpaceNeededTuple space_needed_tuples[] = {
1028 /*
1029 Strings need space for the actual data and a variable length field
1030 that holds the length of the string. Each byte in the variable
1031 length field holds seven bits of the length value, so testing
1032 lengths around 2^(7*N) is important.
1033 */
1034 {new (std::nothrow) Json_string(""), false, 1}, // 2^0-1
1035 {new (std::nothrow) Json_string("a"), false, 2}, // 2^0
1036 {new (std::nothrow) Json_string(127, 'a'), false, 128}, // 2^7-1
1037 {new (std::nothrow) Json_string(128, 'a'), false, 130}, // 2^7
1038 {new (std::nothrow) Json_string(16383, 'a'), false, 16385}, // 2^14-1
1039 {new (std::nothrow) Json_string(16384, 'a'), false, 16387}, // 2^14
1040 {new (std::nothrow) Json_string(2097151, 'a'), false, 2097154}, // 2^21-1
1041 {new (std::nothrow) Json_string(2097152, 'a'), false, 2097156}, // 2^21
1042
1043 // Literals are always inlined.
1044 {new (std::nothrow) Json_null, false, 0},
1045 {new (std::nothrow) Json_boolean(false), false, 0},
1046 {new (std::nothrow) Json_boolean(true), false, 0},
1047
1048 // 16-bit integers are always inlined.
1049 {new (std::nothrow) Json_int(0), false, 0},
1050 {new (std::nothrow) Json_int(-1), false, 0},
1051 {new (std::nothrow) Json_int(1), false, 0},
1052 {new (std::nothrow) Json_int(INT_MIN16), false, 0},
1053 {new (std::nothrow) Json_int(INT_MAX16), false, 0},
1054 {new (std::nothrow) Json_uint(0), false, 0},
1055 {new (std::nothrow) Json_uint(1), false, 0},
1056 {new (std::nothrow) Json_uint(UINT_MAX16), false, 0},
1057
1058 // 32-bit integers are inlined only in the large storage format.
1059 {new (std::nothrow) Json_int(INT_MIN32), false, 4, 0},
1060 {new (std::nothrow) Json_int(INT_MIN16 - 1), false, 4, 0},
1061 {new (std::nothrow) Json_int(INT_MAX16 + 1), false, 4, 0},
1062 {new (std::nothrow) Json_int(INT_MAX32), false, 4, 0},
1063 {new (std::nothrow) Json_uint(UINT_MAX16 + 1), false, 4, 0},
1064 {new (std::nothrow) Json_uint(UINT_MAX32), false, 4, 0},
1065
1066 // Larger integers and doubles require 8 bytes.
1067 {new (std::nothrow) Json_int(INT_MIN64), false, 8},
1068 {new (std::nothrow) Json_int(static_cast<longlong>(INT_MIN32) - 1), false,
1069 8},
1070 {new (std::nothrow) Json_int(static_cast<longlong>(INT_MAX32) + 1), false,
1071 8},
1072 {new (std::nothrow) Json_int(INT_MAX64), false, 8},
1073 {new (std::nothrow) Json_uint(static_cast<ulonglong>(UINT_MAX32) + 1),
1074 false, 8},
1075 {new (std::nothrow) Json_uint(0xFFFFFFFFFFFFFFFFULL), false, 8},
1076 {new (std::nothrow) Json_double(0), false, 8},
1077 {new (std::nothrow) Json_double(3.14), false, 8},
1078
1079 /*
1080 Opaque values need space for type info (one byte), a variable
1081 length field, and the actual data.
1082 */
1083 {new (std::nothrow) Json_opaque(MYSQL_TYPE_BLOB, ""), false, 2},
1084 {new (std::nothrow) Json_opaque(MYSQL_TYPE_BLOB, "a"), false, 3},
1085 {new (std::nothrow) Json_opaque(MYSQL_TYPE_BLOB, 127, 'a'), false, 129},
1086 {new (std::nothrow) Json_opaque(MYSQL_TYPE_BLOB, 128, 'a'), false, 131},
1087 {new (std::nothrow) Json_datetime(create_time(), MYSQL_TYPE_TIME), false,
1088 Json_datetime::PACKED_SIZE + 2},
1089 {new (std::nothrow) Json_datetime(create_date(), MYSQL_TYPE_DATE), false,
1090 Json_datetime::PACKED_SIZE + 2},
1091 {new (std::nothrow) Json_datetime(create_datetime(), MYSQL_TYPE_DATETIME),
1092 false, Json_datetime::PACKED_SIZE + 2},
1093 {new (std::nothrow) Json_datetime(create_datetime(), MYSQL_TYPE_TIMESTAMP),
1094 false, Json_datetime::PACKED_SIZE + 2},
1095 {new (std::nothrow) Json_decimal(create_decimal(12.3)), false, 6},
1096
1097 // Arrays.
1098 {new (std::nothrow) Json_array, false, 4},
1099 {parse_json("[1.5]").release(), false, 15},
1100
1101 // Objects
1102 {new (std::nothrow) Json_object, false, 4},
1103 {parse_json("{\"a\":1.5}").release(), false, 20},
1104
1105 // Handle type == ERROR.
1106 {nullptr, true, 0},
1107 };
1108
1109 INSTANTIATE_TEST_SUITE_P(JsonBinary, SpaceNeededTest,
1110 ::testing::ValuesIn(space_needed_tuples));
1111
1112 /**
1113 Helper function for testing Value::has_space(). Serializes a JSON
1114 array or JSON object and checks if has_space() reports the correct
1115 size and offset for an element in the array or object.
1116 */
1117 static void test_has_space(THD *thd, const Json_dom *container,
1118 Value::enum_type type, size_t size, size_t element,
1119 size_t expected_offset) {
1120 StringBuffer<100> buf;
1121 EXPECT_FALSE(json_binary::serialize(thd, container, &buf));
1122 Value v1 = parse_binary(buf.ptr(), buf.length());
1123 Value v2 = v1.element(element);
1124 EXPECT_EQ(type, v2.type());
1125 size_t offset = 0;
1126 if (size > 0) {
1127 EXPECT_TRUE(v1.has_space(element, size - 1, &offset));
1128 EXPECT_EQ(expected_offset, offset);
1129 }
1130 offset = 0;
1131 EXPECT_TRUE(v1.has_space(element, size, &offset));
1132 EXPECT_EQ(expected_offset, offset);
1133 offset = 0;
1134 EXPECT_FALSE(v1.has_space(element, size + 1, &offset));
1135 EXPECT_EQ(0U, offset);
1136 offset = 0;
1137 EXPECT_TRUE(v1.has_space(element, 0, &offset));
1138 EXPECT_EQ(expected_offset, offset);
1139 }
1140
1141 /**
1142 Test Value::has_size() by inserting a value into an array or an
1143 object and checking that has_size() returns the correct size and
1144 offset.
1145 */
1146 static void test_has_space(THD *thd, const Json_dom *dom, Value::enum_type type,
1147 size_t size) {
1148 {
1149 SCOPED_TRACE("array");
1150 Json_array a;
1151 a.append_clone(dom);
1152
1153 /*
1154 The array contains the element count (2 bytes), byte size (2
1155 bytes) and a value entry (3 bytes) before the value.
1156 */
1157 size_t expected_offset = 2 + 2 + 3;
1158 {
1159 SCOPED_TRACE("first element");
1160 test_has_space(thd, &a, type, size, 0, expected_offset);
1161 }
1162
1163 /*
1164 Insert a literal at the beginning of the array. The offset
1165 should increase by 3 (size of the value entry).
1166 */
1167 expected_offset += 3;
1168 {
1169 SCOPED_TRACE("second element");
1170 a.insert_alias(0, create_dom_ptr<Json_null>());
1171 test_has_space(thd, &a, type, size, 1, expected_offset);
1172 }
1173
1174 /*
1175 Insert a double at the beginning of the array. Expect the offset
1176 to increase by 3 (size of the value entry) + 8 (size of the
1177 double).
1178 */
1179 expected_offset += 3 + 8;
1180 {
1181 SCOPED_TRACE("third element");
1182 a.insert_alias(0, create_dom_ptr<Json_double>(123.0));
1183 test_has_space(thd, &a, type, size, 2, expected_offset);
1184 }
1185
1186 /*
1187 Insert some values at the end of the array. The offset should
1188 increase by 3 (one value entry) per added value.
1189 */
1190 expected_offset += 3;
1191 {
1192 SCOPED_TRACE("append literal");
1193 a.append_alias(new (std::nothrow) Json_boolean(true));
1194 test_has_space(thd, &a, type, size, 2, expected_offset);
1195 }
1196 expected_offset += 3;
1197 {
1198 SCOPED_TRACE("append double");
1199 a.append_alias(new (std::nothrow) Json_double(1.23));
1200 test_has_space(thd, &a, type, size, 2, expected_offset);
1201 }
1202 }
1203
1204 /*
1205 Now test the same with an object.
1206 */
1207 {
1208 SCOPED_TRACE("object");
1209 Json_object o;
1210 o.add_clone("k", dom);
1211
1212 /*
1213 The object contains the element count (2 bytes), byte size (2
1214 bytes), a key entry (4 bytes), a value entry (3 bytes) and a key
1215 (1 byte) before the value.
1216 */
1217 size_t expected_offset = 2 + 2 + 4 + 3 + 1;
1218 {
1219 SCOPED_TRACE("first element");
1220 test_has_space(thd, &o, type, size, 0, expected_offset);
1221 }
1222
1223 /*
1224 Add a literal at the beginning of the object. The offset should
1225 increase by 4 (size of the key entry) + 3 (size of the value
1226 entry) + 1 (size of the key).
1227 */
1228 expected_offset += 4 + 3 + 1;
1229 {
1230 SCOPED_TRACE("second element");
1231 o.add_alias("b", new (std::nothrow) Json_null);
1232 test_has_space(thd, &o, type, size, 1, expected_offset);
1233 }
1234
1235 /*
1236 Add a double at the beginning of the object. Expect the offset
1237 to increase by 4 (size of the key entry) + 3 (size of the value
1238 entry) + 1 (size of the key) + 8 (size of the double).
1239 */
1240 expected_offset += 4 + 3 + 1 + 8;
1241 {
1242 SCOPED_TRACE("third element");
1243 o.add_alias("a", new (std::nothrow) Json_double(123.0));
1244 test_has_space(thd, &o, type, size, 2, expected_offset);
1245 }
1246
1247 /*
1248 Add some values at the end of the array. The offset should
1249 increase by 4 (one key entry) + 3 (one value entry) + 1 (one
1250 key) per added member.
1251 */
1252 expected_offset += 4 + 3 + 1;
1253 {
1254 SCOPED_TRACE("add literal");
1255 o.add_alias("x", new (std::nothrow) Json_boolean(true));
1256 test_has_space(thd, &o, type, size, 2, expected_offset);
1257 }
1258 expected_offset += 4 + 3 + 1;
1259 {
1260 SCOPED_TRACE("add double");
1261 o.add_alias("y", new (std::nothrow) Json_double(1.23));
1262 test_has_space(thd, &o, type, size, 2, expected_offset);
1263 }
1264 }
1265 }
1266
1267 /**
1268 Various tests for Value::has_space().
1269 */
1270 TEST_F(JsonBinaryTest, HasSpace) {
1271 {
1272 SCOPED_TRACE("empty string");
1273 Json_string jstr;
1274 test_has_space(thd(), &jstr, Value::STRING, 1);
1275 }
1276 {
1277 // Test longest possible string with 1-byte length field.
1278 SCOPED_TRACE("string(127)");
1279 Json_string jstr(127, 'a');
1280 test_has_space(thd(), &jstr, Value::STRING, 128);
1281 }
1282 {
1283 // Test shortest possible string with 2-byte length field.
1284 SCOPED_TRACE("string(128)");
1285 Json_string jstr(128, 'a');
1286 test_has_space(thd(), &jstr, Value::STRING, 130);
1287 }
1288 {
1289 SCOPED_TRACE("null literal");
1290 Json_null jnull;
1291 test_has_space(thd(), &jnull, Value::LITERAL_NULL, 0);
1292 }
1293 {
1294 SCOPED_TRACE("true literal");
1295 Json_boolean jtrue(true);
1296 test_has_space(thd(), &jtrue, Value::LITERAL_TRUE, 0);
1297 }
1298 {
1299 SCOPED_TRACE("false literal");
1300 Json_boolean jfalse(false);
1301 test_has_space(thd(), &jfalse, Value::LITERAL_FALSE, 0);
1302 }
1303 {
1304 SCOPED_TRACE("inlined uint");
1305 Json_uint u(123);
1306 EXPECT_TRUE(u.is_16bit());
1307 test_has_space(thd(), &u, Value::UINT, 0);
1308 }
1309 {
1310 SCOPED_TRACE("32-bit uint");
1311 Json_uint u(100000);
1312 EXPECT_FALSE(u.is_16bit());
1313 EXPECT_TRUE(u.is_32bit());
1314 test_has_space(thd(), &u, Value::UINT, 4);
1315 }
1316 {
1317 SCOPED_TRACE("64-bit uint");
1318 Json_uint u(5000000000ULL);
1319 EXPECT_FALSE(u.is_32bit());
1320 test_has_space(thd(), &u, Value::UINT, 8);
1321 }
1322 {
1323 SCOPED_TRACE("inlined int");
1324 Json_int i(123);
1325 EXPECT_TRUE(i.is_16bit());
1326 test_has_space(thd(), &i, Value::INT, 0);
1327 }
1328 {
1329 SCOPED_TRACE("32-bit int");
1330 Json_int i(100000);
1331 EXPECT_FALSE(i.is_16bit());
1332 EXPECT_TRUE(i.is_32bit());
1333 test_has_space(thd(), &i, Value::INT, 4);
1334 }
1335 {
1336 SCOPED_TRACE("64-bit uint");
1337 Json_int i(5000000000LL);
1338 EXPECT_FALSE(i.is_32bit());
1339 test_has_space(thd(), &i, Value::INT, 8);
1340 }
1341 {
1342 SCOPED_TRACE("double");
1343 Json_double d(3.14);
1344 test_has_space(thd(), &d, Value::DOUBLE, 8);
1345 }
1346 {
1347 SCOPED_TRACE("opaque");
1348 Json_opaque o(MYSQL_TYPE_BLOB, "abc", 3);
1349 // 1 byte for type, 1 byte for length, 3 bytes of blob data
1350 test_has_space(thd(), &o, Value::OPAQUE, 5);
1351 }
1352 {
1353 SCOPED_TRACE("empty array");
1354 Json_array a;
1355 /*
1356 An empty array has two bytes for element count and two bytes for
1357 total size in bytes.
1358 */
1359 test_has_space(thd(), &a, Value::ARRAY, 4);
1360 }
1361 {
1362 SCOPED_TRACE("non-empty array");
1363 auto a = parse_json("[null]");
1364 // Here we have an additional 3 bytes for the value entry.
1365 test_has_space(thd(), a.get(), Value::ARRAY, 4 + 3);
1366 }
1367 {
1368 SCOPED_TRACE("empty object");
1369 Json_object o;
1370 /*
1371 An empty object has two bytes for element count and two bytes for
1372 total size in bytes.
1373 */
1374 test_has_space(thd(), &o, Value::OBJECT, 4);
1375 }
1376 {
1377 SCOPED_TRACE("non-empty object");
1378 Json_object o;
1379 o.add_alias("a", new (std::nothrow) Json_null);
1380 /*
1381 Here we have an additional 4 bytes for the key entry, 3 bytes
1382 for the value entry, and 1 byte for the key.
1383 */
1384 test_has_space(thd(), &o, Value::OBJECT, 4 + 4 + 3 + 1);
1385 }
1386 }
1387
1388 /**
1389 Helper function for microbenchmarks that test the performance of
1390 json_binary::serialize().
1391
1392 @param dom the Json_dom to serialize
1393 @param num_iterations the number of iterations in the test
1394 */
1395 static void serialize_benchmark(const Json_dom *dom, size_t num_iterations) {
1396 my_testing::Server_initializer initializer;
1397 initializer.SetUp();
1398 const THD *thd = initializer.thd();
1399
1400 StartBenchmarkTiming();
1401
1402 for (size_t i = 0; i < num_iterations; ++i) {
1403 String buf;
1404 EXPECT_FALSE(json_binary::serialize(thd, dom, &buf));
1405 }
1406
1407 StopBenchmarkTiming();
1408
1409 initializer.TearDown();
1410 }
1411
1412 /**
1413 Microbenchmark which tests the performance of serializing a JSON
1414 array with 10000 integers.
1415 */
1416 static void BM_JsonBinarySerializeIntArray(size_t num_iterations) {
1417 StopBenchmarkTiming();
1418
1419 Json_array array;
1420 for (int i = 0; i < 10000; ++i)
1421 array.append_alias(create_dom_ptr<Json_int>(i * 1000));
1422
1423 serialize_benchmark(&array, num_iterations);
1424 }
1425 BENCHMARK(BM_JsonBinarySerializeIntArray)
1426
1427 /**
1428 Microbenchmark which tests the performance of serializing a JSON
1429 array with 10000 double values.
1430 */
1431 static void BM_JsonBinarySerializeDoubleArray(size_t num_iterations) {
1432 StopBenchmarkTiming();
1433
1434 Json_array array;
1435 for (int i = 0; i < 10000; ++i)
1436 array.append_alias(create_dom_ptr<Json_double>(i * 1000));
1437
1438 serialize_benchmark(&array, num_iterations);
1439 }
1440 BENCHMARK(BM_JsonBinarySerializeDoubleArray)
1441
1442 /**
1443 Microbenchmark which tests the performance of serializing a JSON
1444 array with 10000 strings.
1445 */
1446 static void BM_JsonBinarySerializeStringArray(size_t num_iterations) {
1447 StopBenchmarkTiming();
1448
1449 Json_array array;
1450 for (int i = 0; i < 10000; ++i)
1451 array.append_alias(create_dom_ptr<Json_string>(std::to_string(i)));
1452
1453 serialize_benchmark(&array, num_iterations);
1454 }
1455 BENCHMARK(BM_JsonBinarySerializeStringArray)
1456
1457 } // namespace json_binary_unittest