Coverage Report

Created: 2026-07-17 21:30

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/exec/common/variant_util.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
18
#include "exec/common/variant_util.h"
19
20
#include <fmt/format.h>
21
#include <gen_cpp/FrontendService.h>
22
#include <gen_cpp/FrontendService_types.h>
23
#include <gen_cpp/HeartbeatService_types.h>
24
#include <gen_cpp/MasterService_types.h>
25
#include <gen_cpp/Status_types.h>
26
#include <gen_cpp/Types_types.h>
27
#include <glog/logging.h>
28
#include <rapidjson/document.h>
29
#include <rapidjson/stringbuffer.h>
30
#include <rapidjson/writer.h>
31
#include <simdjson/simdjson.h> // IWYU pragma: keep
32
#include <unicode/uchar.h>
33
34
#include <algorithm>
35
#include <cassert>
36
#include <cstddef>
37
#include <cstdint>
38
#include <cstring>
39
#include <list>
40
#include <memory>
41
#include <mutex>
42
#include <optional>
43
#include <ostream>
44
#include <ranges>
45
#include <set>
46
#include <stack>
47
#include <string>
48
#include <string_view>
49
#include <unordered_map>
50
#include <utility>
51
#include <vector>
52
53
#include "common/config.h"
54
#include "common/status.h"
55
#include "core/assert_cast.h"
56
#include "core/block/block.h"
57
#include "core/block/column_numbers.h"
58
#include "core/block/column_with_type_and_name.h"
59
#include "core/column/column.h"
60
#include "core/column/column_array.h"
61
#include "core/column/column_map.h"
62
#include "core/column/column_nullable.h"
63
#include "core/column/column_string.h"
64
#include "core/column/column_variant.h"
65
#include "core/data_type/data_type.h"
66
#include "core/data_type/data_type_array.h"
67
#include "core/data_type/data_type_factory.hpp"
68
#include "core/data_type/data_type_jsonb.h"
69
#include "core/data_type/data_type_nullable.h"
70
#include "core/data_type/data_type_string.h"
71
#include "core/data_type/data_type_variant.h"
72
#include "core/data_type/define_primitive_type.h"
73
#include "core/data_type/get_least_supertype.h"
74
#include "core/data_type/primitive_type.h"
75
#include "core/data_type/storage_field_type.h"
76
#include "core/field.h"
77
#include "core/typeid_cast.h"
78
#include "core/types.h"
79
#include "exec/common/field_visitors.h"
80
#include "exec/common/sip_hash.h"
81
#include "exprs/function/function.h"
82
#include "exprs/function/simple_function_factory.h"
83
#include "exprs/function_context.h"
84
#include "exprs/json_functions.h"
85
#include "re2/re2.h"
86
#include "runtime/exec_env.h"
87
#include "runtime/runtime_state.h"
88
#include "storage/olap_common.h"
89
#include "storage/rowset/beta_rowset.h"
90
#include "storage/rowset/rowset.h"
91
#include "storage/rowset/rowset_fwd.h"
92
#include "storage/segment/segment_loader.h"
93
#include "storage/segment/variant/nested_group_path.h"
94
#include "storage/segment/variant/variant_column_reader.h"
95
#include "storage/segment/variant/variant_column_writer_impl.h"
96
#include "storage/tablet/tablet.h"
97
#include "storage/tablet/tablet_fwd.h"
98
#include "storage/tablet/tablet_schema.h"
99
#include "util/client_cache.h"
100
#include "util/defer_op.h"
101
#include "util/json/json_parser.h"
102
#include "util/json/path_in_data.h"
103
#include "util/json/simd_json_parser.h"
104
#include "util/jsonb_utils.h"
105
106
namespace doris::variant_util {
107
108
namespace {
109
110
74
PathInData make_full_subcolumn_path(const TabletColumnPtr& parent_column, std::string_view path) {
111
74
    if (!path.empty()) {
112
68
        return PathInData(parent_column->name_lower_case() + "." + std::string(path));
113
68
    }
114
115
    // Keep the empty JSON key as a real path part. The variant root is `parts.empty()`;
116
    // an empty key is `parts.size() == 1 && parts[0].key.empty()` after popping root.
117
6
    PathInDataBuilder builder;
118
6
    return builder.append(parent_column->name_lower_case(), false).append("", false).build();
119
74
}
120
121
void append_empty_key_subcolumn_from_stats(TabletSchema::PathsSetInfo& paths_set_info,
122
                                           const TabletColumnPtr& parent_column,
123
6
                                           TabletSchemaSPtr& output_schema) {
124
6
    if (!paths_set_info.sub_path_set.contains("") || paths_set_info.sparse_path_set.contains("") ||
125
6
        paths_set_info.subcolumn_indexes.contains("")) {
126
5
        return;
127
5
    }
128
129
1
    auto column_name = parent_column->name_lower_case() + ".";
130
1
    auto column_path = make_full_subcolumn_path(parent_column, "");
131
132
1
    TabletColumn subcolumn;
133
1
    subcolumn.set_name(column_name);
134
1
    subcolumn.set_type(FieldType::OLAP_FIELD_TYPE_VARIANT);
135
1
    subcolumn.set_parent_unique_id(parent_column->unique_id());
136
1
    subcolumn.set_path_info(column_path);
137
1
    subcolumn.set_aggregation_method(parent_column->aggregation());
138
1
    subcolumn.set_variant_max_subcolumns_count(parent_column->variant_max_subcolumns_count());
139
1
    subcolumn.set_variant_enable_doc_mode(parent_column->variant_enable_doc_mode());
140
1
    subcolumn.set_is_nullable(true);
141
1
    output_schema->append_column(subcolumn);
142
1
}
143
144
} // namespace
145
146
279
inline void append_escaped_regex_char(std::string* regex_output, char ch) {
147
279
    switch (ch) {
148
11
    case '.':
149
13
    case '^':
150
15
    case '$':
151
17
    case '+':
152
22
    case '*':
153
24
    case '?':
154
26
    case '(':
155
28
    case ')':
156
30
    case '|':
157
32
    case '{':
158
34
    case '}':
159
36
    case '[':
160
36
    case ']':
161
40
    case '\\':
162
40
        regex_output->push_back('\\');
163
40
        regex_output->push_back(ch);
164
40
        break;
165
239
    default:
166
239
        regex_output->push_back(ch);
167
239
        break;
168
279
    }
169
279
}
170
171
// Small LRU to cap compiled glob patterns
172
constexpr size_t kGlobRegexCacheCapacity = 256;
173
174
struct GlobRegexCacheEntry {
175
    std::shared_ptr<RE2> re2;
176
    std::list<std::string>::iterator lru_it;
177
};
178
179
static std::mutex g_glob_regex_cache_mutex;
180
static std::list<std::string> g_glob_regex_cache_lru;
181
static std::unordered_map<std::string, GlobRegexCacheEntry> g_glob_regex_cache;
182
183
286
std::shared_ptr<RE2> get_or_build_re2(const std::string& glob_pattern) {
184
286
    {
185
286
        std::lock_guard<std::mutex> lock(g_glob_regex_cache_mutex);
186
286
        auto it = g_glob_regex_cache.find(glob_pattern);
187
286
        if (it != g_glob_regex_cache.end()) {
188
230
            g_glob_regex_cache_lru.splice(g_glob_regex_cache_lru.begin(), g_glob_regex_cache_lru,
189
230
                                          it->second.lru_it);
190
230
            return it->second.re2;
191
230
        }
192
286
    }
193
56
    std::string regex_pattern;
194
56
    Status st = glob_to_regex(glob_pattern, &regex_pattern);
195
56
    if (!st.ok()) {
196
2
        return nullptr;
197
2
    }
198
54
    auto compiled = std::make_shared<RE2>(regex_pattern);
199
54
    if (!compiled->ok()) {
200
3
        return nullptr;
201
3
    }
202
51
    {
203
51
        std::lock_guard<std::mutex> lock(g_glob_regex_cache_mutex);
204
51
        auto it = g_glob_regex_cache.find(glob_pattern);
205
51
        if (it != g_glob_regex_cache.end()) {
206
0
            g_glob_regex_cache_lru.splice(g_glob_regex_cache_lru.begin(), g_glob_regex_cache_lru,
207
0
                                          it->second.lru_it);
208
0
            return it->second.re2;
209
0
        }
210
51
        g_glob_regex_cache_lru.push_front(glob_pattern);
211
51
        g_glob_regex_cache.emplace(glob_pattern,
212
51
                                   GlobRegexCacheEntry {compiled, g_glob_regex_cache_lru.begin()});
213
51
        if (g_glob_regex_cache.size() > kGlobRegexCacheCapacity) {
214
0
            const std::string& evict_key = g_glob_regex_cache_lru.back();
215
0
            g_glob_regex_cache.erase(evict_key);
216
0
            g_glob_regex_cache_lru.pop_back();
217
0
        }
218
51
    }
219
0
    return compiled;
220
51
}
221
222
// Convert a restricted glob pattern into a regex.
223
// Supported: '*', '?', '[...]', '\\' escape. Others are treated as literals.
224
94
Status glob_to_regex(const std::string& glob_pattern, std::string* regex_pattern) {
225
94
    regex_pattern->clear();
226
94
    regex_pattern->append("^");
227
94
    bool is_escaped = false;
228
94
    size_t pattern_length = glob_pattern.size();
229
447
    for (size_t index = 0; index < pattern_length; ++index) {
230
357
        char current_char = glob_pattern[index];
231
357
        if (is_escaped) {
232
9
            append_escaped_regex_char(regex_pattern, current_char);
233
9
            is_escaped = false;
234
9
            continue;
235
9
        }
236
348
        if (current_char == '\\') {
237
13
            is_escaped = true;
238
13
            continue;
239
13
        }
240
335
        if (current_char == '*') {
241
24
            regex_pattern->append(".*");
242
24
            continue;
243
24
        }
244
311
        if (current_char == '?') {
245
13
            regex_pattern->append(".");
246
13
            continue;
247
13
        }
248
298
        if (current_char == '[') {
249
32
            size_t class_index = index + 1;
250
32
            bool class_closed = false;
251
32
            bool is_class_escaped = false;
252
32
            std::string class_buffer;
253
32
            if (class_index < pattern_length &&
254
32
                (glob_pattern[class_index] == '!' || glob_pattern[class_index] == '^')) {
255
9
                class_buffer.push_back('^');
256
9
                ++class_index;
257
9
            }
258
95
            for (; class_index < pattern_length; ++class_index) {
259
91
                char class_char = glob_pattern[class_index];
260
91
                if (is_class_escaped) {
261
10
                    class_buffer.push_back(class_char);
262
10
                    is_class_escaped = false;
263
10
                    continue;
264
10
                }
265
81
                if (class_char == '\\') {
266
10
                    is_class_escaped = true;
267
10
                    continue;
268
10
                }
269
71
                if (class_char == ']') {
270
28
                    class_closed = true;
271
28
                    break;
272
28
                }
273
43
                class_buffer.push_back(class_char);
274
43
            }
275
32
            if (!class_closed) {
276
4
                return Status::InvalidArgument("Unclosed character class in glob pattern: {}",
277
4
                                               glob_pattern);
278
4
            }
279
28
            regex_pattern->append("[");
280
28
            regex_pattern->append(class_buffer);
281
28
            regex_pattern->append("]");
282
28
            index = class_index;
283
28
            continue;
284
32
        }
285
266
        append_escaped_regex_char(regex_pattern, current_char);
286
266
    }
287
90
    if (is_escaped) {
288
4
        append_escaped_regex_char(regex_pattern, '\\');
289
4
    }
290
90
    regex_pattern->append("$");
291
90
    return Status::OK();
292
94
}
293
294
286
bool glob_match_re2(const std::string& glob_pattern, const std::string& candidate_path) {
295
286
    auto compiled = get_or_build_re2(glob_pattern);
296
286
    if (compiled == nullptr) {
297
5
        return false;
298
5
    }
299
281
    return RE2::FullMatch(candidate_path, *compiled);
300
286
}
301
302
// NestedGroup's physical children and offsets are produced by NestedGroupWriteProvider, not by
303
// appending TabletSchema extracted columns here. This predicate keeps only ordinary Variant paths
304
// that are outside the NG tree, for example `v.owner` beside `v.items[*]`.
305
0
bool is_regular_path_outside_nested_group(const PathInData& path) {
306
0
    const std::string& relative_path = path.get_path();
307
0
    return !relative_path.empty() && !path.get_is_typed() && !path.has_nested_part() &&
308
0
           !segment_v2::contains_nested_group_marker(relative_path) &&
309
0
           !segment_v2::is_root_nested_group_path(relative_path) &&
310
0
           relative_path != SPARSE_COLUMN_PATH &&
311
0
           relative_path.find(DOC_VALUE_COLUMN_PATH) == std::string::npos;
312
0
}
313
314
bool should_materialize_nested_group_regular_subcolumns(
315
        const TabletColumnPtr& column,
316
34
        const std::unordered_map<int32_t, VariantExtendedInfo>& uid_to_variant_extended_info) {
317
34
    const auto info_it = uid_to_variant_extended_info.find(column->unique_id());
318
34
    return column->variant_enable_nested_group() ||
319
34
           (info_it != uid_to_variant_extended_info.end() && info_it->second.has_nested_group);
320
34
}
321
322
std::unordered_set<int32_t> collect_nested_group_compaction_root_uids(
323
        const TabletSchemaSPtr& target,
324
67
        const std::unordered_map<int32_t, VariantExtendedInfo>& uid_to_variant_extended_info) {
325
67
    std::unordered_set<int32_t> root_uids;
326
881
    for (const TabletColumnPtr& column : target->columns()) {
327
881
        if (column->is_variant_type() && should_materialize_nested_group_regular_subcolumns(
328
34
                                                 column, uid_to_variant_extended_info)) {
329
1
            root_uids.insert(column->unique_id());
330
1
        }
331
881
    }
332
67
    return root_uids;
333
67
}
334
335
PathToDataTypes collect_regular_types_outside_nested_group(
336
1
        const VariantExtendedInfo& extended_info) {
337
1
    PathToDataTypes regular_path_to_data_types;
338
1
    for (const auto& [path, data_types] : extended_info.path_to_data_types) {
339
0
        if (!is_regular_path_outside_nested_group(path)) {
340
0
            continue;
341
0
        }
342
0
        regular_path_to_data_types.emplace(path, data_types);
343
0
    }
344
1
    return regular_path_to_data_types;
345
1
}
346
347
80
size_t get_number_of_dimensions(const IDataType& type) {
348
80
    if (const auto* type_array = typeid_cast<const DataTypeArray*>(&type)) {
349
4
        return type_array->get_number_of_dimensions();
350
4
    }
351
76
    return 0;
352
80
}
353
3
size_t get_number_of_dimensions(const IColumn& column) {
354
3
    if (const auto* column_array = check_and_get_column<ColumnArray>(column)) {
355
2
        return column_array->get_number_of_dimensions();
356
2
    }
357
1
    return 0;
358
3
}
359
360
1.10k
DataTypePtr get_base_type_of_array(const DataTypePtr& type) {
361
    /// Get raw pointers to avoid extra copying of type pointers.
362
1.10k
    const DataTypeArray* last_array = nullptr;
363
1.10k
    const auto* current_type = type.get();
364
1.10k
    if (const auto* nullable = typeid_cast<const DataTypeNullable*>(current_type)) {
365
1.09k
        current_type = nullable->get_nested_type().get();
366
1.09k
    }
367
1.12k
    while (const auto* type_array = typeid_cast<const DataTypeArray*>(current_type)) {
368
28
        current_type = type_array->get_nested_type().get();
369
28
        last_array = type_array;
370
28
        if (const auto* nullable = typeid_cast<const DataTypeNullable*>(current_type)) {
371
28
            current_type = nullable->get_nested_type().get();
372
28
        }
373
28
    }
374
1.10k
    return last_array ? last_array->get_nested_type() : type;
375
1.10k
}
376
377
49.6k
Status cast_column(const ColumnWithTypeAndName& arg, const DataTypePtr& type, ColumnPtr* result) {
378
49.6k
    ColumnsWithTypeAndName arguments {arg, {nullptr, type, type->get_name()}};
379
380
    // To prevent from null info lost, we should not call function since the function framework will wrap
381
    // nullable to Variant instead of the root of Variant
382
    // correct output: Nullable(Array(int)) -> Nullable(Variant(Nullable(Array(int))))
383
    // incorrect output: Nullable(Array(int)) -> Nullable(Variant(Array(int)))
384
49.6k
    if (type->get_primitive_type() == TYPE_VARIANT) {
385
        // If source column is variant, so the nullable info is different from dst column
386
19
        if (arg.type->get_primitive_type() == TYPE_VARIANT) {
387
1
            *result = type->is_nullable() ? make_nullable(arg.column) : remove_nullable(arg.column);
388
1
            return Status::OK();
389
1
        }
390
        // set variant root column/type to from column/type
391
19
        CHECK(is_column_nullable(*arg.column));
392
18
        auto to_type = remove_nullable(type);
393
18
        const auto& data_type_object = assert_cast<const DataTypeVariant&>(*to_type);
394
18
        auto variant = ColumnVariant::create(data_type_object.variant_max_subcolumns_count(),
395
18
                                             data_type_object.enable_doc_mode());
396
397
18
        variant->create_root(arg.type, IColumn::mutate(arg.column));
398
18
        ColumnPtr nullable = ColumnNullable::create(
399
18
                variant->get_ptr(),
400
18
                assert_cast<const ColumnNullable*>(arg.column.get())->get_null_map_column_ptr());
401
18
        *result = type->is_nullable() ? nullable : variant->get_ptr();
402
18
        return Status::OK();
403
19
    }
404
405
49.6k
    auto function = SimpleFunctionFactory::instance().get_function("CAST", arguments, type);
406
49.6k
    if (!function) {
407
0
        return Status::InternalError("Not found cast function {} to {}", arg.type->get_name(),
408
0
                                     type->get_name());
409
0
    }
410
49.6k
    Block tmp_block {arguments};
411
49.6k
    uint32_t result_column = cast_set<uint32_t>(tmp_block.columns());
412
49.6k
    RuntimeState state;
413
49.6k
    auto ctx = FunctionContext::create_context(&state, {}, {});
414
415
49.6k
    if (arg.type->get_primitive_type() == INVALID_TYPE) {
416
        // cast from nothing to any type should result in nulls
417
733
        *result = type->create_column_const_with_default_value(arg.column->size())
418
733
                          ->convert_to_full_column_if_const();
419
733
        return Status::OK();
420
733
    }
421
422
    // We convert column string to jsonb type just add a string jsonb field to dst column instead of parse
423
    // each line in original string column.
424
48.8k
    ctx->set_string_as_jsonb_string(true);
425
48.8k
    ctx->set_jsonb_string_as_string(true);
426
48.8k
    tmp_block.insert({nullptr, type, arg.name});
427
    // TODO(lihangyu): we should handle this error in strict mode
428
48.8k
    if (!function->execute(ctx.get(), tmp_block, {0}, result_column, arg.column->size())) {
429
0
        LOG_EVERY_N(WARNING, 100) << fmt::format("cast from {} to {}", arg.type->get_name(),
430
0
                                                 type->get_name());
431
0
        *result = type->create_column_const_with_default_value(arg.column->size())
432
0
                          ->convert_to_full_column_if_const();
433
0
        return Status::OK();
434
0
    }
435
48.8k
    *result = tmp_block.get_by_position(result_column).column->convert_to_full_column_if_const();
436
48.8k
    VLOG_DEBUG << fmt::format("{} before convert {}, after convert {}", arg.name,
437
0
                              arg.column->get_name(), (*result)->get_name());
438
48.8k
    return Status::OK();
439
48.8k
}
440
441
2
ColumnPtr jsonb_root_to_json_string_column(const IColumn& root) {
442
2
    auto root_column = root.convert_to_full_column_if_const();
443
2
    const IColumn* jsonb_column = root_column.get();
444
2
    const NullMap* null_map = nullptr;
445
2
    if (root_column->is_nullable()) {
446
0
        const auto& nullable = assert_cast<const ColumnNullable&>(*root_column);
447
0
        jsonb_column = &nullable.get_nested_column();
448
0
        null_map = &nullable.get_null_map_data();
449
0
    }
450
451
2
    const auto& column = assert_cast<const ColumnString&>(*jsonb_column);
452
2
    auto result = ColumnString::create();
453
2
    result->reserve(column.size());
454
4
    for (size_t i = 0; i < column.size(); ++i) {
455
2
        if (null_map != nullptr && (*null_map)[i]) {
456
0
            result->insert_default();
457
0
            continue;
458
0
        }
459
460
2
        const auto jsonb = column.get_data_at(i);
461
2
        if (jsonb.size == 0) {
462
0
            result->insert_default();
463
0
            continue;
464
0
        }
465
466
2
        const auto json = JsonbToJson::jsonb_to_json_string(jsonb.data, jsonb.size);
467
2
        result->insert_data(json.data(), json.size());
468
2
    }
469
2
    return result->get_ptr();
470
2
}
471
472
void get_column_by_type(const DataTypePtr& data_type, const std::string& name, TabletColumn& column,
473
2.41k
                        const ExtraInfo& ext_info) {
474
2.41k
    column.set_name(name);
475
2.41k
    column.set_type(data_type->get_storage_field_type());
476
2.41k
    if (ext_info.unique_id >= 0) {
477
4
        column.set_unique_id(ext_info.unique_id);
478
4
    }
479
2.41k
    if (ext_info.parent_unique_id >= 0) {
480
1.19k
        column.set_parent_unique_id(ext_info.parent_unique_id);
481
1.19k
    }
482
2.41k
    if (!ext_info.path_info.empty()) {
483
1.19k
        column.set_path_info(ext_info.path_info);
484
1.19k
    }
485
2.41k
    if (data_type->is_nullable()) {
486
1.19k
        const auto& real_type = static_cast<const DataTypeNullable&>(*data_type);
487
1.19k
        column.set_is_nullable(true);
488
1.19k
        get_column_by_type(real_type.get_nested_type(), name, column, {});
489
1.19k
        return;
490
1.19k
    }
491
1.21k
    if (data_type->get_primitive_type() == PrimitiveType::TYPE_ARRAY) {
492
19
        TabletColumn child;
493
19
        get_column_by_type(assert_cast<const DataTypeArray*>(data_type.get())->get_nested_type(),
494
19
                           "", child, {});
495
19
        column.set_length(TabletColumn::get_field_length_by_type(TPrimitiveType::ARRAY, 0));
496
19
        column.add_sub_column(child);
497
19
        return;
498
19
    }
499
1.19k
    if (data_type->get_primitive_type() == PrimitiveType::TYPE_VARIANT) {
500
0
        const auto* dt_variant = assert_cast<const DataTypeVariant*>(data_type.get());
501
0
        column.set_variant_max_subcolumns_count(dt_variant->variant_max_subcolumns_count());
502
0
        column.set_variant_enable_doc_mode(dt_variant->enable_doc_mode());
503
0
        return;
504
0
    }
505
    // size is not fixed when type is string or json
506
1.19k
    if (is_string_type(data_type->get_primitive_type()) ||
507
1.19k
        data_type->get_primitive_type() == TYPE_JSONB) {
508
477
        column.set_length(INT_MAX);
509
477
        return;
510
477
    }
511
512
720
    PrimitiveType type = data_type->get_primitive_type();
513
720
    if (is_int_or_bool(type) || is_string_type(type) || is_float_or_double(type) || is_ip(type) ||
514
720
        is_date_or_datetime(type) || type == PrimitiveType::TYPE_DATEV2) {
515
715
        column.set_length(cast_set<int32_t>(data_type->get_size_of_value_in_memory()));
516
715
        return;
517
715
    }
518
5
    if (is_decimal(type)) {
519
1
        column.set_precision(data_type->get_precision());
520
1
        column.set_frac(data_type->get_scale());
521
1
        return;
522
1
    }
523
    // datetimev2 needs scale
524
4
    if (type == PrimitiveType::TYPE_DATETIMEV2 || type == PrimitiveType::TYPE_TIMESTAMPTZ) {
525
3
        column.set_precision(-1);
526
3
        column.set_frac(data_type->get_scale());
527
3
        return;
528
3
    }
529
530
1
    throw doris::Exception(doris::ErrorCode::INTERNAL_ERROR,
531
1
                           "unexcepted data column type: {}, column name is: {}",
532
1
                           data_type->get_name(), name);
533
4
}
534
535
TabletColumn get_column_by_type(const DataTypePtr& data_type, const std::string& name,
536
1.15k
                                const ExtraInfo& ext_info) {
537
1.15k
    TabletColumn result;
538
1.15k
    get_column_by_type(data_type, name, result, ext_info);
539
1.15k
    return result;
540
1.15k
}
541
542
// check if two paths which same prefix have different structure
543
static bool has_different_structure_in_same_path(const PathInData::Parts& lhs,
544
9.01k
                                                 const PathInData::Parts& rhs) {
545
9.01k
    if (lhs.size() != rhs.size()) {
546
1
        return false; // different size means different structure
547
1
    }
548
    // Since we group by path string, lhs and rhs must have the same size and keys
549
    // We only need to check if they have different nested structure
550
36.0k
    for (size_t i = 0; i < lhs.size(); ++i) {
551
27.0k
        if (lhs[i] != rhs[i]) {
552
5
            VLOG_DEBUG << fmt::format(
553
0
                    "Check different structure: {} vs {}, lhs[i].is_nested: {}, rhs[i].is_nested: "
554
0
                    "{}",
555
0
                    lhs[i].key, rhs[i].key, lhs[i].is_nested, rhs[i].is_nested);
556
5
            return true;
557
5
        }
558
27.0k
    }
559
9.01k
    return false;
560
9.01k
}
561
562
3.05k
Status check_variant_has_no_ambiguous_paths(const PathsInData& tuple_paths) {
563
    // Group paths by their string representation to reduce comparisons
564
3.05k
    std::unordered_map<std::string, std::vector<size_t>> path_groups;
565
566
24.1k
    for (size_t i = 0; i < tuple_paths.size(); ++i) {
567
        // same path should have same structure, so we group them by path
568
21.0k
        path_groups[tuple_paths[i].get_path()].push_back(i);
569
        // print part of tuple_paths[i]
570
21.0k
        VLOG_DEBUG << "tuple_paths[i]: " << tuple_paths[i].get_path();
571
21.0k
    }
572
573
    // Only compare paths within the same group
574
12.0k
    for (const auto& [path_str, indices] : path_groups) {
575
12.0k
        if (indices.size() <= 1) {
576
3.05k
            continue; // No conflicts possible
577
3.05k
        }
578
579
        // Compare all pairs within this group
580
27.0k
        for (size_t i = 0; i < indices.size(); ++i) {
581
27.0k
            for (size_t j = 0; j < i; ++j) {
582
9.01k
                if (has_different_structure_in_same_path(tuple_paths[indices[i]].get_parts(),
583
9.01k
                                                         tuple_paths[indices[j]].get_parts())) {
584
5
                    return Status::DataQualityError(
585
5
                            "Ambiguous paths: {} vs {} with different nested part {} vs {}",
586
5
                            tuple_paths[indices[i]].get_path(), tuple_paths[indices[j]].get_path(),
587
5
                            tuple_paths[indices[i]].has_nested_part(),
588
5
                            tuple_paths[indices[j]].has_nested_part());
589
5
                }
590
9.01k
            }
591
18.0k
        }
592
9.01k
    }
593
3.05k
    return Status::OK();
594
3.05k
}
595
596
Status update_least_schema_internal(const std::map<PathInData, DataTypes>& subcolumns_types,
597
                                    TabletSchemaSPtr& common_schema, int32_t variant_col_unique_id,
598
                                    const std::map<std::string, TabletColumnPtr>& typed_columns,
599
43
                                    std::set<PathInData>* path_set) {
600
43
    PathsInData tuple_paths;
601
43
    DataTypes tuple_types;
602
43
    CHECK(common_schema.use_count() == 1);
603
    // Get the least common type for all paths.
604
56
    for (const auto& [key, subtypes] : subcolumns_types) {
605
56
        assert(!subtypes.empty());
606
56
        if (key.get_path() == ColumnVariant::COLUMN_NAME_DUMMY) {
607
0
            continue;
608
0
        }
609
56
        size_t first_dim = get_number_of_dimensions(*subtypes[0]);
610
56
        tuple_paths.emplace_back(key);
611
76
        for (size_t i = 1; i < subtypes.size(); ++i) {
612
21
            if (first_dim != get_number_of_dimensions(*subtypes[i])) {
613
1
                tuple_types.emplace_back(make_nullable(std::make_shared<DataTypeJsonb>()));
614
1
                LOG(INFO) << fmt::format(
615
1
                        "Uncompatible types of subcolumn '{}': {} and {}, cast to JSONB",
616
1
                        key.get_path(), subtypes[0]->get_name(), subtypes[i]->get_name());
617
1
                break;
618
1
            }
619
21
        }
620
56
        if (tuple_paths.size() == tuple_types.size()) {
621
1
            continue;
622
1
        }
623
55
        DataTypePtr common_type;
624
55
        get_least_supertype_jsonb(subtypes, &common_type);
625
55
        if (!common_type->is_nullable()) {
626
3
            common_type = make_nullable(common_type);
627
3
        }
628
55
        tuple_types.emplace_back(common_type);
629
55
    }
630
43
    CHECK_EQ(tuple_paths.size(), tuple_types.size());
631
632
    // Append all common type columns of this variant
633
99
    for (int i = 0; i < tuple_paths.size(); ++i) {
634
56
        TabletColumn common_column;
635
        // typed path not contains root part
636
56
        auto path_without_root = tuple_paths[i].copy_pop_front().get_path();
637
56
        if (typed_columns.contains(path_without_root) && !tuple_paths[i].has_nested_part()) {
638
17
            common_column = *typed_columns.at(path_without_root);
639
            // parent unique id and path may not be init in write path
640
17
            common_column.set_parent_unique_id(variant_col_unique_id);
641
17
            common_column.set_path_info(tuple_paths[i]);
642
17
            common_column.set_name(tuple_paths[i].get_path());
643
39
        } else {
644
            // const std::string& column_name = variant_col_name + "." + tuple_paths[i].get_path();
645
39
            get_column_by_type(tuple_types[i], tuple_paths[i].get_path(), common_column,
646
39
                               ExtraInfo {.unique_id = -1,
647
39
                                          .parent_unique_id = variant_col_unique_id,
648
39
                                          .path_info = tuple_paths[i]});
649
39
        }
650
56
        common_schema->append_column(common_column);
651
56
        if (path_set != nullptr) {
652
53
            path_set->insert(tuple_paths[i]);
653
53
        }
654
56
    }
655
43
    return Status::OK();
656
43
}
657
658
Status update_least_common_schema(const std::vector<TabletSchemaSPtr>& schemas,
659
                                  TabletSchemaSPtr& common_schema, int32_t variant_col_unique_id,
660
42
                                  std::set<PathInData>* path_set) {
661
42
    std::map<std::string, TabletColumnPtr> typed_columns;
662
42
    for (const TabletColumnPtr& col :
663
48
         common_schema->column_by_uid(variant_col_unique_id).get_sub_columns()) {
664
48
        typed_columns[col->name()] = col;
665
48
    }
666
    // Types of subcolumns by path from all tuples.
667
42
    std::map<PathInData, DataTypes> subcolumns_types;
668
669
    // Collect all paths first to enable batch checking
670
42
    std::vector<PathInData> all_paths;
671
672
60
    for (const TabletSchemaSPtr& schema : schemas) {
673
178
        for (const TabletColumnPtr& col : schema->columns()) {
674
            // Get subcolumns of this variant
675
178
            if (col->has_path_info() && col->parent_unique_id() >= 0 &&
676
178
                col->parent_unique_id() == variant_col_unique_id) {
677
72
                subcolumns_types[*col->path_info_ptr()].emplace_back(
678
72
                        DataTypeFactory::instance().create_data_type(*col, col->is_nullable()));
679
72
                all_paths.push_back(*col->path_info_ptr());
680
72
            }
681
178
        }
682
60
    }
683
684
    // Batch check for conflicts
685
42
    RETURN_IF_ERROR(check_variant_has_no_ambiguous_paths(all_paths));
686
687
42
    return update_least_schema_internal(subcolumns_types, common_schema, variant_col_unique_id,
688
42
                                        typed_columns, path_set);
689
42
}
690
691
// Keep variant subcolumn BF support aligned with FE DDL checks.
692
1.23k
bool is_bf_supported_by_fe_for_variant_subcolumn(FieldType type) {
693
1.23k
    switch (type) {
694
0
    case FieldType::OLAP_FIELD_TYPE_SMALLINT:
695
53
    case FieldType::OLAP_FIELD_TYPE_INT:
696
699
    case FieldType::OLAP_FIELD_TYPE_BIGINT:
697
699
    case FieldType::OLAP_FIELD_TYPE_LARGEINT:
698
699
    case FieldType::OLAP_FIELD_TYPE_CHAR:
699
699
    case FieldType::OLAP_FIELD_TYPE_VARCHAR:
700
1.17k
    case FieldType::OLAP_FIELD_TYPE_STRING:
701
1.17k
    case FieldType::OLAP_FIELD_TYPE_DATE:
702
1.17k
    case FieldType::OLAP_FIELD_TYPE_DATETIME:
703
1.18k
    case FieldType::OLAP_FIELD_TYPE_DATEV2:
704
1.19k
    case FieldType::OLAP_FIELD_TYPE_DATETIMEV2:
705
1.19k
    case FieldType::OLAP_FIELD_TYPE_TIMESTAMPTZ:
706
1.19k
    case FieldType::OLAP_FIELD_TYPE_DECIMAL:
707
1.19k
    case FieldType::OLAP_FIELD_TYPE_DECIMAL32:
708
1.19k
    case FieldType::OLAP_FIELD_TYPE_DECIMAL64:
709
1.19k
    case FieldType::OLAP_FIELD_TYPE_DECIMAL128I:
710
1.19k
    case FieldType::OLAP_FIELD_TYPE_DECIMAL256:
711
1.19k
    case FieldType::OLAP_FIELD_TYPE_IPV4:
712
1.19k
    case FieldType::OLAP_FIELD_TYPE_IPV6:
713
1.19k
        return true;
714
41
    default:
715
41
        return false;
716
1.23k
    }
717
1.23k
}
718
719
void inherit_column_attributes(const TabletColumn& source, TabletColumn& target,
720
1.23k
                               TabletSchemaSPtr* target_schema) {
721
1.23k
    if (!target.is_extracted_column()) {
722
0
        return;
723
0
    }
724
1.23k
    target.set_aggregation_method(source.aggregation());
725
726
    // 1. bloom filter
727
1.23k
    if (is_bf_supported_by_fe_for_variant_subcolumn(target.type())) {
728
1.19k
        target.set_is_bf_column(source.is_bf_column());
729
1.19k
    }
730
731
1.23k
    if (!target_schema) {
732
1.17k
        return;
733
1.17k
    }
734
735
    // 2. inverted index
736
57
    TabletIndexes indexes_to_add;
737
57
    auto source_indexes = (*target_schema)->inverted_indexs(source.unique_id());
738
    // if target is variant type, we need to inherit all indexes
739
    // because this schema is a read schema from fe
740
57
    if (target.is_variant_type()) {
741
0
        for (auto& index : source_indexes) {
742
0
            auto index_info = std::make_shared<TabletIndex>(*index);
743
0
            index_info->set_escaped_escaped_index_suffix_path(target.path_info_ptr()->get_path());
744
0
            indexes_to_add.emplace_back(std::move(index_info));
745
0
        }
746
57
    } else {
747
57
        inherit_index(source_indexes, indexes_to_add, target);
748
57
    }
749
57
    auto target_indexes = (*target_schema)
750
57
                                  ->inverted_indexs(target.parent_unique_id(),
751
57
                                                    target.path_info_ptr()->get_path());
752
57
    if (target_indexes.empty()) {
753
57
        for (auto& index_info : indexes_to_add) {
754
14
            (*target_schema)->append_index(std::move(*index_info));
755
14
        }
756
57
    }
757
758
    // 3. TODO: gnragm bf index
759
57
}
760
761
41
void inherit_column_attributes(TabletSchemaSPtr& schema) {
762
    // Add index meta if extracted column is missing index meta
763
177
    for (size_t i = 0; i < schema->num_columns(); ++i) {
764
136
        TabletColumn& col = schema->mutable_column(i);
765
136
        if (!col.is_extracted_column()) {
766
79
            continue;
767
79
        }
768
57
        if (schema->field_index(col.parent_unique_id()) == -1) {
769
            // parent column is missing, maybe dropped
770
0
            continue;
771
0
        }
772
57
        inherit_column_attributes(schema->column_by_uid(col.parent_unique_id()), col, &schema);
773
57
    }
774
41
}
775
776
Status get_least_common_schema(const std::vector<TabletSchemaSPtr>& schemas,
777
                               const TabletSchemaSPtr& base_schema, TabletSchemaSPtr& output_schema,
778
39
                               bool check_schema_size) {
779
39
    std::vector<int32_t> variant_column_unique_id;
780
    // Construct a schema excluding the extracted columns and gather unique identifiers for variants.
781
    // Ensure that the output schema also excludes these extracted columns. This approach prevents
782
    // duplicated paths following the update_least_common_schema process.
783
39
    auto build_schema_without_extracted_columns = [&](const TabletSchemaSPtr& base_schema) {
784
39
        output_schema = std::make_shared<TabletSchema>();
785
        // not copy columns but only shadow copy other attributes
786
39
        output_schema->shawdow_copy_without_columns(*base_schema);
787
        // Get all columns without extracted columns and collect variant col unique id
788
77
        for (const TabletColumnPtr& col : base_schema->columns()) {
789
77
            if (col->is_variant_type()) {
790
39
                variant_column_unique_id.push_back(col->unique_id());
791
39
            }
792
77
            if (!col->is_extracted_column()) {
793
74
                output_schema->append_column(*col);
794
74
            }
795
77
        }
796
39
    };
797
39
    if (base_schema == nullptr) {
798
        // Pick tablet schema with max schema version
799
4
        auto max_version_schema =
800
4
                *std::max_element(schemas.cbegin(), schemas.cend(),
801
4
                                  [](const TabletSchemaSPtr a, const TabletSchemaSPtr b) {
802
2
                                      return a->schema_version() < b->schema_version();
803
2
                                  });
804
4
        CHECK(max_version_schema);
805
4
        build_schema_without_extracted_columns(max_version_schema);
806
35
    } else {
807
        // use input base_schema schema as base schema
808
35
        build_schema_without_extracted_columns(base_schema);
809
35
    }
810
811
39
    for (int32_t unique_id : variant_column_unique_id) {
812
39
        std::set<PathInData> path_set;
813
39
        RETURN_IF_ERROR(update_least_common_schema(schemas, output_schema, unique_id, &path_set));
814
39
    }
815
816
39
    inherit_column_attributes(output_schema);
817
39
    if (check_schema_size &&
818
39
        output_schema->columns().size() > config::variant_max_merged_tablet_schema_size) {
819
0
        return Status::DataQualityError("Reached max column size limit {}",
820
0
                                        config::variant_max_merged_tablet_schema_size);
821
0
    }
822
823
39
    return Status::OK();
824
39
}
825
826
// sort by paths in lexicographical order
827
757
ColumnVariant::Subcolumns get_sorted_subcolumns(const ColumnVariant::Subcolumns& subcolumns) {
828
    // sort by paths in lexicographical order
829
757
    ColumnVariant::Subcolumns sorted = subcolumns;
830
23.2k
    std::sort(sorted.begin(), sorted.end(), [](const auto& lhsItem, const auto& rhsItem) {
831
23.2k
        return lhsItem->path < rhsItem->path;
832
23.2k
    });
833
757
    return sorted;
834
757
}
835
836
bool has_schema_index_diff(const TabletSchema* new_schema, const TabletSchema* old_schema,
837
4
                           int32_t new_col_idx, int32_t old_col_idx) {
838
4
    const auto& column_new = new_schema->column(new_col_idx);
839
4
    const auto& column_old = old_schema->column(old_col_idx);
840
841
4
    if (column_new.is_bf_column() != column_old.is_bf_column()) {
842
2
        return true;
843
2
    }
844
845
2
    auto new_schema_inverted_indexs = new_schema->inverted_indexs(column_new);
846
2
    auto old_schema_inverted_indexs = old_schema->inverted_indexs(column_old);
847
848
2
    if (new_schema_inverted_indexs.size() != old_schema_inverted_indexs.size()) {
849
1
        return true;
850
1
    }
851
852
2
    for (size_t i = 0; i < new_schema_inverted_indexs.size(); ++i) {
853
1
        if (!new_schema_inverted_indexs[i]->is_same_except_id(old_schema_inverted_indexs[i])) {
854
0
            return true;
855
0
        }
856
1
    }
857
858
1
    return false;
859
1
}
860
861
782
TabletColumn create_sparse_column(const TabletColumn& variant) {
862
782
    TabletColumn res;
863
782
    res.set_name(variant.name_lower_case() + "." + SPARSE_COLUMN_PATH);
864
782
    res.set_type(FieldType::OLAP_FIELD_TYPE_MAP);
865
782
    res.set_aggregation_method(variant.aggregation());
866
782
    res.set_path_info(PathInData {variant.name_lower_case() + "." + SPARSE_COLUMN_PATH});
867
782
    res.set_parent_unique_id(variant.unique_id());
868
    // set default value to "NULL" DefaultColumnIterator will call insert_many_defaults
869
782
    res.set_default_value("NULL");
870
782
    TabletColumn child_tcolumn;
871
782
    child_tcolumn.set_type(FieldType::OLAP_FIELD_TYPE_STRING);
872
782
    res.add_sub_column(child_tcolumn);
873
782
    res.add_sub_column(child_tcolumn);
874
782
    return res;
875
782
}
876
877
63
TabletColumn create_sparse_shard_column(const TabletColumn& variant, int bucket_index) {
878
63
    TabletColumn res;
879
63
    std::string name = variant.name_lower_case() + "." + SPARSE_COLUMN_PATH + ".b" +
880
63
                       std::to_string(bucket_index);
881
63
    res.set_name(name);
882
63
    res.set_type(FieldType::OLAP_FIELD_TYPE_MAP);
883
63
    res.set_aggregation_method(variant.aggregation());
884
63
    res.set_parent_unique_id(variant.unique_id());
885
63
    res.set_default_value("NULL");
886
63
    PathInData path(name);
887
63
    res.set_path_info(path);
888
63
    TabletColumn child_tcolumn;
889
63
    child_tcolumn.set_type(FieldType::OLAP_FIELD_TYPE_STRING);
890
63
    res.add_sub_column(child_tcolumn);
891
63
    res.add_sub_column(child_tcolumn);
892
63
    return res;
893
63
}
894
895
44
TabletColumn create_doc_value_column(const TabletColumn& variant, int bucket_index) {
896
44
    TabletColumn res;
897
44
    std::string name = variant.name_lower_case() + "." + DOC_VALUE_COLUMN_PATH + ".b" +
898
44
                       std::to_string(bucket_index);
899
44
    res.set_name(name);
900
44
    res.set_type(FieldType::OLAP_FIELD_TYPE_MAP);
901
44
    res.set_aggregation_method(variant.aggregation());
902
44
    res.set_parent_unique_id(variant.unique_id());
903
44
    res.set_default_value("NULL");
904
44
    res.set_path_info(PathInData {name});
905
906
44
    TabletColumn child_tcolumn;
907
44
    child_tcolumn.set_type(FieldType::OLAP_FIELD_TYPE_STRING);
908
44
    res.add_sub_column(child_tcolumn);
909
44
    res.add_sub_column(child_tcolumn);
910
44
    return res;
911
44
}
912
913
5.41k
uint32_t variant_binary_shard_of(const StringRef& path, uint32_t bucket_num) {
914
5.41k
    if (bucket_num <= 1) return 0;
915
5.41k
    SipHash hash;
916
5.41k
    hash.update(path.data, path.size);
917
5.41k
    uint64_t h = hash.get64();
918
5.41k
    return static_cast<uint32_t>(h % bucket_num);
919
5.41k
}
920
921
Status VariantCompactionUtil::aggregate_path_to_stats(
922
        const RowsetSharedPtr& rs,
923
97
        std::unordered_map<int32_t, PathToNoneNullValues>* uid_to_path_stats) {
924
97
    SegmentCacheHandle segment_cache;
925
97
    RETURN_IF_ERROR(SegmentLoader::instance()->load_segments(
926
97
            std::static_pointer_cast<BetaRowset>(rs), &segment_cache));
927
928
314
    for (const auto& column : rs->tablet_schema()->columns()) {
929
314
        if (!column->is_variant_type() || column->unique_id() < 0) {
930
192
            continue;
931
192
        }
932
122
        if (!should_check_variant_path_stats(*column)) {
933
0
            continue;
934
0
        }
935
267
        for (const auto& segment : segment_cache.get_segments()) {
936
267
            std::shared_ptr<ColumnReader> column_reader;
937
267
            OlapReaderStatistics stats;
938
267
            RETURN_IF_ERROR(
939
267
                    segment->get_column_reader(column->unique_id(), &column_reader, &stats));
940
267
            if (!column_reader) {
941
0
                continue;
942
0
            }
943
944
267
            CHECK(column_reader->get_meta_type() == FieldType::OLAP_FIELD_TYPE_VARIANT);
945
267
            auto* variant_column_reader =
946
267
                    assert_cast<segment_v2::VariantColumnReader*>(column_reader.get());
947
            // load external meta before getting stats
948
267
            RETURN_IF_ERROR(variant_column_reader->load_external_meta_once());
949
267
            const auto* source_stats = variant_column_reader->get_stats();
950
267
            CHECK(source_stats);
951
952
            // agg path -> stats
953
1.31k
            for (const auto& [path, size] : source_stats->sparse_column_non_null_size) {
954
1.31k
                (*uid_to_path_stats)[column->unique_id()][path] += size;
955
1.31k
            }
956
957
588
            for (const auto& [path, size] : source_stats->subcolumns_non_null_size) {
958
588
                (*uid_to_path_stats)[column->unique_id()][path] += size;
959
588
            }
960
267
        }
961
122
    }
962
97
    return Status::OK();
963
97
}
964
965
Status VariantCompactionUtil::aggregate_variant_extended_info(
966
        const RowsetSharedPtr& rs,
967
64
        std::unordered_map<int32_t, VariantExtendedInfo>* uid_to_variant_extended_info) {
968
64
    SegmentCacheHandle segment_cache;
969
64
    RETURN_IF_ERROR(SegmentLoader::instance()->load_segments(
970
64
            std::static_pointer_cast<BetaRowset>(rs), &segment_cache));
971
972
150
    for (const auto& column : rs->tablet_schema()->columns()) {
973
150
        if (!column->is_variant_type()) {
974
72
            continue;
975
72
        }
976
78
        auto& extended_info = (*uid_to_variant_extended_info)[column->unique_id()];
977
78
        if (column->variant_enable_nested_group()) {
978
0
            extended_info.has_nested_group = true;
979
0
        }
980
125
        for (const auto& segment : segment_cache.get_segments()) {
981
125
            std::shared_ptr<ColumnReader> column_reader;
982
125
            OlapReaderStatistics stats;
983
125
            RETURN_IF_ERROR(
984
125
                    segment->get_column_reader(column->unique_id(), &column_reader, &stats));
985
124
            if (!column_reader) {
986
0
                continue;
987
0
            }
988
989
124
            CHECK(column_reader->get_meta_type() == FieldType::OLAP_FIELD_TYPE_VARIANT);
990
124
            auto* variant_column_reader =
991
124
                    assert_cast<segment_v2::VariantColumnReader*>(column_reader.get());
992
            // load external meta before getting stats
993
124
            RETURN_IF_ERROR(variant_column_reader->load_external_meta_once());
994
124
            const auto* source_stats = variant_column_reader->get_stats();
995
124
            CHECK(source_stats);
996
997
124
            if (!column->variant_enable_nested_group()) {
998
                // NG roots still need type metadata for regular subpaths such as `v.owner`,
999
                // but their compaction schema should not be driven by flat path stats.
1000
465
                for (const auto& [path, size] : source_stats->sparse_column_non_null_size) {
1001
465
                    extended_info.path_to_none_null_values[path] += size;
1002
465
                    extended_info.sparse_paths.emplace(path);
1003
465
                }
1004
1005
234
                for (const auto& [path, size] : source_stats->subcolumns_non_null_size) {
1006
234
                    extended_info.path_to_none_null_values[path] += size;
1007
234
                }
1008
124
            }
1009
1010
            //2. agg path -> schema
1011
124
            variant_column_reader->get_subcolumns_types(&extended_info.path_to_data_types);
1012
1013
            // 3. extract typed paths
1014
124
            variant_column_reader->get_typed_paths(&extended_info.typed_paths);
1015
1016
            // 4. extract nested paths
1017
124
            if (!column->variant_enable_nested_group()) {
1018
124
                variant_column_reader->get_nested_paths(&extended_info.nested_paths);
1019
124
            }
1020
124
        }
1021
78
    }
1022
63
    return Status::OK();
1023
64
}
1024
1025
// get the subpaths and sparse paths for the variant column
1026
void VariantCompactionUtil::get_subpaths(int32_t max_subcolumns_count,
1027
                                         const PathToNoneNullValues& stats,
1028
46
                                         TabletSchema::PathsSetInfo& paths_set_info) {
1029
    // max_subcolumns_count is 0 means no limit
1030
46
    if (max_subcolumns_count > 0 && stats.size() > max_subcolumns_count) {
1031
19
        std::vector<std::pair<size_t, std::string_view>> paths_with_sizes;
1032
19
        paths_with_sizes.reserve(stats.size());
1033
101
        for (const auto& [path, size] : stats) {
1034
101
            paths_with_sizes.emplace_back(size, path);
1035
101
        }
1036
19
        std::sort(paths_with_sizes.begin(), paths_with_sizes.end(), std::greater());
1037
1038
        // Select top N paths as subcolumns, remaining paths as sparse columns
1039
101
        for (const auto& [size, path] : paths_with_sizes) {
1040
101
            if (paths_set_info.sub_path_set.size() < max_subcolumns_count) {
1041
33
                paths_set_info.sub_path_set.emplace(path);
1042
68
            } else {
1043
68
                paths_set_info.sparse_path_set.emplace(path);
1044
68
            }
1045
101
        }
1046
19
        LOG(INFO) << "subpaths " << paths_set_info.sub_path_set.size() << " sparse paths "
1047
19
                  << paths_set_info.sparse_path_set.size() << " variant max subcolumns count "
1048
19
                  << max_subcolumns_count << " stats size " << paths_with_sizes.size();
1049
27
    } else {
1050
        // Apply all paths as subcolumns
1051
43
        for (const auto& [path, _] : stats) {
1052
43
            paths_set_info.sub_path_set.emplace(path);
1053
43
        }
1054
27
    }
1055
46
}
1056
1057
Status VariantCompactionUtil::check_path_stats(const std::vector<RowsetSharedPtr>& intputs,
1058
41
                                               RowsetSharedPtr output, BaseTabletSPtr tablet) {
1059
41
    if (output->tablet_schema()->num_variant_columns() == 0) {
1060
9
        return Status::OK();
1061
9
    }
1062
77
    for (const auto& rowset : intputs) {
1063
236
        for (const auto& column : rowset->tablet_schema()->columns()) {
1064
236
            if (column->is_variant_type() && !should_check_variant_path_stats(*column)) {
1065
0
                return Status::OK();
1066
0
            }
1067
236
        }
1068
77
    }
1069
    // check no extended schema in input rowsets
1070
77
    for (const auto& rowset : intputs) {
1071
236
        for (const auto& column : rowset->tablet_schema()->columns()) {
1072
236
            if (column->is_extracted_column()) {
1073
0
                return Status::OK();
1074
0
            }
1075
236
        }
1076
77
    }
1077
#ifndef BE_TEST
1078
    // check no extended schema in output rowset
1079
    for (const auto& column : output->tablet_schema()->columns()) {
1080
        if (column->is_extracted_column()) {
1081
            const auto& name = column->name();
1082
            if (name.find("." + DOC_VALUE_COLUMN_PATH + ".") != std::string::npos ||
1083
                name.find("." + SPARSE_COLUMN_PATH + ".") != std::string::npos ||
1084
                name.ends_with("." + SPARSE_COLUMN_PATH)) {
1085
                continue;
1086
            }
1087
            return Status::InternalError("Unexpected extracted column {} in output rowset",
1088
                                         column->name());
1089
        }
1090
    }
1091
#endif
1092
    // only check path stats for dup_keys since the rows may be merged in other models
1093
32
    if (tablet->keys_type() != KeysType::DUP_KEYS) {
1094
2
        return Status::OK();
1095
2
    }
1096
    // if there is a delete predicate in the input rowsets, we skip the path stats check
1097
66
    for (auto& rowset : intputs) {
1098
66
        if (rowset->rowset_meta()->has_delete_predicate()) {
1099
0
            return Status::OK();
1100
0
        }
1101
66
    }
1102
128
    for (const auto& column : output->tablet_schema()->columns()) {
1103
128
        if (column->is_variant_type() && !should_check_variant_path_stats(*column)) {
1104
0
            return Status::OK();
1105
0
        }
1106
128
    }
1107
30
    std::unordered_map<int32_t, PathToNoneNullValues> original_uid_to_path_stats;
1108
66
    for (const auto& rs : intputs) {
1109
66
        RETURN_IF_ERROR(aggregate_path_to_stats(rs, &original_uid_to_path_stats));
1110
66
    }
1111
30
    std::unordered_map<int32_t, PathToNoneNullValues> output_uid_to_path_stats;
1112
30
    RETURN_IF_ERROR(aggregate_path_to_stats(output, &output_uid_to_path_stats));
1113
30
    for (const auto& [uid, stats] : output_uid_to_path_stats) {
1114
22
        if (output->tablet_schema()->column_by_uid(uid).is_variant_type() &&
1115
22
            output->tablet_schema()->column_by_uid(uid).variant_enable_doc_mode()) {
1116
0
            continue;
1117
0
        }
1118
22
        if (original_uid_to_path_stats.find(uid) == original_uid_to_path_stats.end()) {
1119
0
            return Status::InternalError("Path stats not found for uid {}, tablet_id {}", uid,
1120
0
                                         tablet->tablet_id());
1121
0
        }
1122
1123
        // In input rowsets, some rowsets may have statistics values exceeding the maximum limit,
1124
        // which leads to inaccurate statistics
1125
22
        if (stats.size() > output->tablet_schema()
1126
22
                                   ->column_by_uid(uid)
1127
22
                                   .variant_max_sparse_column_statistics_size()) {
1128
            // When there is only one segment, we can ensure that the size of each path in output stats is accurate
1129
5
            if (output->num_segments() == 1) {
1130
15
                for (const auto& [path, size] : stats) {
1131
15
                    if (original_uid_to_path_stats.at(uid).find(path) ==
1132
15
                        original_uid_to_path_stats.at(uid).end()) {
1133
0
                        continue;
1134
0
                    }
1135
15
                    if (original_uid_to_path_stats.at(uid).at(path) > size) {
1136
0
                        return Status::InternalError(
1137
0
                                "Path stats not smaller for uid {} with path `{}`, input size {}, "
1138
0
                                "output "
1139
0
                                "size {}, "
1140
0
                                "tablet_id {}",
1141
0
                                uid, path, original_uid_to_path_stats.at(uid).at(path), size,
1142
0
                                tablet->tablet_id());
1143
0
                    }
1144
15
                }
1145
5
            }
1146
5
        }
1147
        // in this case, input stats is accurate, so we check the stats size and stats value
1148
17
        else {
1149
75
            for (const auto& [path, size] : stats) {
1150
75
                if (original_uid_to_path_stats.at(uid).find(path) ==
1151
75
                    original_uid_to_path_stats.at(uid).end()) {
1152
0
                    return Status::InternalError(
1153
0
                            "Path stats not found for uid {}, path {}, tablet_id {}", uid, path,
1154
0
                            tablet->tablet_id());
1155
0
                }
1156
75
                if (original_uid_to_path_stats.at(uid).at(path) != size) {
1157
1
                    return Status::InternalError(
1158
1
                            "Path stats not match for uid {} with path `{}`, input size {}, output "
1159
1
                            "size {}, "
1160
1
                            "tablet_id {}",
1161
1
                            uid, path, original_uid_to_path_stats.at(uid).at(path), size,
1162
1
                            tablet->tablet_id());
1163
1
                }
1164
75
            }
1165
17
        }
1166
22
    }
1167
1168
29
    return Status::OK();
1169
30
}
1170
1171
Status VariantCompactionUtil::get_compaction_typed_columns(
1172
        const TabletSchemaSPtr& target, const std::unordered_set<std::string>& typed_paths,
1173
        const TabletColumnPtr parent_column, TabletSchemaSPtr& output_schema,
1174
35
        TabletSchema::PathsSetInfo& paths_set_info) {
1175
35
    if (parent_column->variant_enable_typed_paths_to_sparse()) {
1176
0
        return Status::OK();
1177
0
    }
1178
35
    for (const auto& path : typed_paths) {
1179
20
        TabletSchema::SubColumnInfo sub_column_info;
1180
20
        if (generate_sub_column_info(*target, parent_column->unique_id(), path, &sub_column_info)) {
1181
19
            inherit_column_attributes(*parent_column, sub_column_info.column);
1182
19
            output_schema->append_column(sub_column_info.column);
1183
19
            paths_set_info.typed_path_set.insert({path, std::move(sub_column_info)});
1184
19
            VLOG_DEBUG << "append typed column " << path;
1185
19
        } else {
1186
1
            return Status::InternalError("Failed to generate sub column info for path {}", path);
1187
1
        }
1188
20
    }
1189
34
    return Status::OK();
1190
35
}
1191
1192
Status VariantCompactionUtil::get_compaction_nested_columns(
1193
        const std::unordered_set<PathInData, PathInData::Hash>& nested_paths,
1194
        const PathToDataTypes& path_to_data_types, const TabletColumnPtr parent_column,
1195
34
        TabletSchemaSPtr& output_schema, TabletSchema::PathsSetInfo& paths_set_info) {
1196
34
    const auto& parent_indexes = output_schema->inverted_indexs(parent_column->unique_id());
1197
34
    for (const auto& path : nested_paths) {
1198
3
        const auto& find_data_types = path_to_data_types.find(path);
1199
3
        if (find_data_types == path_to_data_types.end() || find_data_types->second.empty()) {
1200
1
            return Status::InternalError("Nested path {} has no data type", path.get_path());
1201
1
        }
1202
2
        DataTypePtr data_type;
1203
2
        get_least_supertype_jsonb(find_data_types->second, &data_type);
1204
1205
2
        const std::string& column_name = parent_column->name_lower_case() + "." + path.get_path();
1206
2
        PathInDataBuilder full_path_builder;
1207
2
        auto full_path = full_path_builder.append(parent_column->name_lower_case(), false)
1208
2
                                 .append(path.get_parts(), false)
1209
2
                                 .build();
1210
2
        TabletColumn nested_column =
1211
2
                get_column_by_type(data_type, column_name,
1212
2
                                   ExtraInfo {.unique_id = -1,
1213
2
                                              .parent_unique_id = parent_column->unique_id(),
1214
2
                                              .path_info = full_path});
1215
2
        inherit_column_attributes(*parent_column, nested_column);
1216
2
        TabletIndexes sub_column_indexes;
1217
2
        inherit_index(parent_indexes, sub_column_indexes, nested_column);
1218
2
        paths_set_info.subcolumn_indexes.emplace(path.get_path(), std::move(sub_column_indexes));
1219
2
        output_schema->append_column(nested_column);
1220
2
        VLOG_DEBUG << "append nested column " << path.get_path();
1221
2
    }
1222
33
    return Status::OK();
1223
34
}
1224
1225
void VariantCompactionUtil::get_compaction_subcolumns_from_subpaths(
1226
        TabletSchema::PathsSetInfo& paths_set_info, const TabletColumnPtr parent_column,
1227
        const TabletSchemaSPtr& target, const PathToDataTypes& path_to_data_types,
1228
38
        const std::unordered_set<std::string>& sparse_paths, TabletSchemaSPtr& output_schema) {
1229
38
    auto& path_set = paths_set_info.sub_path_set;
1230
38
    std::vector<StringRef> sorted_subpaths(path_set.begin(), path_set.end());
1231
38
    std::sort(sorted_subpaths.begin(), sorted_subpaths.end());
1232
38
    const auto& parent_indexes = target->inverted_indexs(parent_column->unique_id());
1233
    // append subcolumns
1234
66
    for (const auto& subpath : sorted_subpaths) {
1235
66
        auto column_name = parent_column->name_lower_case() + "." + subpath.to_string();
1236
66
        auto column_path = make_full_subcolumn_path(parent_column,
1237
66
                                                    std::string_view(subpath.data, subpath.size));
1238
1239
66
        const auto& find_data_types = path_to_data_types.find(PathInData(subpath));
1240
1241
        // some cases: the subcolumn type is variant
1242
        // 1. this path has no data type in segments
1243
        // 2. this path is in sparse paths
1244
        // 3. the sparse paths are too much
1245
66
        TabletSchema::SubColumnInfo sub_column_info;
1246
66
        if (parent_column->variant_enable_typed_paths_to_sparse() &&
1247
66
            generate_sub_column_info(*target, parent_column->unique_id(), std::string(subpath),
1248
16
                                     &sub_column_info)) {
1249
8
            inherit_column_attributes(*parent_column, sub_column_info.column);
1250
8
            output_schema->append_column(sub_column_info.column);
1251
8
            paths_set_info.subcolumn_indexes.emplace(subpath, std::move(sub_column_info.indexes));
1252
8
            VLOG_DEBUG << "append typed column " << subpath;
1253
58
        } else if (find_data_types == path_to_data_types.end() || find_data_types->second.empty() ||
1254
58
                   sparse_paths.find(std::string(subpath)) != sparse_paths.end() ||
1255
58
                   sparse_paths.size() >=
1256
42
                           parent_column->variant_max_sparse_column_statistics_size()) {
1257
23
            TabletColumn subcolumn;
1258
23
            subcolumn.set_name(column_name);
1259
23
            subcolumn.set_type(FieldType::OLAP_FIELD_TYPE_VARIANT);
1260
23
            subcolumn.set_parent_unique_id(parent_column->unique_id());
1261
23
            subcolumn.set_path_info(column_path);
1262
23
            subcolumn.set_aggregation_method(parent_column->aggregation());
1263
23
            subcolumn.set_variant_max_subcolumns_count(
1264
23
                    parent_column->variant_max_subcolumns_count());
1265
23
            subcolumn.set_variant_enable_doc_mode(parent_column->variant_enable_doc_mode());
1266
23
            subcolumn.set_is_nullable(true);
1267
23
            output_schema->append_column(subcolumn);
1268
23
            VLOG_DEBUG << "append sub column " << subpath << " data type "
1269
0
                       << "VARIANT";
1270
23
        }
1271
        // normal case: the subcolumn type can be calculated from the data types in segments
1272
35
        else {
1273
35
            DataTypePtr data_type;
1274
35
            get_least_supertype_jsonb(find_data_types->second, &data_type);
1275
35
            TabletColumn sub_column =
1276
35
                    get_column_by_type(data_type, column_name,
1277
35
                                       ExtraInfo {.unique_id = -1,
1278
35
                                                  .parent_unique_id = parent_column->unique_id(),
1279
35
                                                  .path_info = column_path});
1280
35
            inherit_column_attributes(*parent_column, sub_column);
1281
35
            TabletIndexes sub_column_indexes;
1282
35
            inherit_index(parent_indexes, sub_column_indexes, sub_column);
1283
35
            paths_set_info.subcolumn_indexes.emplace(subpath, std::move(sub_column_indexes));
1284
35
            output_schema->append_column(sub_column);
1285
35
            VLOG_DEBUG << "append sub column " << subpath << " data type " << data_type->get_name();
1286
35
        }
1287
66
    }
1288
38
}
1289
1290
void VariantCompactionUtil::get_compaction_subcolumns_from_data_types(
1291
        TabletSchema::PathsSetInfo& paths_set_info, const TabletColumnPtr parent_column,
1292
        const TabletSchemaSPtr& target, const PathToDataTypes& path_to_data_types,
1293
6
        TabletSchemaSPtr& output_schema) {
1294
6
    const auto& parent_indexes = target->inverted_indexs(parent_column->unique_id());
1295
12
    for (const auto& [path, data_types] : path_to_data_types) {
1296
        // Typed paths are materialized by get_compaction_typed_columns(); this helper only
1297
        // materializes regular subcolumns inferred from rowset data types.
1298
12
        if (data_types.empty() || path.empty() || path.get_is_typed() || path.has_nested_part()) {
1299
5
            continue;
1300
5
        }
1301
7
        DataTypePtr data_type;
1302
7
        get_least_supertype_jsonb(data_types, &data_type);
1303
7
        auto column_name = parent_column->name_lower_case() + "." + path.get_path();
1304
7
        auto column_path = make_full_subcolumn_path(parent_column, path.get_path());
1305
7
        TabletColumn sub_column =
1306
7
                get_column_by_type(data_type, column_name,
1307
7
                                   ExtraInfo {.unique_id = -1,
1308
7
                                              .parent_unique_id = parent_column->unique_id(),
1309
7
                                              .path_info = column_path});
1310
7
        inherit_column_attributes(*parent_column, sub_column);
1311
7
        TabletIndexes sub_column_indexes;
1312
7
        inherit_index(parent_indexes, sub_column_indexes, sub_column);
1313
7
        paths_set_info.sub_path_set.emplace(path.get_path());
1314
7
        paths_set_info.subcolumn_indexes.emplace(path.get_path(), std::move(sub_column_indexes));
1315
7
        output_schema->append_column(sub_column);
1316
7
        VLOG_DEBUG << "append sub column " << path.get_path() << " data type "
1317
0
                   << data_type->get_name();
1318
7
    }
1319
    // The data-type map can contain the variant root as PathInData(), while an empty JSON key
1320
    // only appears in path stats as "". If stats selected it as a materialized path, append it
1321
    // with an explicit empty path part so it does not collide with root.
1322
6
    append_empty_key_subcolumn_from_stats(paths_set_info, parent_column, output_schema);
1323
6
}
1324
1325
// Build the temporary schema for compaction.
1326
// NestedGroup roots are special: the root VARIANT column owns the NG tree and the streaming NG
1327
// writer handles NG children, while regular non-NG paths beside the arrays are materialized as
1328
// ordinary extracted subcolumns. NG typed paths still use get_compaction_typed_columns(), keeping
1329
// typed-column rules out of the NG-specific regular-path filtering.
1330
Status VariantCompactionUtil::get_extended_compaction_schema(
1331
67
        const std::vector<RowsetSharedPtr>& rowsets, TabletSchemaSPtr& target) {
1332
67
    std::unordered_map<int32_t, VariantExtendedInfo> uid_to_variant_extended_info;
1333
67
    const bool needs_variant_extended_info =
1334
872
            std::ranges::any_of(target->columns(), [](const TabletColumnPtr& column) {
1335
872
                return column->is_variant_type() && (should_check_variant_path_stats(*column) ||
1336
30
                                                     column->variant_enable_nested_group());
1337
872
            });
1338
67
    if (needs_variant_extended_info) {
1339
        // collect path stats from all rowsets and segments
1340
59
        for (const auto& rs : rowsets) {
1341
59
            RETURN_IF_ERROR(aggregate_variant_extended_info(rs, &uid_to_variant_extended_info));
1342
59
        }
1343
30
    }
1344
1345
    // build the output schema
1346
67
    TabletSchemaSPtr output_schema = std::make_shared<TabletSchema>();
1347
67
    output_schema->shawdow_copy_without_columns(*target);
1348
67
    std::unordered_map<int32_t, TabletSchema::PathsSetInfo> uid_to_paths_set_info;
1349
67
    const auto ng_root_uids =
1350
67
            collect_nested_group_compaction_root_uids(target, uid_to_variant_extended_info);
1351
881
    for (const TabletColumnPtr& column : target->columns()) {
1352
881
        if (!column->is_extracted_column()) {
1353
880
            output_schema->append_column(*column);
1354
880
        }
1355
881
        if (!column->is_variant_type()) {
1356
847
            continue;
1357
847
        }
1358
34
        VLOG_DEBUG << "column " << column->name() << " unique id " << column->unique_id();
1359
1360
34
        const auto info_it = uid_to_variant_extended_info.find(column->unique_id());
1361
34
        const VariantExtendedInfo empty_extended_info;
1362
34
        const VariantExtendedInfo& extended_info = info_it == uid_to_variant_extended_info.end()
1363
34
                                                           ? empty_extended_info
1364
34
                                                           : info_it->second;
1365
34
        auto& paths_set_info = uid_to_paths_set_info[column->unique_id()];
1366
34
        const bool use_nested_group_compaction_schema = ng_root_uids.contains(column->unique_id());
1367
1368
34
        if (use_nested_group_compaction_schema) {
1369
            // 1. append typed columns. Keep this shared with the non-NG typed helper; only the
1370
            // regular-path selection below is NG-specific.
1371
1
            RETURN_IF_ERROR(get_compaction_typed_columns(target, extended_info.typed_paths, column,
1372
1
                                                         output_schema, paths_set_info));
1373
1374
            // NG roots do not record path-count stats for ordinary Variant paths, so their regular
1375
            // non-NG subcolumns use the same data-types materialization helper as the
1376
            // all-materialized non-NG branch below.
1377
1
            auto regular_path_to_data_types =
1378
1
                    collect_regular_types_outside_nested_group(extended_info);
1379
1
            get_compaction_subcolumns_from_data_types(paths_set_info, column, target,
1380
1
                                                      regular_path_to_data_types, output_schema);
1381
1
            LOG(INFO) << "Variant column uid=" << column->unique_id()
1382
1
                      << " keeps nested-group root and materializes regular non-NG subcolumns in "
1383
1
                         "compaction schema";
1384
1
            continue;
1385
1
        }
1386
1387
33
        if (column->variant_enable_doc_mode()) {
1388
1
            const int bucket_num = std::max(1, column->variant_doc_hash_shard_count());
1389
3
            for (int b = 0; b < bucket_num; ++b) {
1390
2
                TabletColumn doc_value_bucket_column = create_doc_value_column(*column, b);
1391
2
                doc_value_bucket_column.set_type(FieldType::OLAP_FIELD_TYPE_VARIANT);
1392
2
                doc_value_bucket_column.set_is_nullable(false);
1393
2
                doc_value_bucket_column.set_variant_enable_doc_mode(true);
1394
2
                output_schema->append_column(doc_value_bucket_column);
1395
2
            }
1396
1
            continue;
1397
1
        }
1398
1399
        // 1. append typed columns
1400
32
        RETURN_IF_ERROR(get_compaction_typed_columns(target, extended_info.typed_paths, column,
1401
32
                                                     output_schema, paths_set_info));
1402
1403
        // 2. append nested columns
1404
32
        RETURN_IF_ERROR(get_compaction_nested_columns(extended_info.nested_paths,
1405
32
                                                      extended_info.path_to_data_types, column,
1406
32
                                                      output_schema, paths_set_info));
1407
1408
        // 3. get the subpaths
1409
32
        get_subpaths(column->variant_max_subcolumns_count(), extended_info.path_to_none_null_values,
1410
32
                     paths_set_info);
1411
1412
        // 4. append subcolumns
1413
32
        if (column->variant_max_subcolumns_count() > 0 || !column->get_sub_columns().empty()) {
1414
30
            get_compaction_subcolumns_from_subpaths(paths_set_info, column, target,
1415
30
                                                    extended_info.path_to_data_types,
1416
30
                                                    extended_info.sparse_paths, output_schema);
1417
30
        }
1418
        // variant_max_subcolumns_count == 0 and no typed paths materialized
1419
        // it means that all subcolumns are materialized, may be from old data
1420
2
        else {
1421
2
            get_compaction_subcolumns_from_data_types(paths_set_info, column, target,
1422
2
                                                      extended_info.path_to_data_types,
1423
2
                                                      output_schema);
1424
2
        }
1425
1426
        // append sparse column(s)
1427
        // If variant uses bucketized sparse columns, append one sparse bucket column per bucket.
1428
        // Otherwise, append the single sparse column.
1429
32
        int bucket_num = std::max(1, column->variant_sparse_hash_shard_count());
1430
32
        if (bucket_num > 1) {
1431
9
            for (int b = 0; b < bucket_num; ++b) {
1432
6
                TabletColumn sparse_bucket_column = create_sparse_shard_column(*column, b);
1433
6
                output_schema->append_column(sparse_bucket_column);
1434
6
            }
1435
29
        } else {
1436
29
            TabletColumn sparse_column = create_sparse_column(*column);
1437
29
            output_schema->append_column(sparse_column);
1438
29
        }
1439
32
    }
1440
1441
67
    target = output_schema;
1442
    // used to merge & filter path to sparse column during reading in compaction
1443
67
    target->set_path_set_info(std::move(uid_to_paths_set_info));
1444
67
    VLOG_DEBUG << "dump schema " << target->dump_full_schema();
1445
67
    return Status::OK();
1446
67
}
1447
1448
// Calculate statistics about variant data paths from the encoded sparse column
1449
void VariantCompactionUtil::calculate_variant_stats(const IColumn& encoded_sparse_column,
1450
                                                    segment_v2::VariantStatisticsPB* stats,
1451
                                                    size_t max_sparse_column_statistics_size,
1452
28
                                                    size_t row_pos, size_t num_rows) {
1453
    // Cast input column to ColumnMap type since sparse column is stored as a map
1454
28
    const auto& map_column = assert_cast<const ColumnMap&>(encoded_sparse_column);
1455
1456
    // Get the keys column which contains the paths as strings
1457
28
    const auto& sparse_data_paths =
1458
28
            assert_cast<const ColumnString*>(map_column.get_keys_ptr().get());
1459
28
    const auto& serialized_sparse_column_offsets = map_column.get_offsets();
1460
28
    auto& count_map = *stats->mutable_sparse_column_non_null_size();
1461
    // Iterate through all paths in the sparse column
1462
150
    for (size_t i = row_pos; i != row_pos + num_rows; ++i) {
1463
122
        size_t offset = serialized_sparse_column_offsets[i - 1];
1464
122
        size_t end = serialized_sparse_column_offsets[i];
1465
200
        for (size_t j = offset; j != end; ++j) {
1466
78
            auto path = sparse_data_paths->get_data_at(j);
1467
1468
78
            const auto& sparse_path = path.to_string();
1469
            // If path already exists in statistics, increment its count
1470
78
            if (auto it = count_map.find(sparse_path); it != count_map.end()) {
1471
29
                ++it->second;
1472
29
            }
1473
            // If path doesn't exist and we haven't hit the max statistics size limit,
1474
            // add it with count 1
1475
49
            else if (count_map.size() < max_sparse_column_statistics_size) {
1476
31
                count_map.emplace(sparse_path, 1);
1477
31
            }
1478
78
        }
1479
122
    }
1480
1481
28
    if (stats->sparse_column_non_null_size().size() > max_sparse_column_statistics_size) {
1482
0
        throw doris::Exception(
1483
0
                ErrorCode::INTERNAL_ERROR,
1484
0
                "Sparse column non null size: {} is greater than max statistics size: {}",
1485
0
                stats->sparse_column_non_null_size().size(), max_sparse_column_statistics_size);
1486
0
    }
1487
28
}
1488
1489
/// Calculates number of dimensions in array field.
1490
/// Returns 0 for scalar fields.
1491
class FieldVisitorToNumberOfDimensions : public StaticVisitor<size_t> {
1492
public:
1493
    FieldVisitorToNumberOfDimensions() = default;
1494
    template <PrimitiveType T>
1495
2.40M
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1496
2.40M
        if constexpr (T == TYPE_ARRAY) {
1497
128k
            const size_t size = x.size();
1498
128k
            size_t dimensions = 0;
1499
873k
            for (size_t i = 0; i < size; ++i) {
1500
745k
                size_t element_dimensions = apply_visitor(*this, x[i]);
1501
745k
                dimensions = std::max(dimensions, element_dimensions);
1502
745k
            }
1503
128k
            return 1 + dimensions;
1504
2.28M
        } else {
1505
2.28M
            return 0;
1506
2.28M
        }
1507
2.40M
    }
_ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE1EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1495
24.0k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1496
        if constexpr (T == TYPE_ARRAY) {
1497
            const size_t size = x.size();
1498
            size_t dimensions = 0;
1499
            for (size_t i = 0; i < size; ++i) {
1500
                size_t element_dimensions = apply_visitor(*this, x[i]);
1501
                dimensions = std::max(dimensions, element_dimensions);
1502
            }
1503
            return 1 + dimensions;
1504
24.0k
        } else {
1505
24.0k
            return 0;
1506
24.0k
        }
1507
24.0k
    }
