forked from apache/doris
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjson_parser.cpp
More file actions
299 lines (283 loc) · 12.1 KB
/
Copy pathjson_parser.cpp
File metadata and controls
299 lines (283 loc) · 12.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
// This file is copied from
// https://github.com/ClickHouse/ClickHouse/blob/master/src/Common/JSONParsers/SimdJSONParser.cpp
// and modified by Doris
#include "vec/json/json_parser.h"
#include <assert.h>
#include <fmt/format.h>
#include <glog/logging.h>
#include <algorithm>
#include <string_view>
#include "common/config.h"
#include "common/status.h"
#include "vec/json/path_in_data.h"
#include "vec/json/simd_json_parser.h"
namespace doris::vectorized {
template <typename ParserImpl>
std::optional<ParseResult> JSONDataParser<ParserImpl>::parse(const char* begin, size_t length,
const ParseConfig& config) {
Element document;
if (!parser.parse(begin, length, document)) {
return {};
}
ParseContext context;
context.enable_flatten_nested = config.enable_flatten_nested;
traverse(document, context);
ParseResult result;
result.values = std::move(context.values);
result.paths.reserve(context.paths.size());
for (auto&& path : context.paths) {
result.paths.emplace_back(std::move(path));
}
return result;
}
template <typename ParserImpl>
void JSONDataParser<ParserImpl>::traverse(const Element& element, ParseContext& ctx) {
// checkStackSize();
if (element.isObject()) {
traverseObject(element.getObject(), ctx);
} else if (element.isArray()) {
has_nested = false;
check_has_nested_object(element);
if (has_nested && !ctx.enable_flatten_nested) {
// Parse nested arrays to JsonbField
JsonbWriter writer;
traverseArrayAsJsonb(element.getArray(), writer);
ctx.paths.push_back(ctx.builder.get_parts());
ctx.values.push_back(
JsonbField(writer.getOutput()->getBuffer(), writer.getOutput()->getSize()));
} else {
traverseArray(element.getArray(), ctx);
}
} else {
ctx.paths.push_back(ctx.builder.get_parts());
ctx.values.push_back(getValueAsField(element));
}
}
template <typename ParserImpl>
void JSONDataParser<ParserImpl>::traverseObject(const JSONObject& object, ParseContext& ctx) {
ctx.paths.reserve(ctx.paths.size() + object.size());
ctx.values.reserve(ctx.values.size() + object.size());
for (auto it = object.begin(); it != object.end(); ++it) {
const auto& [key, value] = *it;
ctx.builder.append(key, false);
traverse(value, ctx);
ctx.builder.pop_back();
}
}
template <typename ParserImpl>
void JSONDataParser<ParserImpl>::check_has_nested_object(const Element& element) {
if (element.isArray()) {
const JSONArray& array = element.getArray();
for (auto it = array.begin(); it != array.end(); ++it) {
check_has_nested_object(*it);
}
}
if (element.isObject()) {
has_nested = true;
}
}
template <typename ParserImpl>
void JSONDataParser<ParserImpl>::traverseAsJsonb(const Element& element, JsonbWriter& writer) {
if (element.isObject()) {
traverseObjectAsJsonb(element.getObject(), writer);
} else if (element.isArray()) {
traverseArrayAsJsonb(element.getArray(), writer);
} else {
writeValueAsJsonb(element, writer);
}
}
template <typename ParserImpl>
void JSONDataParser<ParserImpl>::traverseObjectAsJsonb(const JSONObject& object,
JsonbWriter& writer) {
writer.writeStartObject();
for (auto it = object.begin(); it != object.end(); ++it) {
const auto& [key, value] = *it;
writer.writeKey(key.data(), key.size());
traverseAsJsonb(value, writer);
}
writer.writeEndObject();
}
template <typename ParserImpl>
void JSONDataParser<ParserImpl>::traverseArrayAsJsonb(const JSONArray& array, JsonbWriter& writer) {
writer.writeStartArray();
for (auto it = array.begin(); it != array.end(); ++it) {
traverseAsJsonb(*it, writer);
}
writer.writeEndArray();
}
template <typename ParserImpl>
void JSONDataParser<ParserImpl>::traverseArray(const JSONArray& array, ParseContext& ctx) {
/// Traverse elements of array and collect an array of fields by each path.
ParseArrayContext array_ctx;
array_ctx.total_size = array.size();
for (auto it = array.begin(); it != array.end(); ++it) {
traverseArrayElement(*it, array_ctx);
++array_ctx.current_size;
}
auto&& arrays_by_path = array_ctx.arrays_by_path;
if (arrays_by_path.empty()) {
ctx.paths.push_back(ctx.builder.get_parts());
ctx.values.push_back(Array());
} else {
ctx.paths.reserve(ctx.paths.size() + arrays_by_path.size());
ctx.values.reserve(ctx.values.size() + arrays_by_path.size());
for (auto it = arrays_by_path.begin(); it != arrays_by_path.end(); ++it) {
auto&& [path, path_array] = it->second;
/// Merge prefix path and path of array element.
ctx.paths.push_back(ctx.builder.append(path, true).get_parts());
ctx.values.push_back(std::move(path_array));
ctx.builder.pop_back(path.size());
}
}
}
template <typename ParserImpl>
void JSONDataParser<ParserImpl>::traverseArrayElement(const Element& element,
ParseArrayContext& ctx) {
ParseContext element_ctx;
traverse(element, element_ctx);
auto& [_, paths, values, flatten_nested] = element_ctx;
size_t size = paths.size();
size_t keys_to_update = ctx.arrays_by_path.size();
for (size_t i = 0; i < size; ++i) {
if (values[i].is_null()) {
continue;
}
UInt128 hash = PathInData::get_parts_hash(paths[i]);
auto found = ctx.arrays_by_path.find(hash);
if (found != ctx.arrays_by_path.end()) {
auto& path_array = found->second.second;
assert(path_array.size() == ctx.current_size);
/// If current element of array is part of Nested,
/// collect its size or check it if the size of
/// the Nested has been already collected.
auto nested_key = getNameOfNested(paths[i], values[i]);
if (!nested_key.empty()) {
size_t array_size = get<const Array&>(values[i]).size();
auto& current_nested_sizes = ctx.nested_sizes_by_key[nested_key];
if (current_nested_sizes.size() == ctx.current_size) {
current_nested_sizes.push_back(array_size);
} else if (array_size != current_nested_sizes.back()) {
throw doris::Exception(doris::ErrorCode::INTERNAL_ERROR,
"Array sizes mismatched ({} and {})", array_size,
current_nested_sizes.back());
}
}
path_array.push_back(std::move(values[i]));
--keys_to_update;
} else {
/// We found a new key. Add and empty array with current size.
Array path_array;
path_array.reserve(ctx.total_size);
path_array.resize(ctx.current_size);
auto nested_key = getNameOfNested(paths[i], values[i]);
if (!nested_key.empty()) {
size_t array_size = get<const Array&>(values[i]).size();
auto& current_nested_sizes = ctx.nested_sizes_by_key[nested_key];
if (current_nested_sizes.empty()) {
current_nested_sizes.resize(ctx.current_size);
} else {
/// If newly added element is part of the Nested then
/// resize its elements to keep correct sizes of Nested arrays.
for (size_t j = 0; j < ctx.current_size; ++j) {
path_array[j] = Array(current_nested_sizes[j]);
}
}
if (current_nested_sizes.size() == ctx.current_size) {
current_nested_sizes.push_back(array_size);
} else if (array_size != current_nested_sizes.back()) {
throw doris::Exception(ErrorCode::INTERNAL_ERROR,
"Array sizes mismatched ({} and {})", array_size,
current_nested_sizes.back());
}
}
path_array.push_back(std::move(values[i]));
auto& elem = ctx.arrays_by_path[hash];
elem.first = std::move(paths[i]);
elem.second = std::move(path_array);
}
}
/// If some of the keys are missed in current element,
/// add default values for them.
if (keys_to_update) {
fillMissedValuesInArrays(ctx);
}
}
template <typename ParserImpl>
void JSONDataParser<ParserImpl>::fillMissedValuesInArrays(ParseArrayContext& ctx) {
for (auto it = ctx.arrays_by_path.begin(); it != ctx.arrays_by_path.end(); ++it) {
auto& [path, path_array] = it->second;
assert(path_array.size() == ctx.current_size || path_array.size() == ctx.current_size + 1);
if (path_array.size() == ctx.current_size) {
bool inserted = tryInsertDefaultFromNested(ctx, path, path_array);
if (!inserted) {
path_array.emplace_back();
}
}
}
}
template <typename ParserImpl>
bool JSONDataParser<ParserImpl>::tryInsertDefaultFromNested(ParseArrayContext& ctx,
const PathInData::Parts& path,
Array& array) {
/// If there is a collected size of current Nested
/// then insert array of this size as a default value.
if (path.empty() || array.empty()) {
return false;
}
/// Last element is not Null, because otherwise this path wouldn't exist.
auto nested_key = getNameOfNested(path, array.back());
if (nested_key.empty()) {
return false;
}
auto mapped = ctx.nested_sizes_by_key.find(nested_key);
if (mapped == ctx.nested_sizes_by_key.end()) {
return false;
}
auto& current_nested_sizes = mapped->second;
assert(current_nested_sizes.size() == ctx.current_size ||
current_nested_sizes.size() == ctx.current_size + 1);
/// If all keys of Nested were missed then add a zero length.
if (current_nested_sizes.size() == ctx.current_size) {
current_nested_sizes.push_back(0);
}
size_t array_size = current_nested_sizes.back();
array.push_back(Array(array_size));
return true;
}
template <typename ParserImpl>
StringRef JSONDataParser<ParserImpl>::getNameOfNested(const PathInData::Parts& path,
const Field& value) {
if (value.get_type() != Field::Types::Array || path.empty()) {
return {};
}
/// Find first key that is marked as nested,
/// because we may have tuple of Nested and there could be
/// several arrays with the same prefix, but with independent sizes.
/// Consider we have array element with type `k2 Tuple(k3 Nested(...), k5 Nested(...))`
/// Then subcolumns `k2.k3` and `k2.k5` may have indepented sizes and we should extract
/// `k3` and `k5` keys instead of `k2`.
for (const auto& part : path) {
if (part.is_nested) {
return StringRef(part.key.data(), part.key.size());
}
}
return {};
}
template class JSONDataParser<SimdJSONParser>;
} // namespace doris::vectorized