be/src/util/json/json_parser.cpp
Line | Count | Source |
1 | | // Licensed to the Apache Software Foundation (ASF) under one |
2 | | // or more contributor license agreements. See the NOTICE file |
3 | | // distributed with this work for additional information |
4 | | // regarding copyright ownership. The ASF licenses this file |
5 | | // to you under the Apache License, Version 2.0 (the |
6 | | // "License"); you may not use this file except in compliance |
7 | | // with the License. You may obtain a copy of the License at |
8 | | // |
9 | | // http://www.apache.org/licenses/LICENSE-2.0 |
10 | | // |
11 | | // Unless required by applicable law or agreed to in writing, |
12 | | // software distributed under the License is distributed on an |
13 | | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
14 | | // KIND, either express or implied. See the License for the |
15 | | // specific language governing permissions and limitations |
16 | | // under the License. |
17 | | // This file is copied from |
18 | | // https://github.com/ClickHouse/ClickHouse/blob/master/src/Common/JSONParsers/SimdJSONParser.cpp |
19 | | // and modified by Doris |
20 | | |
21 | | #include "util/json/json_parser.h" |
22 | | |
23 | | #include <fmt/format.h> |
24 | | #include <glog/logging.h> |
25 | | |
26 | | #include <algorithm> |
27 | | #include <cassert> |
28 | | #include <string_view> |
29 | | #include <vector> |
30 | | |
31 | | #include "common/cast_set.h" |
32 | | // IWYU pragma: keep |
33 | | #include "common/status.h" |
34 | | #include "util/json/path_in_data.h" |
35 | | #include "util/json/simd_json_parser.h" |
36 | | |
37 | | namespace doris { |
38 | | |
39 | | template <typename ParserImpl> |
40 | | std::optional<ParseResult> JSONDataParser<ParserImpl>::parse(const char* begin, size_t length, |
41 | 80.7k | const ParseConfig& config) { |
42 | 80.7k | Element document; |
43 | 80.7k | if (!parser.parse(begin, length, document)) { |
44 | 13 | return {}; |
45 | 13 | } |
46 | 80.7k | ParseContext context; |
47 | | // deprecated_enable_flatten_nested controls nested path traversal |
48 | | // NestedGroup expansion is now handled at storage layer |
49 | 80.7k | context.deprecated_enable_flatten_nested = config.deprecated_enable_flatten_nested; |
50 | 80.7k | context.check_duplicate_json_path = config.check_duplicate_json_path; |
51 | 80.7k | context.reject_json_null_value = config.reject_json_null_value; |
52 | 80.7k | context.record_empty_object_path = config.record_empty_object_path; |
53 | 80.7k | context.is_top_array = document.isArray(); |
54 | 80.7k | traverse(document, context); |
55 | 80.7k | ParseResult result; |
56 | 80.7k | result.values = std::move(context.values); |
57 | 80.7k | result.paths.reserve(context.paths.size()); |
58 | 1.35M | for (auto&& path : context.paths) { |
59 | 1.35M | result.paths.emplace_back(std::move(path)); |
60 | 1.35M | } |
61 | 80.7k | return result; |
62 | 80.7k | } |
63 | | |
64 | | template <typename ParserImpl> |
65 | 2.08M | void JSONDataParser<ParserImpl>::traverse(const Element& element, ParseContext& ctx) { |
66 | | // checkStackSize(); |
67 | 2.08M | if (element.isNull() && ctx.reject_json_null_value) { |
68 | 3 | throw doris::Exception( |
69 | 3 | doris::ErrorCode::INVALID_ARGUMENT, |
70 | 3 | "VARIANT flexible partial update does not support JSON null patch values"); |
71 | 3 | } |
72 | 2.08M | if (element.isObject()) { |
73 | 144k | traverseObject(element.getObject(), ctx); |
74 | 1.93M | } else if (element.isArray()) { |
75 | | // allow nested arrays (multi-level) for NestedGroup; deeper levels are |
76 | | // handled by VariantNestedBuilder with a max-depth guard. |
77 | 55.3k | has_nested = false; |
78 | 55.3k | check_has_nested_object(element); |
79 | 55.3k | ctx.has_nested_in_flatten = has_nested && ctx.deprecated_enable_flatten_nested; |
80 | 55.3k | if (has_nested && !ctx.deprecated_enable_flatten_nested) { |
81 | | // Parse nested arrays to JsonbField |
82 | 209 | JsonbWriter writer; |
83 | 209 | traverseArrayAsJsonb(element.getArray(), writer); |
84 | 209 | appendValueIfNotDuplicate( |
85 | 209 | ctx, ctx.builder.get_parts(), |
86 | 209 | Field::create_field<TYPE_JSONB>(JsonbField(writer.getOutput()->getBuffer(), |
87 | 209 | writer.getOutput()->getSize()))); |
88 | 55.1k | } else { |
89 | 55.1k | traverseArray(element.getArray(), ctx); |
90 | 55.1k | } |
91 | | // we should set has_nested_in_flatten to false when traverse array finished for next array otherwise it will be true for next array |
92 | 55.3k | ctx.has_nested_in_flatten = false; |
93 | 1.88M | } else { |
94 | 1.88M | appendValueIfNotDuplicate(ctx, ctx.builder.get_parts(), getValueAsField(element)); |
95 | 1.88M | } |
96 | 2.08M | } |
97 | | |
98 | | template <typename ParserImpl> |
99 | | void JSONDataParser<ParserImpl>::appendValueIfNotDuplicate(ParseContext& ctx, |
100 | | const PathInData::Parts& path, |
101 | 1.94M | Field&& value) { |
102 | 1.94M | if (ctx.check_duplicate_json_path) { |
103 | 32 | PathInData path_in_data(path); |
104 | 32 | if (!ctx.visited_path_names.emplace(path_in_data.get_path()).second) { |
105 | 10 | return; |
106 | 10 | } |
107 | 32 | } |
108 | 1.94M | ctx.paths.push_back(path); |
109 | 1.94M | ctx.values.push_back(std::move(value)); |
110 | 1.94M | } |
111 | | |
112 | | template <typename ParserImpl> |
113 | 144k | void JSONDataParser<ParserImpl>::traverseObject(const JSONObject& object, ParseContext& ctx) { |
114 | 144k | ctx.paths.reserve(ctx.paths.size() + object.size()); |
115 | 144k | ctx.values.reserve(ctx.values.size() + object.size()); |
116 | 144k | if (object.size() == 0 && ctx.record_empty_object_path && !ctx.builder.get_parts().empty()) { |
117 | 7 | JsonbWriter writer; |
118 | 7 | writer.writeStartObject(); |
119 | 7 | writer.writeEndObject(); |
120 | 7 | appendValueIfNotDuplicate( |
121 | 7 | ctx, ctx.builder.get_parts(), |
122 | 7 | Field::create_field<TYPE_JSONB>(JsonbField(writer.getOutput()->getBuffer(), |
123 | 7 | writer.getOutput()->getSize()))); |
124 | 7 | return; |
125 | 7 | } |
126 | 1.42M | auto check_key_length = [](const auto& key) { |
127 | 1.42M | const size_t max_key_length = cast_set<size_t>(config::variant_max_json_key_length); |
128 | 1.42M | if (key.size() > max_key_length) { |
129 | 336 | throw doris::Exception( |
130 | 336 | doris::ErrorCode::INVALID_ARGUMENT, |
131 | 336 | fmt::format("Key length exceeds maximum allowed size of {} bytes.", |
132 | 336 | max_key_length)); |
133 | 336 | } |
134 | 1.42M | }; |
135 | 1.42M | auto traverse_object_member = [&](const auto& key, const auto& value) { |
136 | 1.42M | check_key_length(key); |
137 | 1.42M | ctx.builder.append(key, false); |
138 | 1.42M | traverse(value, ctx); |
139 | 1.42M | ctx.builder.pop_back(); |
140 | 1.42M | }; |
141 | | |
142 | 1.57M | for (auto it = object.begin(); it != object.end(); ++it) { |
143 | 1.42M | const auto& [key, value] = *it; |
144 | 1.42M | traverse_object_member(key, value); |
145 | 1.42M | } |
146 | 144k | } |
147 | | |
148 | | template <typename ParserImpl> |
149 | 1.12M | void JSONDataParser<ParserImpl>::check_has_nested_object(const Element& element) { |
150 | 1.12M | if (element.isArray()) { |
151 | 105k | const JSONArray& array = element.getArray(); |
152 | 1.17M | for (auto it = array.begin(); it != array.end(); ++it) { |
153 | 1.06M | check_has_nested_object(*it); |
154 | 1.06M | } |
155 | 105k | } |
156 | 1.12M | if (element.isObject()) { |
157 | 23.0k | has_nested = true; |
158 | 23.0k | } |
159 | 1.12M | } |
160 | | |
161 | | template <typename ParserImpl> |
162 | 4.31k | void JSONDataParser<ParserImpl>::traverseAsJsonb(const Element& element, JsonbWriter& writer) { |
163 | 4.31k | if (element.isObject()) { |
164 | 1.49k | traverseObjectAsJsonb(element.getObject(), writer); |
165 | 2.82k | } else if (element.isArray()) { |
166 | 7 | traverseArrayAsJsonb(element.getArray(), writer); |
167 | 2.81k | } else { |
168 | 2.81k | writeValueAsJsonb(element, writer); |
169 | 2.81k | } |
170 | 4.31k | } |
171 | | |
172 | | template <typename ParserImpl> |
173 | | void JSONDataParser<ParserImpl>::traverseObjectAsJsonb(const JSONObject& object, |
174 | 1.49k | JsonbWriter& writer) { |
175 | 1.49k | writer.writeStartObject(); |
176 | 4.93k | for (auto it = object.begin(); it != object.end(); ++it) { |
177 | 3.64k | const auto& [key, value] = *it; |
178 | 3.64k | const size_t max_key_length = cast_set<size_t>(config::variant_max_json_key_length); |
179 | 3.64k | if (key.size() > max_key_length) { |
180 | 201 | throw doris::Exception( |
181 | 201 | doris::ErrorCode::INVALID_ARGUMENT, |
182 | 201 | fmt::format("Key length exceeds maximum allowed size of {} bytes.", |
183 | 201 | max_key_length)); |
184 | 201 | } |
185 | 3.44k | writer.writeKey(key.data(), cast_set<uint8_t>(key.size())); |
186 | 3.44k | traverseAsJsonb(value, writer); |
187 | 3.44k | } |
188 | 1.28k | writer.writeEndObject(); |
189 | 1.28k | } |
190 | | |
191 | | template <typename ParserImpl> |
192 | 216 | void JSONDataParser<ParserImpl>::traverseArrayAsJsonb(const JSONArray& array, JsonbWriter& writer) { |
193 | 216 | writer.writeStartArray(); |
194 | 1.08k | for (auto it = array.begin(); it != array.end(); ++it) { |
195 | 873 | traverseAsJsonb(*it, writer); |
196 | 873 | } |
197 | 216 | writer.writeEndArray(); |
198 | 216 | } |
199 | | |
200 | | // check isPrefix in PathInData::Parts. like : [{"a": {"c": {"b": 1}}}, {"a": {"c": 2.2}}], "a.c" is prefix of "a.c.b" |
201 | | // return true if prefix is a prefix of parts |
202 | 6 | static bool is_prefix(const PathInData::Parts& prefix, const PathInData::Parts& parts) { |
203 | 6 | if (prefix.size() >= parts.size()) { |
204 | 5 | return false; |
205 | 5 | } |
206 | 2 | for (size_t i = 0; i < prefix.size(); ++i) { |
207 | 1 | if (prefix[i].key != parts[i].key) { |
208 | 0 | return false; |
209 | 0 | } |
210 | 1 | } |
211 | 1 | return true; |
212 | 1 | } |
213 | | |
214 | | template <typename ParserImpl> |
215 | 55.1k | void JSONDataParser<ParserImpl>::traverseArray(const JSONArray& array, ParseContext& ctx) { |
216 | | /// Traverse elements of array and collect an array of fields by each path. |
217 | 55.1k | ParseArrayContext array_ctx; |
218 | 55.1k | array_ctx.has_nested_in_flatten = ctx.has_nested_in_flatten; |
219 | 55.1k | array_ctx.is_top_array = ctx.is_top_array; |
220 | 55.1k | array_ctx.check_duplicate_json_path = ctx.check_duplicate_json_path; |
221 | 55.1k | array_ctx.reject_json_null_value = ctx.reject_json_null_value; |
222 | 55.1k | array_ctx.total_size = array.size(); |
223 | 633k | for (auto it = array.begin(); it != array.end(); ++it) { |
224 | 577k | traverseArrayElement(*it, array_ctx); |
225 | 577k | ++array_ctx.current_size; |
226 | 577k | } |
227 | 55.1k | auto&& arrays_by_path = array_ctx.arrays_by_path; |
228 | 55.1k | if (arrays_by_path.empty()) { |
229 | 4 | appendValueIfNotDuplicate(ctx, ctx.builder.get_parts(), |
230 | 4 | Field::create_field<TYPE_ARRAY>(Array())); |
231 | 55.1k | } else { |
232 | 55.1k | ctx.paths.reserve(ctx.paths.size() + arrays_by_path.size()); |
233 | 55.1k | ctx.values.reserve(ctx.values.size() + arrays_by_path.size()); |
234 | 113k | for (auto it = arrays_by_path.begin(); it != arrays_by_path.end(); ++it) { |
235 | 58.1k | auto&& [path, path_array] = it->second; |
236 | | /// Merge prefix path and path of array element. |
237 | 58.1k | ctx.builder.append(path, true); |
238 | 58.1k | appendValueIfNotDuplicate(ctx, ctx.builder.get_parts(), |
239 | 58.1k | Field::create_field<TYPE_ARRAY>(std::move(path_array))); |
240 | 58.1k | ctx.builder.pop_back(path.size()); |
241 | 58.1k | } |
242 | 55.1k | } |
243 | 55.1k | } |
244 | | |
245 | | template <typename ParserImpl> |
246 | | void JSONDataParser<ParserImpl>::traverseArrayElement(const Element& element, |
247 | 577k | ParseArrayContext& ctx) { |
248 | 577k | ParseContext element_ctx; |
249 | 577k | element_ctx.has_nested_in_flatten = ctx.has_nested_in_flatten; |
250 | 577k | element_ctx.is_top_array = ctx.is_top_array; |
251 | 577k | element_ctx.check_duplicate_json_path = ctx.check_duplicate_json_path; |
252 | 577k | element_ctx.reject_json_null_value = ctx.reject_json_null_value; |
253 | 577k | traverse(element, element_ctx); |
254 | 577k | auto& paths = element_ctx.paths; |
255 | 577k | auto& values = element_ctx.values; |
256 | | |
257 | 577k | if (element_ctx.has_nested_in_flatten && element_ctx.is_top_array) { |
258 | 6 | checkAmbiguousStructure(ctx, paths); |
259 | 6 | } |
260 | | |
261 | 577k | size_t size = paths.size(); |
262 | 577k | size_t keys_to_update = ctx.arrays_by_path.size(); |
263 | | |
264 | 1.15M | for (size_t i = 0; i < size; ++i) { |
265 | 580k | if (values[i].is_null()) { |
266 | 11.7k | continue; |
267 | 11.7k | } |
268 | | |
269 | 569k | UInt128 hash = PathInData::get_parts_hash(paths[i]); |
270 | 569k | auto found = ctx.arrays_by_path.find(hash); |
271 | | |
272 | 569k | if (found != ctx.arrays_by_path.end()) { |
273 | 510k | handleExistingPath(found->second, paths[i], values[i], ctx, keys_to_update); |
274 | 510k | } else { |
275 | 58.1k | handleNewPath(hash, paths[i], values[i], ctx); |
276 | 58.1k | } |
277 | 569k | } |
278 | | |
279 | | // always fill missed values to keep element-level association between keys. |
280 | 577k | if (keys_to_update) { |
281 | 10.2k | fillMissedValuesInArrays(ctx); |
282 | 10.2k | } |
283 | 577k | } |
284 | | |
285 | | // check if the structure of top_array is ambiguous like: |
286 | | // [{"a": {"b": {"c": 1}}}, {"a": {"b": 1}}] a.b is ambiguous |
287 | | template <typename ParserImpl> |
288 | | void JSONDataParser<ParserImpl>::checkAmbiguousStructure( |
289 | 6 | const ParseArrayContext& ctx, const std::vector<PathInData::Parts>& paths) { |
290 | 6 | for (auto&& current_path : paths) { |
291 | 8 | for (auto it = ctx.arrays_by_path.begin(); it != ctx.arrays_by_path.end(); ++it) { |
292 | 3 | auto&& [p, _] = it->second; |
293 | 3 | if (is_prefix(p, current_path) || is_prefix(current_path, p)) { |
294 | 1 | throw doris::Exception(doris::ErrorCode::INVALID_ARGUMENT, |
295 | 1 | "Ambiguous structure of top_array nested subcolumns: {}, {}", |
296 | 1 | PathInData(p).to_jsonpath(), |
297 | 1 | PathInData(current_path).to_jsonpath()); |
298 | 1 | } |
299 | 3 | } |
300 | 6 | } |
301 | 6 | } |
302 | | |
303 | | template <typename ParserImpl> |
304 | | void JSONDataParser<ParserImpl>::handleExistingPath(std::pair<PathInData::Parts, Array>& path_data, |
305 | | const PathInData::Parts& path, Field& value, |
306 | | ParseArrayContext& ctx, |
307 | 510k | size_t& keys_to_update) { |
308 | 510k | auto& path_array = path_data.second; |
309 | | // keep arrays aligned for all keys (including top-level arrays). |
310 | 510k | assert(path_array.size() == ctx.current_size); |
311 | | // If current element of array is part of Nested, |
312 | | // collect its size or check it if the size of |
313 | | // the Nested has been already collected. |
314 | 510k | auto nested_key = getNameOfNested(path, value); |
315 | 510k | if (!nested_key.empty()) { |
316 | 0 | size_t array_size = value.get<TYPE_ARRAY>().size(); |
317 | 0 | auto& current_nested_sizes = ctx.nested_sizes_by_key[nested_key]; |
318 | 0 | if (current_nested_sizes.size() == ctx.current_size) { |
319 | 0 | current_nested_sizes.push_back(array_size); |
320 | 0 | } else if (array_size != current_nested_sizes.back()) { |
321 | 0 | throw doris::Exception(doris::ErrorCode::INTERNAL_ERROR, |
322 | 0 | "Array sizes mismatched ({} and {})", array_size, |
323 | 0 | current_nested_sizes.back()); |
324 | 0 | } |
325 | 0 | } |
326 | | |
327 | 510k | path_array.push_back(std::move(value)); |
328 | 510k | --keys_to_update; |
329 | 510k | } |
330 | | |
331 | | template <typename ParserImpl> |
332 | | void JSONDataParser<ParserImpl>::handleNewPath(UInt128 hash, const PathInData::Parts& path, |
333 | 58.1k | Field& value, ParseArrayContext& ctx) { |
334 | 58.1k | Array path_array; |
335 | 58.1k | path_array.reserve(ctx.total_size); |
336 | | |
337 | | // always resize to keep alignment. |
338 | 58.1k | path_array.resize(ctx.current_size); |
339 | | |
340 | 58.1k | auto nested_key = getNameOfNested(path, value); |
341 | 58.1k | if (!nested_key.empty()) { |
342 | 3 | size_t array_size = value.get<TYPE_ARRAY>().size(); |
343 | 3 | auto& current_nested_sizes = ctx.nested_sizes_by_key[nested_key]; |
344 | 3 | if (current_nested_sizes.empty()) { |
345 | 2 | current_nested_sizes.resize(ctx.current_size); |
346 | 2 | } else { |
347 | | // If newly added element is part of the Nested then |
348 | | // resize its elements to keep correct sizes of Nested arrays. |
349 | 3 | for (size_t j = 0; j < ctx.current_size; ++j) { |
350 | 2 | path_array[j] = Field::create_field<TYPE_ARRAY>(Array(current_nested_sizes[j])); |
351 | 2 | } |
352 | 1 | } |
353 | 3 | if (current_nested_sizes.size() == ctx.current_size) { |
354 | 2 | current_nested_sizes.push_back(array_size); |
355 | 2 | } else if (array_size != current_nested_sizes.back()) { |
356 | 0 | throw doris::Exception(doris::ErrorCode::INTERNAL_ERROR, |
357 | 0 | "Array sizes mismatched ({} and {})", array_size, |
358 | 0 | current_nested_sizes.back()); |
359 | 0 | } |
360 | 3 | } |
361 | | |
362 | 58.1k | path_array.push_back(std::move(value)); |
363 | 58.1k | auto& elem = ctx.arrays_by_path[hash]; |
364 | 58.1k | elem.first = std::move(path); |
365 | 58.1k | elem.second = std::move(path_array); |
366 | 58.1k | } |
367 | | |
368 | | template <typename ParserImpl> |
369 | 10.2k | void JSONDataParser<ParserImpl>::fillMissedValuesInArrays(ParseArrayContext& ctx) { |
370 | 20.5k | for (auto it = ctx.arrays_by_path.begin(); it != ctx.arrays_by_path.end(); ++it) { |
371 | 10.2k | auto& [path, path_array] = it->second; |
372 | 10.2k | assert(path_array.size() == ctx.current_size || path_array.size() == ctx.current_size + 1); |
373 | 10.2k | if (path_array.size() == ctx.current_size) { |
374 | 10.2k | bool inserted = tryInsertDefaultFromNested(ctx, path, path_array); |
375 | 10.2k | if (!inserted) { |
376 | 10.2k | path_array.emplace_back(); |
377 | 10.2k | } |
378 | 10.2k | } |
379 | 10.2k | } |
380 | 10.2k | } |
381 | | |
382 | | template <typename ParserImpl> |
383 | | bool JSONDataParser<ParserImpl>::tryInsertDefaultFromNested(ParseArrayContext& ctx, |
384 | | const PathInData::Parts& path, |
385 | 10.2k | Array& array) { |
386 | | /// If there is a collected size of current Nested |
387 | | /// then insert array of this size as a default value. |
388 | 10.2k | if (path.empty() || array.empty()) { |
389 | 10.2k | return false; |
390 | 10.2k | } |
391 | | /// Last element is not Null, because otherwise this path wouldn't exist. |
392 | 1 | auto nested_key = getNameOfNested(path, array.back()); |
393 | 1 | if (nested_key.empty()) { |
394 | 1 | return false; |
395 | 1 | } |
396 | 0 | auto mapped = ctx.nested_sizes_by_key.find(nested_key); |
397 | 0 | if (mapped == ctx.nested_sizes_by_key.end()) { |
398 | 0 | return false; |
399 | 0 | } |
400 | 0 | auto& current_nested_sizes = mapped->second; |
401 | 0 | assert(current_nested_sizes.size() == ctx.current_size || |
402 | 0 | current_nested_sizes.size() == ctx.current_size + 1); |
403 | | /// If all keys of Nested were missed then add a zero length. |
404 | 0 | if (current_nested_sizes.size() == ctx.current_size) { |
405 | 0 | current_nested_sizes.push_back(0); |
406 | 0 | } |
407 | 0 | size_t array_size = current_nested_sizes.back(); |
408 | 0 | array.push_back(Field::create_field<TYPE_ARRAY>(Array(array_size))); |
409 | 0 | return true; |
410 | 0 | } |
411 | | |
412 | | template <typename ParserImpl> |
413 | | StringRef JSONDataParser<ParserImpl>::getNameOfNested(const PathInData::Parts& path, |
414 | 569k | const Field& value) { |
415 | 569k | if (value.get_type() != PrimitiveType::TYPE_ARRAY || path.empty()) { |
416 | 569k | return {}; |
417 | 569k | } |
418 | | /// Find first key that is marked as nested, |
419 | | /// because we may have struct of Nested and there could be |
420 | | /// several arrays with the same prefix, but with independent sizes. |
421 | | /// Consider we have array element with type `k2 Struct(k3 Nested(...), k5 Nested(...))` |
422 | | /// Then subcolumns `k2.k3` and `k2.k5` may have indepented sizes and we should extract |
423 | | /// `k3` and `k5` keys instead of `k2`. |
424 | 3 | for (const auto& part : path) { |
425 | 3 | if (part.is_nested) { |
426 | 3 | return {part.key.data(), part.key.size()}; |
427 | 3 | } |
428 | 3 | } |
429 | 0 | return {}; |
430 | 3 | } |
431 | | |
432 | | template class JSONDataParser<SimdJSONParser>; |
433 | | } // namespace doris |