Unexecuted instantiation: _ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE26EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE42EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE7EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1495
40.9k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1496
        if constexpr (T == TYPE_ARRAY) {
1497
            const size_t size = x.size();
1498
            size_t dimensions = 0;
1499
            for (size_t i = 0; i < size; ++i) {
1500
                size_t element_dimensions = apply_visitor(*this, x[i]);
1501
                dimensions = std::max(dimensions, element_dimensions);
1502
            }
1503
            return 1 + dimensions;
1504
40.9k
        } else {
1505
40.9k
            return 0;
1506
40.9k
        }
1507
40.9k
    }
Unexecuted instantiation: _ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE12EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE11EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE25EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE2EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1495
69.6k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1496
        if constexpr (T == TYPE_ARRAY) {
1497
            const size_t size = x.size();
1498
            size_t dimensions = 0;
1499
            for (size_t i = 0; i < size; ++i) {
1500
                size_t element_dimensions = apply_visitor(*this, x[i]);
1501
                dimensions = std::max(dimensions, element_dimensions);
1502
            }
1503
            return 1 + dimensions;
1504
69.6k
        } else {
1505
69.6k
            return 0;
1506
69.6k
        }
1507
69.6k
    }
_ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE3EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1495
6
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1496
        if constexpr (T == TYPE_ARRAY) {
1497
            const size_t size = x.size();
1498
            size_t dimensions = 0;
1499
            for (size_t i = 0; i < size; ++i) {
1500
                size_t element_dimensions = apply_visitor(*this, x[i]);
1501
                dimensions = std::max(dimensions, element_dimensions);
1502
            }
1503
            return 1 + dimensions;
1504
6
        } else {
1505
6
            return 0;
1506
6
        }
1507
6
    }
_ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE4EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1495
7
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1496
        if constexpr (T == TYPE_ARRAY) {
1497
            const size_t size = x.size();
1498
            size_t dimensions = 0;
1499
            for (size_t i = 0; i < size; ++i) {
1500
                size_t element_dimensions = apply_visitor(*this, x[i]);
1501
                dimensions = std::max(dimensions, element_dimensions);
1502
            }
1503
            return 1 + dimensions;
1504
7
        } else {
1505
7
            return 0;
1506
7
        }
1507
7
    }
_ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE5EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1495
1.20k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1496
        if constexpr (T == TYPE_ARRAY) {
1497
            const size_t size = x.size();
1498
            size_t dimensions = 0;
1499
            for (size_t i = 0; i < size; ++i) {
1500
                size_t element_dimensions = apply_visitor(*this, x[i]);
1501
                dimensions = std::max(dimensions, element_dimensions);
1502
            }
1503
            return 1 + dimensions;
1504
1.20k
        } else {
1505
1.20k
            return 0;
1506
1.20k
        }
1507
1.20k
    }
_ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE6EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1495
1.00M
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1496
        if constexpr (T == TYPE_ARRAY) {
1497
            const size_t size = x.size();
1498
            size_t dimensions = 0;
1499
            for (size_t i = 0; i < size; ++i) {
1500
                size_t element_dimensions = apply_visitor(*this, x[i]);
1501
                dimensions = std::max(dimensions, element_dimensions);
1502
            }
1503
            return 1 + dimensions;
1504
1.00M
        } else {
1505
1.00M
            return 0;
1506
1.00M
        }
1507
1.00M
    }
Unexecuted instantiation: _ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE38EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE39EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE8EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1495
1
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1496
        if constexpr (T == TYPE_ARRAY) {
1497
            const size_t size = x.size();
1498
            size_t dimensions = 0;
1499
            for (size_t i = 0; i < size; ++i) {
1500
                size_t element_dimensions = apply_visitor(*this, x[i]);
1501
                dimensions = std::max(dimensions, element_dimensions);
1502
            }
1503
            return 1 + dimensions;
1504
1
        } else {
1505
1
            return 0;
1506
1
        }
1507
1
    }
Unexecuted instantiation: _ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE27EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE9EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1495
164k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1496
        if constexpr (T == TYPE_ARRAY) {
1497
            const size_t size = x.size();
1498
            size_t dimensions = 0;
1499
            for (size_t i = 0; i < size; ++i) {
1500
                size_t element_dimensions = apply_visitor(*this, x[i]);
1501
                dimensions = std::max(dimensions, element_dimensions);
1502
            }
1503
            return 1 + dimensions;
1504
164k
        } else {
1505
164k
            return 0;
1506
164k
        }
1507
164k
    }
Unexecuted instantiation: _ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE36EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE37EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE23EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1495
976k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1496
        if constexpr (T == TYPE_ARRAY) {
1497
            const size_t size = x.size();
1498
            size_t dimensions = 0;
1499
            for (size_t i = 0; i < size; ++i) {
1500
                size_t element_dimensions = apply_visitor(*this, x[i]);
1501
                dimensions = std::max(dimensions, element_dimensions);
1502
            }
1503
            return 1 + dimensions;
1504
976k
        } else {
1505
976k
            return 0;
1506
976k
        }
1507
976k
    }
Unexecuted instantiation: _ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE15EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE10EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE41EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE17EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1495
128k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1496
128k
        if constexpr (T == TYPE_ARRAY) {
1497
128k
            const size_t size = x.size();
1498
128k
            size_t dimensions = 0;
1499
873k
            for (size_t i = 0; i < size; ++i) {
1500
745k
                size_t element_dimensions = apply_visitor(*this, x[i]);
1501
745k
                dimensions = std::max(dimensions, element_dimensions);
1502
745k
            }
1503
128k
            return 1 + dimensions;
1504
        } else {
1505
            return 0;
1506
        }
1507
128k
    }
_ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE16EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1495
1
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1496
        if constexpr (T == TYPE_ARRAY) {
1497
            const size_t size = x.size();
1498
            size_t dimensions = 0;
1499
            for (size_t i = 0; i < size; ++i) {
1500
                size_t element_dimensions = apply_visitor(*this, x[i]);
1501
                dimensions = std::max(dimensions, element_dimensions);
1502
            }
1503
            return 1 + dimensions;
1504
1
        } else {
1505
1
            return 0;
1506
1
        }
1507
1
    }
Unexecuted instantiation: _ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE18EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE32EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1495
1
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1496
        if constexpr (T == TYPE_ARRAY) {
1497
            const size_t size = x.size();
1498
            size_t dimensions = 0;
1499
            for (size_t i = 0; i < size; ++i) {
1500
                size_t element_dimensions = apply_visitor(*this, x[i]);
1501
                dimensions = std::max(dimensions, element_dimensions);
1502
            }
1503
            return 1 + dimensions;
1504
1
        } else {
1505
1
            return 0;
1506
1
        }
1507
1
    }
Unexecuted instantiation: _ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE28EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE29EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE20EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE30EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE35EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE22EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE19EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE24EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE31EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1495
31
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1496
        if constexpr (T == TYPE_ARRAY) {
1497
            const size_t size = x.size();
1498
            size_t dimensions = 0;
1499
            for (size_t i = 0; i < size; ++i) {
1500
                size_t element_dimensions = apply_visitor(*this, x[i]);
1501
                dimensions = std::max(dimensions, element_dimensions);
1502
            }
1503
            return 1 + dimensions;
1504
31
        } else {
1505
31
            return 0;
1506
31
        }
1507
31
    }
1508
};
1509
1510
// Visitor that allows to get type of scalar field
1511
// but exclude fields contain complex field.This is a faster version
1512
// for FieldVisitorToScalarType which does not support complex field.
1513
class SimpleFieldVisitorToScalarType : public StaticVisitor<size_t> {
1514
public:
1515
    template <PrimitiveType T>
1516
1.58M
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1517
1.58M
        if constexpr (T == TYPE_ARRAY) {
1518
0
            throw doris::Exception(ErrorCode::INVALID_ARGUMENT, "Array type is not supported");
1519
12.3k
        } else if constexpr (T == TYPE_NULL) {
1520
12.3k
            have_nulls = true;
1521
12.3k
            return 1;
1522
1.57M
        } else {
1523
1.57M
            type = T;
1524
1.57M
            return 1;
1525
1.57M
        }
1526
1.58M
    }
_ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE1EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1516
12.3k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1517
        if constexpr (T == TYPE_ARRAY) {
1518
            throw doris::Exception(ErrorCode::INVALID_ARGUMENT, "Array type is not supported");
1519
12.3k
        } else if constexpr (T == TYPE_NULL) {
1520
12.3k
            have_nulls = true;
1521
12.3k
            return 1;
1522
        } else {
1523
            type = T;
1524
            return 1;
1525
        }
1526
12.3k
    }
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE26EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE42EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE7EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1516
12.3k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1517
        if constexpr (T == TYPE_ARRAY) {
1518
            throw doris::Exception(ErrorCode::INVALID_ARGUMENT, "Array type is not supported");
1519
        } else if constexpr (T == TYPE_NULL) {
1520
            have_nulls = true;
1521
            return 1;
1522
12.3k
        } else {
1523
12.3k
            type = T;
1524
12.3k
            return 1;
1525
12.3k
        }
1526
12.3k
    }
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE12EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE11EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE25EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE2EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1516
12.4k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1517
        if constexpr (T == TYPE_ARRAY) {
1518
            throw doris::Exception(ErrorCode::INVALID_ARGUMENT, "Array type is not supported");
1519
        } else if constexpr (T == TYPE_NULL) {
1520
            have_nulls = true;
1521
            return 1;
1522
12.4k
        } else {
1523
12.4k
            type = T;
1524
12.4k
            return 1;
1525
12.4k
        }
1526
12.4k
    }
_ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE3EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1516
2
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1517
        if constexpr (T == TYPE_ARRAY) {
1518
            throw doris::Exception(ErrorCode::INVALID_ARGUMENT, "Array type is not supported");
1519
        } else if constexpr (T == TYPE_NULL) {
1520
            have_nulls = true;
1521
            return 1;
1522
2
        } else {
1523
2
            type = T;
1524
2
            return 1;
1525
2
        }
1526
2
    }
_ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE4EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1516
7
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1517
        if constexpr (T == TYPE_ARRAY) {
1518
            throw doris::Exception(ErrorCode::INVALID_ARGUMENT, "Array type is not supported");
1519
        } else if constexpr (T == TYPE_NULL) {
1520
            have_nulls = true;
1521
            return 1;
1522
7
        } else {
1523
7
            type = T;
1524
7
            return 1;
1525
7
        }
1526
7
    }
_ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE5EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1516
676
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1517
        if constexpr (T == TYPE_ARRAY) {
1518
            throw doris::Exception(ErrorCode::INVALID_ARGUMENT, "Array type is not supported");
1519
        } else if constexpr (T == TYPE_NULL) {
1520
            have_nulls = true;
1521
            return 1;
1522
676
        } else {
1523
676
            type = T;
1524
676
            return 1;
1525
676
        }
1526
676
    }
_ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE6EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1516
855k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1517
        if constexpr (T == TYPE_ARRAY) {
1518
            throw doris::Exception(ErrorCode::INVALID_ARGUMENT, "Array type is not supported");
1519
        } else if constexpr (T == TYPE_NULL) {
1520
            have_nulls = true;
1521
            return 1;
1522
855k
        } else {
1523
855k
            type = T;
1524
855k
            return 1;
1525
855k
        }
1526
855k
    }
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE38EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE39EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE8EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1516
1
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1517
        if constexpr (T == TYPE_ARRAY) {
1518
            throw doris::Exception(ErrorCode::INVALID_ARGUMENT, "Array type is not supported");
1519
        } else if constexpr (T == TYPE_NULL) {
1520
            have_nulls = true;
1521
            return 1;
1522
1
        } else {
1523
1
            type = T;
1524
1
            return 1;
1525
1
        }
1526
1
    }
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE27EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE9EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1516
12.7k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1517
        if constexpr (T == TYPE_ARRAY) {
1518
            throw doris::Exception(ErrorCode::INVALID_ARGUMENT, "Array type is not supported");
1519
        } else if constexpr (T == TYPE_NULL) {
1520
            have_nulls = true;
1521
            return 1;
1522
12.7k
        } else {
1523
12.7k
            type = T;
1524
12.7k
            return 1;
1525
12.7k
        }
1526
12.7k
    }
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE36EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE37EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE23EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1516
679k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1517
        if constexpr (T == TYPE_ARRAY) {
1518
            throw doris::Exception(ErrorCode::INVALID_ARGUMENT, "Array type is not supported");
1519
        } else if constexpr (T == TYPE_NULL) {
1520
            have_nulls = true;
1521
            return 1;
1522
679k
        } else {
1523
679k
            type = T;
1524
679k
            return 1;
1525
679k
        }
1526
679k
    }
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE15EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE10EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE41EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE17EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE16EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE18EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE32EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE28EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE29EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE20EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE30EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE35EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE22EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE19EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE24EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE31EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1516
5
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1517
        if constexpr (T == TYPE_ARRAY) {
1518
            throw doris::Exception(ErrorCode::INVALID_ARGUMENT, "Array type is not supported");
1519
        } else if constexpr (T == TYPE_NULL) {
1520
            have_nulls = true;
1521
            return 1;
1522
5
        } else {
1523
5
            type = T;
1524
5
            return 1;
1525
5
        }
1526
5
    }
1527
1.58M
    void get_scalar_type(PrimitiveType* data_type) const { *data_type = type; }
1528
1.58M
    bool contain_nulls() const { return have_nulls; }
1529
1530
1.58M
    bool need_convert_field() const { return false; }
1531
1532
private:
1533
    PrimitiveType type = PrimitiveType::INVALID_TYPE;
1534
    bool have_nulls = false;
1535
};
1536
1537
/// Visitor that allows to get type of scalar field
1538
/// or least common type of scalars in array.
1539
/// More optimized version of FieldToDataType.
1540
class FieldVisitorToScalarType : public StaticVisitor<size_t> {
1541
public:
1542
    template <PrimitiveType T>
1543
823k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1544
823k
        if constexpr (T == TYPE_ARRAY) {
1545
128k
            size_t size = x.size();
1546
873k
            for (size_t i = 0; i < size; ++i) {
1547
745k
                apply_visitor(*this, x[i]);
1548
745k
            }
1549
128k
            return 0;
1550
128k
        } else if constexpr (T == TYPE_NULL) {
1551
11.6k
            have_nulls = true;
1552
11.6k
            return 0;
1553
683k
        } else {
1554
683k
            field_types.insert(T);
1555
683k
            type_indexes.insert(T);
1556
683k
            return 0;
1557
683k
        }
1558
823k
    }
_ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE1EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1543
11.6k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1544
        if constexpr (T == TYPE_ARRAY) {
1545
            size_t size = x.size();
1546
            for (size_t i = 0; i < size; ++i) {
1547
                apply_visitor(*this, x[i]);
1548
            }
1549
            return 0;
1550
11.6k
        } else if constexpr (T == TYPE_NULL) {
1551
11.6k
            have_nulls = true;
1552
11.6k
            return 0;
1553
        } else {
1554
            field_types.insert(T);
1555
            type_indexes.insert(T);
1556
            return 0;
1557
        }
1558
11.6k
    }
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE26EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE42EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE7EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1543
28.6k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1544
        if constexpr (T == TYPE_ARRAY) {
1545
            size_t size = x.size();
1546
            for (size_t i = 0; i < size; ++i) {
1547
                apply_visitor(*this, x[i]);
1548
            }
1549
            return 0;
1550
        } else if constexpr (T == TYPE_NULL) {
1551
            have_nulls = true;
1552
            return 0;
1553
28.6k
        } else {
1554
28.6k
            field_types.insert(T);
1555
28.6k
            type_indexes.insert(T);
1556
28.6k
            return 0;
1557
28.6k
        }
1558
28.6k
    }
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE12EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE11EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE25EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE2EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1543
57.2k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1544
        if constexpr (T == TYPE_ARRAY) {
1545
            size_t size = x.size();
1546
            for (size_t i = 0; i < size; ++i) {
1547
                apply_visitor(*this, x[i]);
1548
            }
1549
            return 0;
1550
        } else if constexpr (T == TYPE_NULL) {
1551
            have_nulls = true;
1552
            return 0;
1553
57.2k
        } else {
1554
57.2k
            field_types.insert(T);
1555
57.2k
            type_indexes.insert(T);
1556
57.2k
            return 0;
1557
57.2k
        }
1558
57.2k
    }
_ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE3EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1543
4
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1544
        if constexpr (T == TYPE_ARRAY) {
1545
            size_t size = x.size();
1546
            for (size_t i = 0; i < size; ++i) {
1547
                apply_visitor(*this, x[i]);
1548
            }
1549
            return 0;
1550
        } else if constexpr (T == TYPE_NULL) {
1551
            have_nulls = true;
1552
            return 0;
1553
4
        } else {
1554
4
            field_types.insert(T);
1555
4
            type_indexes.insert(T);
1556
4
            return 0;
1557
4
        }
1558
4
    }
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE4EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE5EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1543
531
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1544
        if constexpr (T == TYPE_ARRAY) {
1545
            size_t size = x.size();
1546
            for (size_t i = 0; i < size; ++i) {
1547
                apply_visitor(*this, x[i]);
1548
            }
1549
            return 0;
1550
        } else if constexpr (T == TYPE_NULL) {
1551
            have_nulls = true;
1552
            return 0;
1553
531
        } else {
1554
531
            field_types.insert(T);
1555
531
            type_indexes.insert(T);
1556
531
            return 0;
1557
531
        }
1558
531
    }
_ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE6EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1543
147k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1544
        if constexpr (T == TYPE_ARRAY) {
1545
            size_t size = x.size();
1546
            for (size_t i = 0; i < size; ++i) {
1547
                apply_visitor(*this, x[i]);
1548
            }
1549
            return 0;
1550
        } else if constexpr (T == TYPE_NULL) {
1551
            have_nulls = true;
1552
            return 0;
1553
147k
        } else {
1554
147k
            field_types.insert(T);
1555
147k
            type_indexes.insert(T);
1556
147k
            return 0;
1557
147k
        }
1558
147k
    }
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE38EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE39EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE8EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE27EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE9EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1543
151k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1544
        if constexpr (T == TYPE_ARRAY) {
1545
            size_t size = x.size();
1546
            for (size_t i = 0; i < size; ++i) {
1547
                apply_visitor(*this, x[i]);
1548
            }
1549
            return 0;
1550
        } else if constexpr (T == TYPE_NULL) {
1551
            have_nulls = true;
1552
            return 0;
1553
151k
        } else {
1554
151k
            field_types.insert(T);
1555
151k
            type_indexes.insert(T);
1556
151k
            return 0;
1557
151k
        }
1558
151k
    }
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE36EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE37EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE23EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1543
297k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1544
        if constexpr (T == TYPE_ARRAY) {
1545
            size_t size = x.size();
1546
            for (size_t i = 0; i < size; ++i) {
1547
                apply_visitor(*this, x[i]);
1548
            }
1549
            return 0;
1550
        } else if constexpr (T == TYPE_NULL) {
1551
            have_nulls = true;
1552
            return 0;
1553
297k
        } else {
1554
297k
            field_types.insert(T);
1555
297k
            type_indexes.insert(T);
1556
297k
            return 0;
1557
297k
        }
1558
297k
    }
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE15EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE10EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE41EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE17EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1543
128k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1544
128k
        if constexpr (T == TYPE_ARRAY) {
1545
128k
            size_t size = x.size();
1546
873k
            for (size_t i = 0; i < size; ++i) {
1547
745k
                apply_visitor(*this, x[i]);
1548
745k
            }
1549
128k
            return 0;
1550
        } else if constexpr (T == TYPE_NULL) {
1551
            have_nulls = true;
1552
            return 0;
1553
        } else {
1554
            field_types.insert(T);
1555
            type_indexes.insert(T);
1556
            return 0;
1557
        }
1558
128k
    }
_ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE16EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1543
1
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1544
        if constexpr (T == TYPE_ARRAY) {
1545
            size_t size = x.size();
1546
            for (size_t i = 0; i < size; ++i) {
1547
                apply_visitor(*this, x[i]);
1548
            }
1549
            return 0;
1550
        } else if constexpr (T == TYPE_NULL) {
1551
            have_nulls = true;
1552
            return 0;
1553
1
        } else {
1554
1
            field_types.insert(T);
1555
1
            type_indexes.insert(T);
1556
1
            return 0;
1557
1
        }
1558
1
    }
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE18EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE32EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1543
1
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1544
        if constexpr (T == TYPE_ARRAY) {
1545
            size_t size = x.size();
1546
            for (size_t i = 0; i < size; ++i) {
1547
                apply_visitor(*this, x[i]);
1548
            }
1549
            return 0;
1550
        } else if constexpr (T == TYPE_NULL) {
1551
            have_nulls = true;
1552
            return 0;
1553
1
        } else {
1554
1
            field_types.insert(T);
1555
1
            type_indexes.insert(T);
1556
1
            return 0;
1557
1
        }
1558
1
    }
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE28EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE29EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE20EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE30EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE35EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE22EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE19EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE24EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE31EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1543
26
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1544
        if constexpr (T == TYPE_ARRAY) {
1545
            size_t size = x.size();
1546
            for (size_t i = 0; i < size; ++i) {
1547
                apply_visitor(*this, x[i]);
1548
            }
1549
            return 0;
1550
        } else if constexpr (T == TYPE_NULL) {
1551
            have_nulls = true;
1552
            return 0;
1553
26
        } else {
1554
26
            field_types.insert(T);
1555
26
            type_indexes.insert(T);
1556
26
            return 0;
1557
26
        }
1558
26
    }
1559
77.9k
    void get_scalar_type(PrimitiveType* type) const {
1560
77.9k
        if (type_indexes.size() == 1) {
1561
            // Most cases will have only one type
1562
64.6k
            *type = *type_indexes.begin();
1563
64.6k
            return;
1564
64.6k
        }
1565
13.2k
        DataTypePtr data_type;
1566
13.2k
        get_least_supertype_jsonb(type_indexes, &data_type);
1567
13.2k
        *type = data_type->get_primitive_type();
1568
13.2k
    }
1569
77.9k
    bool contain_nulls() const { return have_nulls; }
1570
77.9k
    bool need_convert_field() const { return field_types.size() > 1; }
1571
1572
private:
1573
    phmap::flat_hash_set<PrimitiveType> type_indexes;
1574
    phmap::flat_hash_set<PrimitiveType> field_types;
1575
    bool have_nulls = false;
1576
};
1577
1578
template <typename Visitor>
1579
1.66M
void get_field_info_impl(const Field& field, FieldInfo* info) {
1580
1.66M
    Visitor to_scalar_type_visitor;
1581
1.66M
    apply_visitor(to_scalar_type_visitor, field);
1582
1.66M
    PrimitiveType type_id;
1583
1.66M
    to_scalar_type_visitor.get_scalar_type(&type_id);
1584
    // array item's dimension may missmatch, eg. [1, 2, [1, 2, 3]]
1585
1.66M
    *info = {type_id, to_scalar_type_visitor.contain_nulls(),
1586
1.66M
             to_scalar_type_visitor.need_convert_field(),
1587
1.66M
             apply_visitor(FieldVisitorToNumberOfDimensions(), field)};
1588
1.66M
}
_ZN5doris12variant_util19get_field_info_implINS0_24FieldVisitorToScalarTypeEEEvRKNS_5FieldEPNS_9FieldInfoE
Line
Count
Source
1579
77.9k
void get_field_info_impl(const Field& field, FieldInfo* info) {
1580
77.9k
    Visitor to_scalar_type_visitor;
1581
77.9k
    apply_visitor(to_scalar_type_visitor, field);
1582
77.9k
    PrimitiveType type_id;
1583
77.9k
    to_scalar_type_visitor.get_scalar_type(&type_id);
1584
    // array item's dimension may missmatch, eg. [1, 2, [1, 2, 3]]
1585
77.9k
    *info = {type_id, to_scalar_type_visitor.contain_nulls(),
1586
77.9k
             to_scalar_type_visitor.need_convert_field(),
1587
77.9k
             apply_visitor(FieldVisitorToNumberOfDimensions(), field)};
1588
77.9k
}
_ZN5doris12variant_util19get_field_info_implINS0_30SimpleFieldVisitorToScalarTypeEEEvRKNS_5FieldEPNS_9FieldInfoE
Line
Count
Source
1579
1.58M
void get_field_info_impl(const Field& field, FieldInfo* info) {
1580
1.58M
    Visitor to_scalar_type_visitor;
1581
1.58M
    apply_visitor(to_scalar_type_visitor, field);
1582
1.58M
    PrimitiveType type_id;
1583
1.58M
    to_scalar_type_visitor.get_scalar_type(&type_id);
1584
    // array item's dimension may missmatch, eg. [1, 2, [1, 2, 3]]
1585
1.58M
    *info = {type_id, to_scalar_type_visitor.contain_nulls(),
1586
1.58M
             to_scalar_type_visitor.need_convert_field(),
1587
1.58M
             apply_visitor(FieldVisitorToNumberOfDimensions(), field)};
1588
1.58M
}
1589
1590
1.66M
void get_field_info(const Field& field, FieldInfo* info) {
1591
1.66M
    if (field.is_complex_field()) {
1592
77.9k
        get_field_info_impl<FieldVisitorToScalarType>(field, info);
1593
1.58M
    } else {
1594
1.58M
        get_field_info_impl<SimpleFieldVisitorToScalarType>(field, info);
1595
1.58M
    }
1596
1.66M
}
1597
1598
bool generate_sub_column_info(const TabletSchema& schema, int32_t col_unique_id,
1599
                              const std::string& path,
1600
4.45k
                              TabletSchema::SubColumnInfo* sub_column_info) {
1601
4.45k
    const auto& parent_column = schema.column_by_uid(col_unique_id);
1602
4.45k
    std::function<void(const TabletColumn&, TabletColumn*)> generate_result_column =
1603
4.45k
            [&](const TabletColumn& from_column, TabletColumn* to_column) {
1604
241
                to_column->set_name(parent_column.name_lower_case() + "." + path);
1605
241
                to_column->set_type(from_column.type());
1606
241
                to_column->set_parent_unique_id(parent_column.unique_id());
1607
241
                bool is_typed = !parent_column.variant_enable_typed_paths_to_sparse();
1608
241
                to_column->set_path_info(
1609
241
                        PathInData(parent_column.name_lower_case() + "." + path, is_typed));
1610
241
                to_column->set_aggregation_method(parent_column.aggregation());
1611
241
                to_column->set_is_nullable(true);
1612
241
                to_column->set_parent_unique_id(parent_column.unique_id());
1613
241
                if (from_column.is_decimal()) {
1614
0
                    to_column->set_precision(from_column.precision());
1615
0
                }
1616
241
                to_column->set_frac(from_column.frac());
1617
1618
241
                if (from_column.is_array_type()) {
1619
41
                    TabletColumn nested_column;
1620
41
                    generate_result_column(*from_column.get_sub_columns()[0], &nested_column);
1621
41
                    to_column->add_sub_column(nested_column);
1622
41
                }
1623
241
            };
1624
1625
4.45k
    auto generate_index = [&](const std::string& pattern) {
1626
        // 1. find subcolumn's index
1627
200
        if (const auto& indexes = schema.inverted_index_by_field_pattern(col_unique_id, pattern);
1628
200
            !indexes.empty()) {
1629
152
            for (const auto& index : indexes) {
1630
152
                auto index_ptr = std::make_shared<TabletIndex>(*index);
1631
152
                index_ptr->set_escaped_escaped_index_suffix_path(
1632
152
                        sub_column_info->column.path_info_ptr()->get_path());
1633
152
                sub_column_info->indexes.emplace_back(std::move(index_ptr));
1634
152
            }
1635
136
        }
1636
        // 2. find parent column's index
1637
64
        else if (const auto parent_index = schema.inverted_indexs(col_unique_id);
1638
64
                 !parent_index.empty()) {
1639
2
            inherit_index(parent_index, sub_column_info->indexes, sub_column_info->column);
1640
62
        } else {
1641
62
            sub_column_info->indexes.clear();
1642
62
        }
1643
200
    };
1644
1645
4.45k
    const auto& sub_columns = parent_column.get_sub_columns();
1646
4.45k
    for (const auto& sub_column : sub_columns) {
1647
402
        const char* pattern = sub_column->name().c_str();
1648
402
        switch (sub_column->pattern_type()) {
1649
172
        case PatternTypePB::MATCH_NAME: {
1650
172
            if (strcmp(pattern, path.c_str()) == 0) {
1651
91
                generate_result_column(*sub_column, &sub_column_info->column);
1652
91
                generate_index(sub_column->name());
1653
91
                return true;
1654
91
            }
1655
81
            break;
1656
172
        }
1657
230
        case PatternTypePB::MATCH_NAME_GLOB: {
1658
230
            if (glob_match_re2(pattern, path)) {
1659
109
                generate_result_column(*sub_column, &sub_column_info->column);
1660
109
                generate_index(sub_column->name());
1661
109
                return true;
1662
109
            }
1663
121
            break;
1664
230
        }
1665
121
        default:
1666
0
            break;
1667
402
        }
1668
402
    }
1669
4.25k
    return false;
1670
4.45k
}
1671
1672
TabletSchemaSPtr VariantCompactionUtil::calculate_variant_extended_schema(
1673
36
        const std::vector<RowsetSharedPtr>& rowsets, const TabletSchemaSPtr& base_schema) {
1674
36
    if (rowsets.empty()) {
1675
1
        return nullptr;
1676
1
    }
1677
1678
35
    std::vector<TabletSchemaSPtr> schemas;
1679
41
    for (const auto& rs : rowsets) {
1680
41
        if (rs->num_segments() == 0) {
1681
0
            continue;
1682
0
        }
1683
41
        const auto& tablet_schema = rs->tablet_schema();
1684
41
        SegmentCacheHandle segment_cache;
1685
41
        auto st = SegmentLoader::instance()->load_segments(std::static_pointer_cast<BetaRowset>(rs),
1686
41
                                                           &segment_cache);
1687
41
        if (!st.ok()) {
1688
0
            return base_schema;
1689
0
        }
1690
48
        for (const auto& segment : segment_cache.get_segments()) {
1691
48
            TabletSchemaSPtr schema = tablet_schema->copy_without_variant_extracted_columns();
1692
96
            for (const auto& column : tablet_schema->columns()) {
1693
96
                if (!column->is_variant_type()) {
1694
48
                    continue;
1695
48
                }
1696
48
                std::shared_ptr<ColumnReader> column_reader;
1697
48
                OlapReaderStatistics stats;
1698
48
                st = segment->get_column_reader(column->unique_id(), &column_reader, &stats);
1699
48
                if (!st.ok()) {
1700
0
                    LOG(WARNING) << "Failed to get column reader for column: " << column->name()
1701
0
                                 << " error: " << st.to_string();
1702
0
                    continue;
1703
0
                }
1704
48
                if (!column_reader) {
1705
0
                    continue;
1706
0
                }
1707
1708
48
                CHECK(column_reader->get_meta_type() == FieldType::OLAP_FIELD_TYPE_VARIANT);
1709
48
                auto* variant_column_reader =
1710
48
                        assert_cast<segment_v2::VariantColumnReader*>(column_reader.get());
1711
                // load external meta before getting subcolumn meta info
1712
48
                st = variant_column_reader->load_external_meta_once();
1713
48
                if (!st.ok()) {
1714
0
                    LOG(WARNING) << "Failed to load external meta for column: " << column->name()
1715
0
                                 << " error: " << st.to_string();
1716
0
                    continue;
1717
0
                }
1718
48
                const auto* subcolumn_meta_info = variant_column_reader->get_subcolumns_meta_info();
1719
114
                for (const auto& entry : *subcolumn_meta_info) {
1720
114
                    if (entry->path.empty()) {
1721
48
                        continue;
1722
48
                    }
1723
66
                    const std::string& column_name =
1724
66
                            column->name_lower_case() + "." + entry->path.get_path();
1725
66
                    const DataTypePtr& data_type = entry->data.file_column_type;
1726
66
                    PathInDataBuilder full_path_builder;
1727
66
                    auto full_path = full_path_builder.append(column->name_lower_case(), false)
1728
66
                                             .append(entry->path.get_parts(), false)
1729
66
                                             .build();
1730
66
                    TabletColumn subcolumn =
1731
66
                            get_column_by_type(data_type, column_name,
1732
66
                                               ExtraInfo {.unique_id = -1,
1733
66
                                                          .parent_unique_id = column->unique_id(),
1734
66
                                                          .path_info = full_path});
1735
66
                    schema->append_column(subcolumn);
1736
66
                }
1737
48
            }
1738
48
            schemas.emplace_back(schema);
1739
48
        }
1740
41
    }
1741
35
    TabletSchemaSPtr least_common_schema;
1742
35
    auto st = get_least_common_schema(schemas, base_schema, least_common_schema, false);
1743
35
    if (!st.ok()) {
1744
0
        return base_schema;
1745
0
    }
1746
35
    return least_common_schema;
1747
35
}
1748
1749
bool inherit_index(const std::vector<const TabletIndex*>& parent_indexes,
1750
                   TabletIndexes& subcolumns_indexes, FieldType column_type,
1751
1.14k
                   const std::string& suffix_path, bool is_array_nested_type) {
1752
1.14k
    if (parent_indexes.empty()) {
1753
1.10k
        return false;
1754
1.10k
    }
1755
33
    subcolumns_indexes.clear();
1756
    // bkd index or array index only need to inherit one index
1757
33
    if (field_is_numeric_type(column_type) ||
1758
33
        (is_array_nested_type &&
1759
24
         (field_is_numeric_type(column_type) || field_is_slice_type(column_type)))) {
1760
13
        auto index_ptr = std::make_shared<TabletIndex>(*parent_indexes[0]);
1761
13
        index_ptr->set_escaped_escaped_index_suffix_path(suffix_path);
1762
        // no need parse for bkd index or array index
1763
13
        index_ptr->remove_parser_and_analyzer();
1764
13
        subcolumns_indexes.emplace_back(std::move(index_ptr));
1765
13
        return true;
1766
13
    }
1767
    // string type need to inherit all indexes
1768
20
    else if (field_is_slice_type(column_type) && !is_array_nested_type) {
1769
19
        for (const auto& index : parent_indexes) {
1770
19
            auto index_ptr = std::make_shared<TabletIndex>(*index);
1771
19
            index_ptr->set_escaped_escaped_index_suffix_path(suffix_path);
1772
19
            subcolumns_indexes.emplace_back(std::move(index_ptr));
1773
19
        }
1774
18
        return true;
1775
18
    }
1776
2
    return false;
1777
33
}
1778
1779
bool inherit_index(const std::vector<const TabletIndex*>& parent_indexes,
1780
1.14k
                   TabletIndexes& subcolumns_indexes, const TabletColumn& column) {
1781
1.14k
    if (!column.is_extracted_column()) {
1782
3
        return false;
1783
3
    }
1784
1.14k
    if (column.is_array_type()) {
1785
18
        if (column.get_sub_columns().empty()) {
1786
0
            return false;
1787
0
        }
1788
18
        const TabletColumn* nested = column.get_sub_columns()[0].get();
1789
18
        while (nested != nullptr && nested->is_array_type()) {
1790
0
            if (nested->get_sub_columns().empty()) {
1791
0
                return false;
1792
0
            }
1793
0
            nested = nested->get_sub_columns()[0].get();
1794
0
        }
1795
18
        if (nested == nullptr) {
1796
0
            return false;
1797
0
        }
1798
18
        return inherit_index(parent_indexes, subcolumns_indexes, nested->type(),
1799
18
                             column.path_info_ptr()->get_path(), true);
1800
18
    }
1801
1.12k
    return inherit_index(parent_indexes, subcolumns_indexes, column.type(),
1802
1.12k
                         column.path_info_ptr()->get_path());
1803
1.14k
}
1804
1805
bool inherit_index(const std::vector<const TabletIndex*>& parent_indexes,
1806
0
                   TabletIndexes& subcolumns_indexes, const ColumnMetaPB& column_pb) {
1807
0
    if (!column_pb.has_column_path_info()) {
1808
0
        return false;
1809
0
    }
1810
0
    if (column_pb.type() == (int)FieldType::OLAP_FIELD_TYPE_ARRAY) {
1811
0
        if (column_pb.children_columns_size() == 0) {
1812
0
            return false;
1813
0
        }
1814
0
        const ColumnMetaPB* nested = &column_pb.children_columns(0);
1815
0
        while (nested != nullptr && nested->type() == (int)FieldType::OLAP_FIELD_TYPE_ARRAY) {
1816
0
            if (nested->children_columns_size() == 0) {
1817
0
                return false;
1818
0
            }
1819
0
            nested = &nested->children_columns(0);
1820
0
        }
1821
0
        if (nested == nullptr) {
1822
0
            return false;
1823
0
        }
1824
0
        return inherit_index(parent_indexes, subcolumns_indexes, (FieldType)nested->type(),
1825
0
                             column_pb.column_path_info().path(), true);
1826
0
    }
1827
0
    return inherit_index(parent_indexes, subcolumns_indexes, (FieldType)column_pb.type(),
1828
0
                         column_pb.column_path_info().path());
1829
0
}
1830
1831
// ============ Implementation from parse2column.cpp ============
1832
1833
/** Pool for objects that cannot be used from different threads simultaneously.
1834
  * Allows to create an object for each thread.
1835
  * Pool has unbounded size and objects are not destroyed before destruction of pool.
1836
  *
1837
  * Use it in cases when thread local storage is not appropriate
1838
  *  (when maximum number of simultaneously used objects is less
1839
  *   than number of running/sleeping threads, that has ever used object,
1840
  *   and creation/destruction of objects is expensive).
1841
  */
1842
template <typename T>
1843
class SimpleObjectPool {
1844
protected:
1845
    /// Hold all available objects in stack.
1846
    std::mutex mutex;
1847
    std::stack<std::unique_ptr<T>> stack;
1848
    /// Specialized deleter for std::unique_ptr.
1849
    /// Returns underlying pointer back to stack thus reclaiming its ownership.
1850
    struct Deleter {
1851
        SimpleObjectPool<T>* parent;
1852
12.7k
        Deleter(SimpleObjectPool<T>* parent_ = nullptr) : parent {parent_} {} /// NOLINT
1853
12.7k
        void operator()(T* owning_ptr) const {
1854
12.7k
            std::lock_guard lock {parent->mutex};
1855
12.7k
            parent->stack.emplace(owning_ptr);
1856
12.7k
        }
1857
    };
1858
1859
public:
1860
    using Pointer = std::unique_ptr<T, Deleter>;
1861
    /// Extracts and returns a pointer from the stack if it's not empty,
1862
    ///  creates a new one by calling provided f() otherwise.
1863
    template <typename Factory>
1864
12.7k
    Pointer get(Factory&& f) {
1865
12.7k
        std::unique_lock lock(mutex);
1866
12.7k
        if (stack.empty()) {
1867
1
            return {f(), this};
1868
1
        }
1869
12.7k
        auto object = stack.top().release();
1870
12.7k
        stack.pop();
1871
12.7k
        return std::unique_ptr<T, Deleter>(object, Deleter(this));
1872
12.7k
    }
variant_util.cpp:_ZN5doris12variant_util16SimpleObjectPoolINS_14JSONDataParserINS_14SimdJSONParserEEEE3getIZNS0_21parse_json_to_variantERNS_7IColumnERKNS_9StringRefEPS4_RKNS_11ParseConfigEE3$_0EESt10unique_ptrIS4_NS5_7DeleterEEOT_
Line
Count
Source
1864
12.4k
    Pointer get(Factory&& f) {
1865
12.4k
        std::unique_lock lock(mutex);
1866
12.4k
        if (stack.empty()) {
1867
1
            return {f(), this};
1868
1
        }
1869
12.4k
        auto object = stack.top().release();
1870
12.4k
        stack.pop();
1871
12.4k
        return std::unique_ptr<T, Deleter>(object, Deleter(this));
1872
12.4k
    }
variant_util.cpp:_ZN5doris12variant_util16SimpleObjectPoolINS_14JSONDataParserINS_14SimdJSONParserEEEE3getIZNS0_21parse_json_to_variantERNS_7IColumnERKNS_9ColumnStrIjEERKNS_11ParseConfigEE3$_0EESt10unique_ptrIS4_NS5_7DeleterEEOT_
Line
Count
Source
1864
307
    Pointer get(Factory&& f) {
1865
307
        std::unique_lock lock(mutex);
1866
307
        if (stack.empty()) {
1867
0
            return {f(), this};
1868
0
        }
1869
307
        auto object = stack.top().release();
1870
307
        stack.pop();
1871
307
        return std::unique_ptr<T, Deleter>(object, Deleter(this));
1872
307
    }
1873
    /// Like get(), but creates object using default constructor.
1874
    Pointer getDefault() {
1875
        return get([] { return new T; });
1876
    }
1877
};
1878
1879
SimpleObjectPool<JsonParser> parsers_pool;
1880
1881
using Node = typename ColumnVariant::Subcolumns::Node;
1882
1883
148k
static inline void append_binary_bytes(ColumnString::Chars& chars, const void* data, size_t size) {
1884
148k
    const auto old_size = chars.size();
1885
148k
    chars.resize(old_size + size);
1886
148k
    memcpy(chars.data() + old_size, reinterpret_cast<const char*>(data), size);
1887
148k
}
1888
1889
72.3k
static inline void append_binary_type(ColumnString::Chars& chars, FieldType type) {
1890
72.3k
    const uint8_t t = static_cast<uint8_t>(type);
1891
72.3k
    append_binary_bytes(chars, &t, sizeof(uint8_t));
1892
72.3k
}
1893
1894
3.74k
static inline void append_binary_sizet(ColumnString::Chars& chars, size_t v) {
1895
3.74k
    append_binary_bytes(chars, &v, sizeof(size_t));
1896
3.74k
}
1897
1898
72.3k
static void append_field_to_binary_chars(const Field& field, ColumnString::Chars& chars) {
1899
72.3k
    switch (field.get_type()) {
1900
0
    case PrimitiveType::TYPE_NULL: {
1901
0
        append_binary_type(chars, FieldType::OLAP_FIELD_TYPE_NONE);
1902
0
        return;
1903
0
    }
1904
2
    case PrimitiveType::TYPE_BOOLEAN: {
1905
2
        append_binary_type(chars,
1906
2
                           primitive_type_to_storage_field_type(PrimitiveType::TYPE_BOOLEAN));
1907
2
        const auto v = static_cast<UInt8>(field.get<PrimitiveType::TYPE_BOOLEAN>());
1908
2
        append_binary_bytes(chars, &v, sizeof(UInt8));
1909
2
        return;
1910
0
    }
1911
68.5k
    case PrimitiveType::TYPE_BIGINT: {
1912
68.5k
        append_binary_type(chars, primitive_type_to_storage_field_type(PrimitiveType::TYPE_BIGINT));
1913
68.5k
        const auto v = field.get<PrimitiveType::TYPE_BIGINT>();
1914
68.5k
        append_binary_bytes(chars, &v, sizeof(Int64));
1915
68.5k
        return;
1916
0
    }
1917
1
    case PrimitiveType::TYPE_LARGEINT: {
1918
1
        append_binary_type(chars,
1919
1
                           primitive_type_to_storage_field_type(PrimitiveType::TYPE_LARGEINT));
1920
1
        const auto v = field.get<PrimitiveType::TYPE_LARGEINT>();
1921
1
        append_binary_bytes(chars, &v, sizeof(int128_t));
1922
1
        return;
1923
0
    }
1924
3
    case PrimitiveType::TYPE_DOUBLE: {
1925
3
        append_binary_type(chars, primitive_type_to_storage_field_type(PrimitiveType::TYPE_DOUBLE));
1926
3
        const auto v = field.get<PrimitiveType::TYPE_DOUBLE>();
1927
3
        append_binary_bytes(chars, &v, sizeof(Float64));
1928
3
        return;
1929
0
    }
1930
3.73k
    case PrimitiveType::TYPE_STRING: {
1931
3.73k
        append_binary_type(chars, FieldType::OLAP_FIELD_TYPE_STRING);
1932
3.73k
        const auto& v = field.get<PrimitiveType::TYPE_STRING>();
1933
3.73k
        append_binary_sizet(chars, v.size());
1934
3.73k
        append_binary_bytes(chars, v.data(), v.size());
1935
3.73k
        return;
1936
0
    }
1937
0
    case PrimitiveType::TYPE_JSONB: {
1938
0
        append_binary_type(chars, FieldType::OLAP_FIELD_TYPE_JSONB);
1939
0
        const auto& v = field.get<PrimitiveType::TYPE_JSONB>();
1940
0
        append_binary_sizet(chars, v.get_size());
1941
0
        append_binary_bytes(chars, v.get_value(), v.get_size());
1942
0
        return;
1943
0
    }
1944
13
    case PrimitiveType::TYPE_ARRAY: {
1945
13
        append_binary_type(chars, FieldType::OLAP_FIELD_TYPE_ARRAY);
1946
13
        const auto& a = field.get<PrimitiveType::TYPE_ARRAY>();
1947
13
        append_binary_sizet(chars, a.size());
1948
18
        for (const auto& elem : a) {
1949
18
            append_field_to_binary_chars(elem, chars);
1950
18
        }
1951
13
        return;
1952
0
    }
1953
0
    default:
1954
0
        throw doris::Exception(ErrorCode::INVALID_ARGUMENT, "Unsupported field type {}",
1955
0
                               field.get_type());
1956
72.3k
    }
1957
72.3k
}
1958
template <typename ParserImpl>
1959
void parse_json_to_variant_impl(IColumn& column, const char* src, size_t length,
1960
107k
                                JSONDataParser<ParserImpl>* parser, const ParseConfig& config) {
1961
107k
    auto& column_variant = assert_cast<ColumnVariant&>(column);
1962
107k
    std::optional<ParseResult> result;
1963
    /// Treat empty string as an empty object
1964
    /// for better CAST from String to Object.
1965
107k
    if (length > 0) {
1966
107k
        result = parser->parse(src, length, config);
1967
107k
    } else {
1968
0
        result = ParseResult {};
1969
0
    }
1970
107k
    if (!result) {
1971
11
        VLOG_DEBUG << "failed to parse " << std::string_view(src, length) << ", length= " << length;
1972
11
        if (config::variant_throw_exeception_on_invalid_json) {
1973
0
            throw doris::Exception(ErrorCode::INVALID_ARGUMENT, "Failed to parse object {}",
1974
0
                                   std::string_view(src, length));
1975
0
        }
1976
        // Treat as string
1977
11
        PathInData root_path;
1978
11
        Field field = Field::create_field<TYPE_STRING>(String(src, length));
1979
11
        result = ParseResult {{root_path}, {field}};
1980
11
    }
1981
107k
    auto& [paths, values] = *result;
1982
107k
    assert(paths.size() == values.size());
1983
107k
    size_t old_num_rows = column_variant.rows();
1984
107k
    if (config.deprecated_enable_flatten_nested) {
1985
        // here we should check the paths in variant and paths in result,
1986
        // if two paths which same prefix have different structure, we should throw an exception
1987
3.00k
        std::vector<PathInData> check_paths;
1988
11.9k
        for (const auto& entry : column_variant.get_subcolumns()) {
1989
11.9k
            check_paths.push_back(entry->path);
1990
11.9k
        }
1991
3.00k
        check_paths.insert(check_paths.end(), paths.begin(), paths.end());
1992
3.00k
        THROW_IF_ERROR(check_variant_has_no_ambiguous_paths(check_paths));
1993
3.00k
    }
1994
107k
    auto [doc_value_data_paths, doc_value_data_values] =
1995
107k
            column_variant.get_doc_value_data_paths_and_values();
1996
107k
    auto& doc_value_data_offsets = column_variant.serialized_doc_value_column_offsets();
1997
1998
1.43M
    auto flush_defaults = [](ColumnVariant::Subcolumn* subcolumn) {
1999
1.43M
        const auto num_defaults = subcolumn->cur_num_of_defaults();
2000
1.43M
        if (num_defaults > 0) {
2001
165k
            subcolumn->insert_many_defaults(num_defaults);
2002
165k
            subcolumn->reset_current_num_of_defaults();
2003
165k
        }
2004
1.43M
    };
2005
2006
107k
    auto is_plain_path = [](const PathInData& path) {
2007
13
        for (const auto& part : path.get_parts()) {
2008
13
            if (part.is_nested || part.anonymous_array_level != 0) {
2009
0
                return false;
2010
0
            }
2011
13
        }
2012
9
        return true;
2013
9
    };
2014
2015
107k
    auto get_or_create_subcolumn = [&](const PathInData& path, size_t index_hint,
2016
1.43M
                                       const FieldInfo& field_info) -> ColumnVariant::Subcolumn* {
2017
1.43M
        auto* subcolumn = column_variant.get_subcolumn(path, index_hint);
2018
1.43M
        if (subcolumn == nullptr) {
2019
3.78k
            if (path.has_nested_part()) {
2020
8
                column_variant.add_nested_subcolumn(path, field_info, old_num_rows);
2021
3.77k
            } else {
2022
3.77k
                column_variant.add_sub_column(path, old_num_rows);
2023
3.77k
            }
2024
3.78k
            subcolumn = column_variant.get_subcolumn(path, index_hint);
2025
3.78k
        }
2026
1.43M
        if (!subcolumn) {
2027
0
            throw doris::Exception(ErrorCode::INVALID_ARGUMENT, "Failed to find sub column {}",
2028
0
                                   path.get_path());
2029
0
        }
2030
1.43M
        return subcolumn;
2031
1.43M
    };
2032
2033
1.43M
    auto normalize_plain_path = [&](const PathInData& path) {
2034
1.43M
        if (!config.check_duplicate_json_path || path.empty() || !is_plain_path(path)) {
2035
1.43M
            return path;
2036
1.43M
        }
2037
9
        return PathInData(path.get_path());
2038
1.43M
    };
2039
2040
107k
    auto insert_into_subcolumn = [&](size_t i,
2041
1.43M
                                     bool check_size_mismatch) -> ColumnVariant::Subcolumn* {
2042
1.43M
        FieldInfo field_info;
2043
1.43M
        get_field_info(values[i], &field_info);
2044
1.43M
        if (field_info.scalar_type_id == PrimitiveType::INVALID_TYPE) {
2045
109
            return nullptr;
2046
109
        }
2047
1.43M
        auto path = normalize_plain_path(paths[i]);
2048
1.43M
        auto* subcolumn = get_or_create_subcolumn(path, i, field_info);
2049
1.43M
        flush_defaults(subcolumn);
2050
1.43M
        if (check_size_mismatch && subcolumn->size() != old_num_rows) {
2051
1
            throw doris::Exception(ErrorCode::INVALID_ARGUMENT,
2052
1
                                   "subcolumn {} size missmatched, may contains duplicated entry",
2053
1
                                   path.get_path());
2054
1
        }
2055
1.43M
        subcolumn->insert(std::move(values[i]), std::move(field_info));
2056
1.43M
        return subcolumn;
2057
1.43M
    };
2058
2059
107k
    switch (config.parse_to) {
2060
102k
    case ParseConfig::ParseTo::OnlySubcolumns:
2061
1.54M
        for (size_t i = 0; i < paths.size(); ++i) {
2062
1.43M
            insert_into_subcolumn(i, true);
2063
1.43M
        }
2064
102k
        break;
2065
4.30k
    case ParseConfig::ParseTo::OnlyDocValueColumn: {
2066
4.30k
        std::vector<size_t> doc_item_indexes;
2067
4.30k
        doc_item_indexes.reserve(paths.size());
2068
4.30k
        phmap::flat_hash_set<StringRef, StringRefHash> seen_paths;
2069
4.30k
        seen_paths.reserve(paths.size());
2070
2071
76.6k
        for (size_t i = 0; i < paths.size(); ++i) {
2072
72.3k
            FieldInfo field_info;
2073
72.3k
            get_field_info(values[i], &field_info);
2074
72.3k
            if (paths[i].empty()) {
2075
                // Plain non-doc VARIANT can use doc-value KV as writer-side staging. An
2076
                // invalid root entry from JSON object/array is neither a scalar root value nor
2077
                // a doc KV path, so leave this row's doc offset empty. Doc-mode and valid scalar
2078
                // roots still populate the root subcolumn below.
2079
2
                if (!column_variant.enable_doc_mode() &&
2080
2
                    field_info.scalar_type_id == PrimitiveType::INVALID_TYPE) {
2081
1
                    continue;
2082
1
                }
2083
1
                auto* subcolumn = column_variant.get_subcolumn(paths[i]);
2084
1
                DCHECK(subcolumn != nullptr);
2085
1
                flush_defaults(subcolumn);
2086
1
                subcolumn->insert(std::move(values[i]), std::move(field_info));
2087
1
                continue;
2088
2
            }
2089
72.3k
            if (field_info.scalar_type_id == PrimitiveType::INVALID_TYPE ||
2090
72.3k
                values[i].get_type() == PrimitiveType::TYPE_NULL) {
2091
0
                continue;
2092
0
            }
2093
72.3k
            const auto& path_str = paths[i].get_path();
2094
72.3k
            StringRef path_ref {path_str.data(), path_str.size()};
2095
72.3k
            if (UNLIKELY(!seen_paths.emplace(path_ref).second)) {
2096
0
                throw doris::Exception(ErrorCode::INVALID_ARGUMENT,
2097
0
                                       "may contains duplicated entry : {}",
2098
0
                                       std::string_view(path_str));
2099
0
            }
2100
72.3k
            doc_item_indexes.push_back(i);
2101
72.3k
        }
2102
2103
4.30k
        std::sort(doc_item_indexes.begin(), doc_item_indexes.end(),
2104
617k
                  [&](size_t l, size_t r) { return paths[l].get_path() < paths[r].get_path(); });
2105
72.3k
        for (const auto idx : doc_item_indexes) {
2106
72.3k
            const auto& path_str = paths[idx].get_path();
2107
72.3k
            doc_value_data_paths->insert_data(path_str.data(), path_str.size());
2108
72.3k
            auto& chars = doc_value_data_values->get_chars();
2109
72.3k
            append_field_to_binary_chars(values[idx], chars);
2110
72.3k
            doc_value_data_values->get_offsets().push_back(chars.size());
2111
72.3k
        }
2112
4.30k
    } break;
2113
107k
    }
2114
107k
    doc_value_data_offsets.push_back(doc_value_data_paths->size());
2115
    // /// Insert default values to missed subcolumns.
2116
107k
    const auto& subcolumns = column_variant.get_subcolumns();
2117
4.32M
    for (const auto& entry : subcolumns) {
2118
4.32M
        if (entry->data.size() == old_num_rows) {
2119
            // Handle nested paths differently from simple paths
2120
2.88M
            if (entry->path.has_nested_part()) {
2121
                // Try to insert default from nested, if failed, insert regular default
2122
0
                bool success = UNLIKELY(column_variant.try_insert_default_from_nested(entry));
2123
0
                if (!success) {
2124
0
                    entry->data.insert_default();
2125
0
                }
2126
2.88M
            } else {
2127
                // For non-nested paths, increment default counter
2128
2.88M
                entry->data.increment_default_counter();
2129
2.88M
            }
2130
2.88M
        }
2131
4.32M
    }
2132
107k
    column_variant.incr_num_rows();
2133
107k
    if (column_variant.get_sparse_column()->size() == old_num_rows) {
2134
107k
        column_variant.get_sparse_column_mutable().insert_default();
2135
107k
    }
2136
107k
#ifndef NDEBUG
2137
107k
    column_variant.check_consistency();
2138
107k
#endif
2139
107k
}
2140
2141
// exposed interfaces
2142
void parse_json_to_variant(IColumn& column, const StringRef& json, JsonParser* parser,
2143
12.4k
                           const ParseConfig& config) {
2144
12.4k
    if (parser) {
2145
0
        return parse_json_to_variant_impl(column, json.data, json.size, parser, config);
2146
12.4k
    } else {
2147
12.4k
        auto pool_parser = parsers_pool.get([] { return new JsonParser(); });
2148
12.4k
        return parse_json_to_variant_impl(column, json.data, json.size, pool_parser.get(), config);
2149
12.4k
    }
2150
12.4k
}
2151
2152
void parse_json_to_variant(IColumn& column, const ColumnString& raw_json_column,
2153
307
                           const ParseConfig& config) {
2154
307
    auto parser = parsers_pool.get([] { return new JsonParser(); });
2155
95.4k
    for (size_t i = 0; i < raw_json_column.size(); ++i) {
2156
95.1k
        StringRef raw_json = raw_json_column.get_data_at(i);
2157
95.1k
        parse_json_to_variant_impl(column, raw_json.data, raw_json.size, parser.get(), config);
2158
95.1k
    }
2159
307
    column.finalize();
2160
307
}
2161
2162
// parse the doc snapshot column to subcolumns
2163
0
void materialize_docs_to_subcolumns(ColumnVariant& column_variant) {
2164
0
    auto subcolumns = materialize_docs_to_subcolumns_map(column_variant);
2165
2166
0
    for (auto& entry : subcolumns) {
2167
0
        entry.second.finalize();
2168
0
        if (!column_variant.add_sub_column(PathInData(entry.first),
2169
0
                                           IColumn::mutate(entry.second.get_finalized_column_ptr()),
2170
0
                                           entry.second.get_least_common_type())) {
2171
0
            throw doris::Exception(ErrorCode::INTERNAL_ERROR,
2172
0
                                   "Failed to add subcolumn {}, which is from doc snapshot column",
2173
0
                                   entry.first);
2174
0
        }
2175
0
    }
2176
2177
0
    column_variant.finalize();
2178
0
}
2179
2180
// ============ Implementation from variant_util.cpp ============
2181
2182
phmap::flat_hash_map<std::string_view, ColumnVariant::Subcolumn> materialize_docs_to_subcolumns_map(
2183
11
        const ColumnVariant& variant, size_t expected_unique_paths) {
2184
11
    constexpr size_t kInitialPathReserve = 8192;
2185
11
    phmap::flat_hash_map<std::string_view, ColumnVariant::Subcolumn> subcolumns;
2186
2187
11
    const auto [column_key, column_value] = variant.get_doc_value_data_paths_and_values();
2188
11
    const auto& column_offsets = variant.serialized_doc_value_column_offsets();
2189
11
    const size_t num_rows = column_offsets.size();
2190
2191
11
    DCHECK_EQ(num_rows, variant.size()) << "doc snapshot offsets size mismatch with variant rows";
2192
2193
11
    subcolumns.reserve(expected_unique_paths != 0
2194
11
                               ? expected_unique_paths
2195
11
                               : std::min<size_t>(column_key->size(), kInitialPathReserve));
2196
2197
36
    for (size_t row = 0; row < num_rows; ++row) {
2198
25
        const size_t start = column_offsets[row - 1];
2199
25
        const size_t end = column_offsets[row];
2200
71
        for (size_t i = start; i < end; ++i) {
2201
46
            const auto& key = column_key->get_data_at(i);
2202
46
            const std::string_view path_sv(key.data, key.size);
2203
2204
46
            auto [it, inserted] =
2205
46
                    subcolumns.try_emplace(path_sv, ColumnVariant::Subcolumn {0, true, false});
2206
46
            auto& subcolumn = it->second;
2207
46
            if (inserted) {
2208
27
                subcolumn.insert_many_defaults(row);
2209
27
            } else if (subcolumn.size() != row) {
2210
4
                subcolumn.insert_many_defaults(row - subcolumn.size());
2211
4
            }
2212
46
            subcolumn.deserialize_from_binary_column(column_value, i);
2213
46
        }
2214
25
    }
2215
2216
27
    for (auto& [path, subcolumn] : subcolumns) {
2217
27
        if (subcolumn.size() != num_rows) {
2218
7
            subcolumn.insert_many_defaults(num_rows - subcolumn.size());
2219
7
        }
2220
27
    }
2221
2222
11
    return subcolumns;
2223
11
}
2224
2225
Status _parse_and_materialize_variant_columns(Block& block,
2226
                                              const std::vector<uint32_t>& variant_pos,
2227
242
                                              const std::vector<ParseConfig>& configs) {
2228
623
    for (size_t i = 0; i < variant_pos.size(); ++i) {
2229
381
        auto column_ref = block.get_by_position(variant_pos[i]).column;
2230
381
        bool is_nullable = is_column_nullable(*column_ref);
2231
381
        MutableColumnPtr owner_column = IColumn::mutate(std::move(column_ref));
2232
381
        ColumnPtr nullable_null_map;
2233
381
        MutableColumnPtr var_column;
2234
381
        if (is_nullable) {
2235
15
            const auto& nullable = assert_cast<const ColumnNullable&>(*owner_column);
2236
15
            nullable_null_map = nullable.get_null_map_column_ptr();
2237
15
            var_column = IColumn::mutate(nullable.get_nested_column_ptr());
2238
366
        } else {
2239
366
            var_column = std::move(owner_column);
2240
366
        }
2241
381
        auto& var = assert_cast<ColumnVariant&>(*var_column);
2242
381
        var_column->finalize();
2243
2244
381
        MutableColumnPtr variant_column;
2245
381
        if (!var.is_scalar_variant()) {
2246
            // already parsed
2247
356
            continue;
2248
356
        }
2249
2250
25
        VLOG_DEBUG << "parse scalar variant column: " << var.get_root_type()->get_name();
2251
25
        ColumnPtr scalar_root_column;
2252
25
        if (var.get_root_type()->get_primitive_type() == TYPE_JSONB) {
2253
2
            scalar_root_column = jsonb_root_to_json_string_column(*var.get_root());
2254
23
        } else {
2255
23
            const auto& root = *var.get_root();
2256
23
            scalar_root_column =
2257
23
                    is_column_nullable(root)
2258
23
                            ? assert_cast<const ColumnNullable&>(root).get_nested_column_ptr()
2259
23
                            : var.get_root();
2260
23
        }
2261
2262
25
        if (scalar_root_column->is_column_string()) {
2263
24
            variant_column = ColumnVariant::create(0, var.enable_doc_mode());
2264
24
            parse_json_to_variant(*variant_column.get(),
2265
24
                                  assert_cast<const ColumnString&>(*scalar_root_column),
2266
24
                                  configs[i]);
2267
24
        } else {
2268
            // Root maybe other types rather than string like ColumnVariant(Int32).
2269
            // In this case, we should finlize the root and cast to JSON type
2270
1
            auto expected_root_type =
2271
1
                    make_nullable(std::make_shared<ColumnVariant::MostCommonType>());
2272
1
            var.ensure_root_node_type(expected_root_type);
2273
1
            variant_column = std::move(var_column);
2274
1
        }
2275
2276
        // Wrap variant with nullmap if it is nullable
2277
25
        ColumnPtr result = variant_column->get_ptr();
2278
25
        if (is_nullable) {
2279
2
            result = ColumnNullable::create(result, nullable_null_map);
2280
2
        }
2281
25
        block.get_by_position(variant_pos[i]).column = result;
2282
25
    }
2283
242
    return Status::OK();
2284
242
}
2285
2286
Status parse_and_materialize_variant_columns(Block& block, const std::vector<uint32_t>& variant_pos,
2287
242
                                             const std::vector<ParseConfig>& configs) {
2288
242
    RETURN_IF_CATCH_EXCEPTION(
2289
242
            { return _parse_and_materialize_variant_columns(block, variant_pos, configs); });
2290
242
}
2291
2292
namespace {
2293
2294
ParseConfig::ParseTo select_storage_variant_parse_target(const TabletColumn& column,
2295
370
                                                         const ParseConfig& config) {
2296
    // NestedGroup consumes the parse-time subcolumn tree to build nested storage structures, so it
2297
    // must not go through doc-value staging.
2298
370
    if (column.variant_enable_nested_group()) {
2299
0
        return ParseConfig::ParseTo::OnlySubcolumns;
2300
0
    }
2301
2302
    // Persistent doc mode owns doc-value bucket columns in VariantDocWriter. Keep it separate from
2303
    // the plain non-doc staging optimization, even when typed paths or parent indexes exist.
2304
370
    if (column.variant_enable_doc_mode()) {
2305
3
        return ParseConfig::ParseTo::OnlyDocValueColumn;
2306
3
    }
2307
2308
    // Deprecated flatten-nested still consumes parse-time subcolumns. Predefined typed paths and
2309
    // parent inverted indexes are handled later by regular doc-value staging: typed paths are
2310
    // forced into the materialized set unless typed-to-sparse is enabled, and materialized dynamic
2311
    // subcolumns inherit parent indexes while sparse payloads stay unindexed.
2312
367
    if (config.deprecated_enable_flatten_nested) {
2313
0
        return ParseConfig::ParseTo::OnlySubcolumns;
2314
0
    }
2315
2316
    // Plain dynamic non-doc VARIANT can avoid eagerly creating thousands of parse-time subcolumns.
2317
    // The segment writer will pick the materialized/sparse split from this doc-value KV staging.
2318
    // Keep a BE switch so tests and rollouts can compare the old parse-time path with staging under
2319
    // the same writer and schema.
2320
367
    switch (config::variant_storage_parse_mode) {
2321
363
    case 0:
2322
365
    case 2:
2323
365
        return ParseConfig::ParseTo::OnlyDocValueColumn;
2324
2
    case 1:
2325
2
        return ParseConfig::ParseTo::OnlySubcolumns;
2326
0
    default:
2327
0
        CHECK(false) << "invalid variant_storage_parse_mode: "
2328
0
                     << config::variant_storage_parse_mode;
2329
0
        return ParseConfig::ParseTo::OnlyDocValueColumn;
2330
367
    }
2331
367
}
2332
2333
} // namespace
2334
2335
Status parse_and_materialize_variant_columns(Block& block, const TabletSchema& tablet_schema,
2336
231
                                             const std::vector<uint32_t>& column_pos) {
2337
231
    std::vector<uint32_t> variant_column_pos;
2338
231
    std::vector<uint32_t> variant_schema_pos;
2339
231
    variant_column_pos.reserve(column_pos.size());
2340
231
    variant_schema_pos.reserve(column_pos.size());
2341
1.08k
    for (size_t block_pos = 0; block_pos < column_pos.size(); ++block_pos) {
2342
851
        const uint32_t schema_pos = column_pos[block_pos];
2343
851
        const auto& column = tablet_schema.column(schema_pos);
2344
851
        if (column.is_variant_type()) {
2345
370
            variant_column_pos.push_back(schema_pos);
2346
370
            variant_schema_pos.push_back(schema_pos);
2347
370
        }
2348
851
    }
2349
2350
231
    if (variant_column_pos.empty()) {
2351
0
        return Status::OK();
2352
0
    }
2353
2354
231
    std::vector<ParseConfig> configs(variant_column_pos.size());
2355
601
    for (size_t i = 0; i < variant_column_pos.size(); ++i) {
2356
        // Deprecated legacy flatten-nested switch. Distinct from variant_enable_nested_group.
2357
370
        configs[i].deprecated_enable_flatten_nested =
2358
370
                tablet_schema.deprecated_variant_flatten_nested();
2359
370
        configs[i].check_duplicate_json_path = config::variant_enable_duplicate_json_path_check;
2360
370
        const auto& column = tablet_schema.column(variant_schema_pos[i]);
2361
370
        if (!column.is_variant_type()) {
2362
0
            return Status::InternalError("column is not variant type, column name: {}",
2363
0
                                         column.name());
2364
0
        }
2365
370
        configs[i].parse_to = select_storage_variant_parse_target(column, configs[i]);
2366
370
    }
2367
2368
231
    RETURN_IF_ERROR(parse_and_materialize_variant_columns(block, variant_column_pos, configs));
2369
231
    return Status::OK();
2370
231
}
2371
2372
} // namespace doris::variant_util