Coverage Report

Created: 2026-06-24 20:24

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/exprs/function/function_jsonb.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 <glog/logging.h>
19
20
#include <algorithm>
21
#include <cstdlib>
22
#include <memory>
23
#include <string>
24
#include <string_view>
25
#include <tuple>
26
#include <type_traits>
27
#include <utility>
28
#include <variant>
29
30
#include "common/compiler_util.h" // IWYU pragma: keep
31
#include "common/status.h"
32
#include "core/assert_cast.h"
33
#include "core/block/block.h"
34
#include "core/block/column_numbers.h"
35
#include "core/block/column_with_type_and_name.h"
36
#include "core/column/column.h"
37
#include "core/column/column_array.h"
38
#include "core/column/column_const.h"
39
#include "core/column/column_nullable.h"
40
#include "core/column/column_string.h"
41
#include "core/column/column_vector.h"
42
#include "core/custom_allocator.h"
43
#include "core/data_type/data_type.h"
44
#include "core/data_type/data_type_array.h"
45
#include "core/data_type/data_type_jsonb.h"
46
#include "core/data_type/data_type_nullable.h"
47
#include "core/data_type/data_type_string.h"
48
#include "core/data_type/define_primitive_type.h"
49
#include "core/data_type/primitive_type.h"
50
#include "core/string_ref.h"
51
#include "core/types.h"
52
#include "core/value/jsonb_value.h"
53
#include "exec/common/stringop_substring.h"
54
#include "exec/common/template_helpers.hpp"
55
#include "exec/common/util.hpp"
56
#include "exprs/aggregate/aggregate_function.h"
57
#include "exprs/function/function.h"
58
#include "exprs/function/like.h"
59
#include "exprs/function/simple_function_factory.h"
60
#include "exprs/function_context.h"
61
#include "util/jsonb_document.h"
62
#include "util/jsonb_utils.h"
63
#include "util/jsonb_writer.h"
64
#include "util/simd/bits.h"
65
66
namespace doris {
67
68
enum class NullalbeMode { NULLABLE = 0, FOLLOW_INPUT };
69
70
enum class JsonbParseErrorMode { FAIL = 0, RETURN_NULL, RETURN_VALUE };
71
72
// func(string,string) -> json
73
template <NullalbeMode nullable_mode, JsonbParseErrorMode parse_error_handle_mode>
74
class FunctionJsonbParseBase : public IFunction {
75
private:
76
    struct FunctionJsonbParseState {
77
        StringRef default_value;
78
        JsonBinaryValue default_value_parser;
79
        bool has_const_default_value = false;
80
        bool default_is_null = false;
81
    };
82
83
public:
84
    static constexpr auto name = "json_parse";
85
    static constexpr auto alias = "jsonb_parse";
86
18
    static FunctionPtr create() { return std::make_shared<FunctionJsonbParseBase>(); }
_ZN5doris22FunctionJsonbParseBaseILNS_12NullalbeModeE1ELNS_19JsonbParseErrorModeE0EE6createEv
Line
Count
Source
86
9
    static FunctionPtr create() { return std::make_shared<FunctionJsonbParseBase>(); }
_ZN5doris22FunctionJsonbParseBaseILNS_12NullalbeModeE0ELNS_19JsonbParseErrorModeE1EE6createEv
Line
Count
Source
86
3
    static FunctionPtr create() { return std::make_shared<FunctionJsonbParseBase>(); }
_ZN5doris22FunctionJsonbParseBaseILNS_12NullalbeModeE1ELNS_19JsonbParseErrorModeE2EE6createEv
Line
Count
Source
86
6
    static FunctionPtr create() { return std::make_shared<FunctionJsonbParseBase>(); }
87
88
4
    String get_name() const override {
89
4
        String error_mode;
90
4
        switch (parse_error_handle_mode) {
91
1
        case JsonbParseErrorMode::FAIL:
92
1
            break;
93
1
        case JsonbParseErrorMode::RETURN_NULL:
94
1
            error_mode = "_error_to_null";
95
1
            break;
96
2
        case JsonbParseErrorMode::RETURN_VALUE:
97
2
            error_mode = "_error_to_value";
98
2
            break;
99
4
        }
100
101
4
        return name + error_mode;
102
4
    }
_ZNK5doris22FunctionJsonbParseBaseILNS_12NullalbeModeE1ELNS_19JsonbParseErrorModeE0EE8get_nameB5cxx11Ev
Line
Count
Source
88
1
    String get_name() const override {
89
1
        String error_mode;
90
1
        switch (parse_error_handle_mode) {
91
1
        case JsonbParseErrorMode::FAIL:
92
1
            break;
93
0
        case JsonbParseErrorMode::RETURN_NULL:
94
0
            error_mode = "_error_to_null";
95
0
            break;
96
0
        case JsonbParseErrorMode::RETURN_VALUE:
97
0
            error_mode = "_error_to_value";
98
0
            break;
99
1
        }
100
101
1
        return name + error_mode;
102
1
    }
_ZNK5doris22FunctionJsonbParseBaseILNS_12NullalbeModeE0ELNS_19JsonbParseErrorModeE1EE8get_nameB5cxx11Ev
Line
Count
Source
88
1
    String get_name() const override {
89
1
        String error_mode;
90
1
        switch (parse_error_handle_mode) {
91
0
        case JsonbParseErrorMode::FAIL:
92
0
            break;
93
1
        case JsonbParseErrorMode::RETURN_NULL:
94
1
            error_mode = "_error_to_null";
95
1
            break;
96
0
        case JsonbParseErrorMode::RETURN_VALUE:
97
0
            error_mode = "_error_to_value";
98
0
            break;
99
1
        }
100
101
1
        return name + error_mode;
102
1
    }
_ZNK5doris22FunctionJsonbParseBaseILNS_12NullalbeModeE1ELNS_19JsonbParseErrorModeE2EE8get_nameB5cxx11Ev
Line
Count
Source
88
2
    String get_name() const override {
89
2
        String error_mode;
90
2
        switch (parse_error_handle_mode) {
91
0
        case JsonbParseErrorMode::FAIL:
92
0
            break;
93
0
        case JsonbParseErrorMode::RETURN_NULL:
94
0
            error_mode = "_error_to_null";
95
0
            break;
96
2
        case JsonbParseErrorMode::RETURN_VALUE:
97
2
            error_mode = "_error_to_value";
98
2
            break;
99
2
        }
100
101
2
        return name + error_mode;
102
2
    }
103
104
16
    bool is_variadic() const override {
105
16
        return parse_error_handle_mode == JsonbParseErrorMode::RETURN_VALUE;
106
16
    }
_ZNK5doris22FunctionJsonbParseBaseILNS_12NullalbeModeE1ELNS_19JsonbParseErrorModeE0EE11is_variadicEv
Line
Count
Source
104
8
    bool is_variadic() const override {
105
8
        return parse_error_handle_mode == JsonbParseErrorMode::RETURN_VALUE;
106
8
    }
_ZNK5doris22FunctionJsonbParseBaseILNS_12NullalbeModeE0ELNS_19JsonbParseErrorModeE1EE11is_variadicEv
Line
Count
Source
104
2
    bool is_variadic() const override {
105
2
        return parse_error_handle_mode == JsonbParseErrorMode::RETURN_VALUE;
106
2
    }
_ZNK5doris22FunctionJsonbParseBaseILNS_12NullalbeModeE1ELNS_19JsonbParseErrorModeE2EE11is_variadicEv
Line
Count
Source
104
6
    bool is_variadic() const override {
105
6
        return parse_error_handle_mode == JsonbParseErrorMode::RETURN_VALUE;
106
6
    }
107
108
9
    size_t get_number_of_arguments() const override {
109
9
        switch (parse_error_handle_mode) {
110
7
        case JsonbParseErrorMode::FAIL:
111
7
            return 1;
112
1
        case JsonbParseErrorMode::RETURN_NULL:
113
1
            return 1;
114
1
        case JsonbParseErrorMode::RETURN_VALUE:
115
1
            return 0;
116
9
        }
117
9
    }
_ZNK5doris22FunctionJsonbParseBaseILNS_12NullalbeModeE1ELNS_19JsonbParseErrorModeE0EE23get_number_of_argumentsEv
Line
Count
Source
108
7
    size_t get_number_of_arguments() const override {
109
7
        switch (parse_error_handle_mode) {
110
7
        case JsonbParseErrorMode::FAIL:
111
7
            return 1;
112
0
        case JsonbParseErrorMode::RETURN_NULL:
113
0
            return 1;
114
0
        case JsonbParseErrorMode::RETURN_VALUE:
115
0
            return 0;
116
7
        }
117
7
    }
_ZNK5doris22FunctionJsonbParseBaseILNS_12NullalbeModeE0ELNS_19JsonbParseErrorModeE1EE23get_number_of_argumentsEv
Line
Count
Source
108
1
    size_t get_number_of_arguments() const override {
109
1
        switch (parse_error_handle_mode) {
110
0
        case JsonbParseErrorMode::FAIL:
111
0
            return 1;
112
1
        case JsonbParseErrorMode::RETURN_NULL:
113
1
            return 1;
114
0
        case JsonbParseErrorMode::RETURN_VALUE:
115
0
            return 0;
116
1
        }
117
1
    }
_ZNK5doris22FunctionJsonbParseBaseILNS_12NullalbeModeE1ELNS_19JsonbParseErrorModeE2EE23get_number_of_argumentsEv
Line
Count
Source
108
1
    size_t get_number_of_arguments() const override {
109
1
        switch (parse_error_handle_mode) {
110
0
        case JsonbParseErrorMode::FAIL:
111
0
            return 1;
112
0
        case JsonbParseErrorMode::RETURN_NULL:
113
0
            return 1;
114
1
        case JsonbParseErrorMode::RETURN_VALUE:
115
1
            return 0;
116
1
        }
117
1
    }
118
119
12
    DataTypePtr get_return_type_impl(const DataTypes& arguments) const override {
120
12
        bool is_nullable = false;
121
12
        switch (nullable_mode) {
122
1
        case NullalbeMode::NULLABLE:
123
1
            is_nullable = true;
124
1
            break;
125
11
        case NullalbeMode::FOLLOW_INPUT: {
126
16
            for (auto arg : arguments) {
127
16
                is_nullable |= arg->is_nullable();
128
16
            }
129
11
            break;
130
0
        }
131
12
        }
132
133
12
        return is_nullable ? make_nullable(std::make_shared<DataTypeJsonb>())
134
12
                           : std::make_shared<DataTypeJsonb>();
135
12
    }
_ZNK5doris22FunctionJsonbParseBaseILNS_12NullalbeModeE1ELNS_19JsonbParseErrorModeE0EE20get_return_type_implERKSt6vectorISt10shared_ptrIKNS_9IDataTypeEESaIS8_EE
Line
Count
Source
119
7
    DataTypePtr get_return_type_impl(const DataTypes& arguments) const override {
120
7
        bool is_nullable = false;
121
7
        switch (nullable_mode) {
122
0
        case NullalbeMode::NULLABLE:
123
0
            is_nullable = true;
124
0
            break;
125
7
        case NullalbeMode::FOLLOW_INPUT: {
126
7
            for (auto arg : arguments) {
127
7
                is_nullable |= arg->is_nullable();
128
7
            }
129
7
            break;
130
0
        }
131
7
        }
132
133
7
        return is_nullable ? make_nullable(std::make_shared<DataTypeJsonb>())
134
7
                           : std::make_shared<DataTypeJsonb>();
135
7
    }
_ZNK5doris22FunctionJsonbParseBaseILNS_12NullalbeModeE0ELNS_19JsonbParseErrorModeE1EE20get_return_type_implERKSt6vectorISt10shared_ptrIKNS_9IDataTypeEESaIS8_EE
Line
Count
Source
119
1
    DataTypePtr get_return_type_impl(const DataTypes& arguments) const override {
120
1
        bool is_nullable = false;
121
1
        switch (nullable_mode) {
122
1
        case NullalbeMode::NULLABLE:
123
1
            is_nullable = true;
124
1
            break;
125
0
        case NullalbeMode::FOLLOW_INPUT: {
126
0
            for (auto arg : arguments) {
127
0
                is_nullable |= arg->is_nullable();
128
0
            }
129
0
            break;
130
0
        }
131
1
        }
132
133
1
        return is_nullable ? make_nullable(std::make_shared<DataTypeJsonb>())
134
1
                           : std::make_shared<DataTypeJsonb>();
135
1
    }
_ZNK5doris22FunctionJsonbParseBaseILNS_12NullalbeModeE1ELNS_19JsonbParseErrorModeE2EE20get_return_type_implERKSt6vectorISt10shared_ptrIKNS_9IDataTypeEESaIS8_EE
Line
Count
Source
119
4
    DataTypePtr get_return_type_impl(const DataTypes& arguments) const override {
120
4
        bool is_nullable = false;
121
4
        switch (nullable_mode) {
122
0
        case NullalbeMode::NULLABLE:
123
0
            is_nullable = true;
124
0
            break;
125
4
        case NullalbeMode::FOLLOW_INPUT: {
126
9
            for (auto arg : arguments) {
127
9
                is_nullable |= arg->is_nullable();
128
9
            }
129
4
            break;
130
0
        }
131
4
        }
132
133
4
        return is_nullable ? make_nullable(std::make_shared<DataTypeJsonb>())
134
4
                           : std::make_shared<DataTypeJsonb>();
135
4
    }
136
137
23
    bool use_default_implementation_for_nulls() const override { return false; }
_ZNK5doris22FunctionJsonbParseBaseILNS_12NullalbeModeE1ELNS_19JsonbParseErrorModeE0EE36use_default_implementation_for_nullsEv
Line
Count
Source
137
14
    bool use_default_implementation_for_nulls() const override { return false; }
_ZNK5doris22FunctionJsonbParseBaseILNS_12NullalbeModeE0ELNS_19JsonbParseErrorModeE1EE36use_default_implementation_for_nullsEv
Line
Count
Source
137
2
    bool use_default_implementation_for_nulls() const override { return false; }
_ZNK5doris22FunctionJsonbParseBaseILNS_12NullalbeModeE1ELNS_19JsonbParseErrorModeE2EE36use_default_implementation_for_nullsEv
Line
Count
Source
137
7
    bool use_default_implementation_for_nulls() const override { return false; }
138
139
22
    Status open(FunctionContext* context, FunctionContext::FunctionStateScope scope) override {
140
22
        if (scope == FunctionContext::FunctionStateScope::FRAGMENT_LOCAL) {
141
11
            std::shared_ptr<FunctionJsonbParseState> state =
142
11
                    std::make_shared<FunctionJsonbParseState>();
143
11
            context->set_function_state(FunctionContext::FRAGMENT_LOCAL, state);
144
11
        }
145
22
        if constexpr (parse_error_handle_mode == JsonbParseErrorMode::RETURN_VALUE) {
146
6
            if (scope == FunctionContext::FunctionStateScope::FRAGMENT_LOCAL) {
147
3
                auto* state = reinterpret_cast<FunctionJsonbParseState*>(
148
3
                        context->get_function_state(FunctionContext::FRAGMENT_LOCAL));
149
3
                if (state) {
150
3
                    if (context->get_num_args() == 2) {
151
2
                        if (context->is_col_constant(1)) {
152
0
                            const auto default_value_col = context->get_constant_col(1)->column_ptr;
153
0
                            if (default_value_col->is_null_at(0)) {
154
0
                                state->default_is_null = true;
155
0
                            } else {
156
0
                                const auto& default_value = default_value_col->get_data_at(0);
157
158
0
                                state->default_value = default_value;
159
0
                                state->has_const_default_value = true;
160
0
                            }
161
0
                        }
162
2
                    } else if (context->get_num_args() == 1) {
163
0
                        RETURN_IF_ERROR(
164
0
                                state->default_value_parser.from_json_string(std::string("{}")));
165
0
                        state->default_value = StringRef(state->default_value_parser.value(),
166
0
                                                         state->default_value_parser.size());
167
0
                        state->has_const_default_value = true;
168
0
                    }
169
3
                }
170
3
            }
171
172
6
            if (context->get_num_args() != 1 && context->get_num_args() != 2) {
173
1
                return Status::InvalidArgument(
174
1
                        "{} function should have 1 or 2 arguments, "
175
1
                        "but got {}",
176
1
                        get_name(), context->get_num_args());
177
1
            }
178
6
        }
179
5
        return Status::OK();
180
22
    }
_ZN5doris22FunctionJsonbParseBaseILNS_12NullalbeModeE1ELNS_19JsonbParseErrorModeE0EE4openEPNS_15FunctionContextENS4_18FunctionStateScopeE
Line
Count
Source
139
14
    Status open(FunctionContext* context, FunctionContext::FunctionStateScope scope) override {
140
14
        if (scope == FunctionContext::FunctionStateScope::FRAGMENT_LOCAL) {
141
7
            std::shared_ptr<FunctionJsonbParseState> state =
142
7
                    std::make_shared<FunctionJsonbParseState>();
143
7
            context->set_function_state(FunctionContext::FRAGMENT_LOCAL, state);
144
7
        }
145
        if constexpr (parse_error_handle_mode == JsonbParseErrorMode::RETURN_VALUE) {
146
            if (scope == FunctionContext::FunctionStateScope::FRAGMENT_LOCAL) {
147
                auto* state = reinterpret_cast<FunctionJsonbParseState*>(
148
                        context->get_function_state(FunctionContext::FRAGMENT_LOCAL));
149
                if (state) {
150
                    if (context->get_num_args() == 2) {
151
                        if (context->is_col_constant(1)) {
152
                            const auto default_value_col = context->get_constant_col(1)->column_ptr;
153
                            if (default_value_col->is_null_at(0)) {
154
                                state->default_is_null = true;
155
                            } else {
156
                                const auto& default_value = default_value_col->get_data_at(0);
157
158
                                state->default_value = default_value;
159
                                state->has_const_default_value = true;
160
                            }
161
                        }
162
                    } else if (context->get_num_args() == 1) {
163
                        RETURN_IF_ERROR(
164
                                state->default_value_parser.from_json_string(std::string("{}")));
165
                        state->default_value = StringRef(state->default_value_parser.value(),
166
                                                         state->default_value_parser.size());
167
                        state->has_const_default_value = true;
168
                    }
169
                }
170
            }
171
172
            if (context->get_num_args() != 1 && context->get_num_args() != 2) {
173
                return Status::InvalidArgument(
174
                        "{} function should have 1 or 2 arguments, "
175
                        "but got {}",
176
                        get_name(), context->get_num_args());
177
            }
178
        }
179
14
        return Status::OK();
180
14
    }
_ZN5doris22FunctionJsonbParseBaseILNS_12NullalbeModeE0ELNS_19JsonbParseErrorModeE1EE4openEPNS_15FunctionContextENS4_18FunctionStateScopeE
Line
Count
Source
139
2
    Status open(FunctionContext* context, FunctionContext::FunctionStateScope scope) override {
140
2
        if (scope == FunctionContext::FunctionStateScope::FRAGMENT_LOCAL) {
141
1
            std::shared_ptr<FunctionJsonbParseState> state =
142
1
                    std::make_shared<FunctionJsonbParseState>();
143
1
            context->set_function_state(FunctionContext::FRAGMENT_LOCAL, state);
144
1
        }
145
        if constexpr (parse_error_handle_mode == JsonbParseErrorMode::RETURN_VALUE) {
146
            if (scope == FunctionContext::FunctionStateScope::FRAGMENT_LOCAL) {
147
                auto* state = reinterpret_cast<FunctionJsonbParseState*>(
148
                        context->get_function_state(FunctionContext::FRAGMENT_LOCAL));
149
                if (state) {
150
                    if (context->get_num_args() == 2) {
151
                        if (context->is_col_constant(1)) {
152
                            const auto default_value_col = context->get_constant_col(1)->column_ptr;
153
                            if (default_value_col->is_null_at(0)) {
154
                                state->default_is_null = true;
155
                            } else {
156
                                const auto& default_value = default_value_col->get_data_at(0);
157
158
                                state->default_value = default_value;
159
                                state->has_const_default_value = true;
160
                            }
161
                        }
162
                    } else if (context->get_num_args() == 1) {
163
                        RETURN_IF_ERROR(
164
                                state->default_value_parser.from_json_string(std::string("{}")));
165
                        state->default_value = StringRef(state->default_value_parser.value(),
166
                                                         state->default_value_parser.size());
167
                        state->has_const_default_value = true;
168
                    }
169
                }
170
            }
171
172
            if (context->get_num_args() != 1 && context->get_num_args() != 2) {
173
                return Status::InvalidArgument(
174
                        "{} function should have 1 or 2 arguments, "
175
                        "but got {}",
176
                        get_name(), context->get_num_args());
177
            }
178
        }
179
2
        return Status::OK();
180
2
    }
_ZN5doris22FunctionJsonbParseBaseILNS_12NullalbeModeE1ELNS_19JsonbParseErrorModeE2EE4openEPNS_15FunctionContextENS4_18FunctionStateScopeE
Line
Count
Source
139
6
    Status open(FunctionContext* context, FunctionContext::FunctionStateScope scope) override {
140
6
        if (scope == FunctionContext::FunctionStateScope::FRAGMENT_LOCAL) {
141
3
            std::shared_ptr<FunctionJsonbParseState> state =
142
3
                    std::make_shared<FunctionJsonbParseState>();
143
3
            context->set_function_state(FunctionContext::FRAGMENT_LOCAL, state);
144
3
        }
145
6
        if constexpr (parse_error_handle_mode == JsonbParseErrorMode::RETURN_VALUE) {
146
6
            if (scope == FunctionContext::FunctionStateScope::FRAGMENT_LOCAL) {
147
3
                auto* state = reinterpret_cast<FunctionJsonbParseState*>(
148
3
                        context->get_function_state(FunctionContext::FRAGMENT_LOCAL));
149
3
                if (state) {
150
3
                    if (context->get_num_args() == 2) {
151
2
                        if (context->is_col_constant(1)) {
152
0
                            const auto default_value_col = context->get_constant_col(1)->column_ptr;
153
0
                            if (default_value_col->is_null_at(0)) {
154
0
                                state->default_is_null = true;
155
0
                            } else {
156
0
                                const auto& default_value = default_value_col->get_data_at(0);
157
158
0
                                state->default_value = default_value;
159
0
                                state->has_const_default_value = true;
160
0
                            }
161
0
                        }
162
2
                    } else if (context->get_num_args() == 1) {
163
0
                        RETURN_IF_ERROR(
164
0
                                state->default_value_parser.from_json_string(std::string("{}")));
165
0
                        state->default_value = StringRef(state->default_value_parser.value(),
166
0
                                                         state->default_value_parser.size());
167
0
                        state->has_const_default_value = true;
168
0
                    }
169
3
                }
170
3
            }
171
172
6
            if (context->get_num_args() != 1 && context->get_num_args() != 2) {
173
1
                return Status::InvalidArgument(
174
1
                        "{} function should have 1 or 2 arguments, "
175
1
                        "but got {}",
176
1
                        get_name(), context->get_num_args());
177
1
            }
178
6
        }
179
5
        return Status::OK();
180
6
    }
181
182
    Status execute_impl(FunctionContext* context, Block& block, const ColumnNumbers& arguments,
183
11
                        uint32_t result, size_t input_rows_count) const override {
184
11
        auto&& [col_from, col_from_is_const] =
185
11
                unpack_if_const(block.get_by_position(arguments[0]).column);
186
187
11
        if (col_from_is_const && col_from->is_null_at(0)) {
188
0
            auto col_str = ColumnString::create();
189
0
            col_str->insert_default();
190
0
            auto null_map = ColumnUInt8::create(1, 1);
191
0
            auto nullable_col = ColumnNullable::create(std::move(col_str), std::move(null_map));
192
0
            block.get_by_position(result).column =
193
0
                    ColumnConst::create(std::move(nullable_col), input_rows_count);
194
0
            return Status::OK();
195
0
        }
196
197
11
        auto null_map = ColumnUInt8::create(0, 0);
198
11
        bool is_nullable = false;
199
200
11
        switch (nullable_mode) {
201
1
        case NullalbeMode::NULLABLE: {
202
1
            is_nullable = true;
203
1
            break;
204
0
        }
205
10
        case NullalbeMode::FOLLOW_INPUT: {
206
13
            for (auto arg : arguments) {
207
13
                is_nullable |= block.get_by_position(arg).type->is_nullable();
208
13
            }
209
10
            break;
210
0
        }
211
11
        }
212
213
11
        if (is_nullable) {
214
10
            null_map = ColumnUInt8::create(input_rows_count, 0);
215
10
        }
216
217
8
        const ColumnString* col_from_string = nullptr;
218
11
        if (const auto* nullable_col = check_and_get_column<ColumnNullable>(col_from.get())) {
219
10
            VectorizedUtils::update_null_map(null_map->get_data(),
220
10
                                             nullable_col->get_null_map_data(), col_from_is_const);
221
10
            col_from_string =
222
10
                    assert_cast<const ColumnString*>(nullable_col->get_nested_column_ptr().get());
223
10
        } else {
224
1
            col_from_string = assert_cast<const ColumnString*>(col_from.get());
225
1
        }
226
227
8
        StringRef constant_default_value;
228
8
        bool default_value_const = false;
229
8
        bool default_value_null_const = false;
230
8
        ColumnPtr default_value_col;
231
8
        JsonBinaryValue default_jsonb_value_parser;
232
8
        const ColumnString* default_value_str_col = nullptr;
233
8
        const NullMap* default_value_nullmap = nullptr;
234
8
        if constexpr (parse_error_handle_mode == JsonbParseErrorMode::RETURN_VALUE) {
235
3
            auto* state = reinterpret_cast<FunctionJsonbParseState*>(
236
3
                    context->get_function_state(FunctionContext::FRAGMENT_LOCAL));
237
3
            if (state && state->has_const_default_value) {
238
0
                constant_default_value = state->default_value;
239
0
                default_value_null_const = state->default_is_null;
240
0
                default_value_const = true;
241
3
            } else if (arguments.size() > 1) {
242
3
                if (block.get_by_position(arguments[1]).type->get_primitive_type() !=
243
3
                    PrimitiveType::TYPE_JSONB) {
244
1
                    return Status::InvalidArgument(
245
1
                            "{} second argument should be jsonb type, but got {}", get_name(),
246
1
                            block.get_by_position(arguments[1]).type->get_name());
247
1
                }
248
2
                std::tie(default_value_col, default_value_const) =
249
2
                        unpack_if_const(block.get_by_position(arguments[1]).column);
250
2
                if (default_value_const) {
251
0
                    const JsonbDocument* default_value_doc = nullptr;
252
0
                    if (default_value_col->is_null_at(0)) {
253
0
                        default_value_null_const = true;
254
0
                    } else {
255
0
                        auto data = default_value_col->get_data_at(0);
256
0
                        RETURN_IF_ERROR(JsonbDocument::checkAndCreateDocument(data.data, data.size,
257
0
                                                                              &default_value_doc));
258
0
                        constant_default_value = data;
259
0
                    }
260
2
                } else {
261
2
                    if (const auto* nullable_col =
262
2
                                check_and_get_column<ColumnNullable>(default_value_col.get())) {
263
1
                        default_value_str_col = assert_cast<const ColumnString*>(
264
1
                                nullable_col->get_nested_column_ptr().get());
265
1
                        default_value_nullmap = &(nullable_col->get_null_map_data());
266
1
                    } else {
267
1
                        default_value_str_col =
268
1
                                assert_cast<const ColumnString*>(default_value_col.get());
269
1
                    }
270
2
                }
271
2
            } else if (arguments.size() == 1) {
272
                // parse default value '{}' should always success.
273
0
                RETURN_IF_ERROR(default_jsonb_value_parser.from_json_string(std::string("{}")));
274
0
                default_value_const = true;
275
0
                constant_default_value.data = default_jsonb_value_parser.value();
276
0
                constant_default_value.size = default_jsonb_value_parser.size();
277
0
            }
278
3
        }
279
280
2
        auto col_to = ColumnString::create();
281
282
8
        col_to->reserve(input_rows_count);
283
284
8
        auto& null_map_data = null_map->get_data();
285
286
        // parser can be reused for performance
287
8
        JsonBinaryValue jsonb_value;
288
289
1.10k
        for (size_t i = 0; i < input_rows_count; ++i) {
290
1.09k
            if (is_nullable && null_map_data[i]) {
291
3
                col_to->insert_default();
292
3
                continue;
293
3
            }
294
295
1.09k
            auto index = index_check_const(i, col_from_is_const);
296
1.09k
            const auto& val = col_from_string->get_data_at(index);
297
1.09k
            auto st = jsonb_value.from_json_string(val.data, val.size);
298
1.09k
            if (st.ok()) {
299
                // insert jsonb format data
300
1.07k
                col_to->insert_data(jsonb_value.value(), jsonb_value.size());
301
1.07k
            } else {
302
18
                if constexpr (parse_error_handle_mode == JsonbParseErrorMode::FAIL) {
303
6
                    return Status::InvalidArgument(
304
6
                            "Parse json document failed at row {}, error: {}", i, st.to_string());
305
6
                } else if constexpr (parse_error_handle_mode == JsonbParseErrorMode::RETURN_NULL) {
306
6
                    null_map_data[i] = 1;
307
6
                    col_to->insert_default();
308
6
                } else {
309
6
                    if (default_value_const) {
310
0
                        if (default_value_null_const) {
311
0
                            null_map_data[i] = 1;
312
0
                            col_to->insert_default();
313
0
                        } else {
314
0
                            col_to->insert_data(constant_default_value.data,
315
0
                                                constant_default_value.size);
316
0
                        }
317
6
                    } else {
318
6
                        if (default_value_nullmap && (*default_value_nullmap)[i]) {
319
0
                            null_map_data[i] = 1;
320
0
                            col_to->insert_default();
321
0
                            continue;
322
0
                        }
323
6
                        auto value = default_value_str_col->get_data_at(i);
324
6
                        col_to->insert_data(value.data, value.size);
325
6
                    }
326
6
                }
327
18
            }
328
1.09k
        }
329
330
11
        if (is_nullable) {
331
4
            block.replace_by_position(
332
4
                    result, ColumnNullable::create(std::move(col_to), std::move(null_map)));
333
7
        } else {
334
7
            block.replace_by_position(result, std::move(col_to));
335
7
        }
336
337
3
        return Status::OK();
338
3
    }
_ZNK5doris22FunctionJsonbParseBaseILNS_12NullalbeModeE1ELNS_19JsonbParseErrorModeE0EE12execute_implEPNS_15FunctionContextERNS_5BlockERKSt6vectorIjSaIjEEjm
Line
Count
Source
183
7
                        uint32_t result, size_t input_rows_count) const override {
184
7
        auto&& [col_from, col_from_is_const] =
185
7
                unpack_if_const(block.get_by_position(arguments[0]).column);
186
187
7
        if (col_from_is_const && col_from->is_null_at(0)) {
188
0
            auto col_str = ColumnString::create();
189
0
            col_str->insert_default();
190
0
            auto null_map = ColumnUInt8::create(1, 1);
191
0
            auto nullable_col = ColumnNullable::create(std::move(col_str), std::move(null_map));
192
0
            block.get_by_position(result).column =
193
0
                    ColumnConst::create(std::move(nullable_col), input_rows_count);
194
0
            return Status::OK();
195
0
        }
196
197
7
        auto null_map = ColumnUInt8::create(0, 0);
198
7
        bool is_nullable = false;
199
200
7
        switch (nullable_mode) {
201
0
        case NullalbeMode::NULLABLE: {
202
0
            is_nullable = true;
203
0
            break;
204
0
        }
205
7
        case NullalbeMode::FOLLOW_INPUT: {
206
7
            for (auto arg : arguments) {
207
7
                is_nullable |= block.get_by_position(arg).type->is_nullable();
208
7
            }
209
7
            break;
210
0
        }
211
7
        }
212
213
7
        if (is_nullable) {
214
7
            null_map = ColumnUInt8::create(input_rows_count, 0);
215
7
        }
216
217
7
        const ColumnString* col_from_string = nullptr;
218
7
        if (const auto* nullable_col = check_and_get_column<ColumnNullable>(col_from.get())) {
219
7
            VectorizedUtils::update_null_map(null_map->get_data(),
220
7
                                             nullable_col->get_null_map_data(), col_from_is_const);
221
7
            col_from_string =
222
7
                    assert_cast<const ColumnString*>(nullable_col->get_nested_column_ptr().get());
223
7
        } else {
224
0
            col_from_string = assert_cast<const ColumnString*>(col_from.get());
225
0
        }
226
227
7
        StringRef constant_default_value;
228
7
        bool default_value_const = false;
229
7
        bool default_value_null_const = false;
230
7
        ColumnPtr default_value_col;
231
7
        JsonBinaryValue default_jsonb_value_parser;
232
7
        const ColumnString* default_value_str_col = nullptr;
233
7
        const NullMap* default_value_nullmap = nullptr;
234
        if constexpr (parse_error_handle_mode == JsonbParseErrorMode::RETURN_VALUE) {
235
            auto* state = reinterpret_cast<FunctionJsonbParseState*>(
236
                    context->get_function_state(FunctionContext::FRAGMENT_LOCAL));
237
            if (state && state->has_const_default_value) {
238
                constant_default_value = state->default_value;
239
                default_value_null_const = state->default_is_null;
240
                default_value_const = true;
241
            } else if (arguments.size() > 1) {
242
                if (block.get_by_position(arguments[1]).type->get_primitive_type() !=
243
                    PrimitiveType::TYPE_JSONB) {
244
                    return Status::InvalidArgument(
245
                            "{} second argument should be jsonb type, but got {}", get_name(),
246
                            block.get_by_position(arguments[1]).type->get_name());
247
                }
248
                std::tie(default_value_col, default_value_const) =
249
                        unpack_if_const(block.get_by_position(arguments[1]).column);
250
                if (default_value_const) {
251
                    const JsonbDocument* default_value_doc = nullptr;
252
                    if (default_value_col->is_null_at(0)) {
253
                        default_value_null_const = true;
254
                    } else {
255
                        auto data = default_value_col->get_data_at(0);
256
                        RETURN_IF_ERROR(JsonbDocument::checkAndCreateDocument(data.data, data.size,
257
                                                                              &default_value_doc));
258
                        constant_default_value = data;
259
                    }
260
                } else {
261
                    if (const auto* nullable_col =
262
                                check_and_get_column<ColumnNullable>(default_value_col.get())) {
263
                        default_value_str_col = assert_cast<const ColumnString*>(
264
                                nullable_col->get_nested_column_ptr().get());
265
                        default_value_nullmap = &(nullable_col->get_null_map_data());
266
                    } else {
267
                        default_value_str_col =
268
                                assert_cast<const ColumnString*>(default_value_col.get());
269
                    }
270
                }
271
            } else if (arguments.size() == 1) {
272
                // parse default value '{}' should always success.
273
                RETURN_IF_ERROR(default_jsonb_value_parser.from_json_string(std::string("{}")));
274
                default_value_const = true;
275
                constant_default_value.data = default_jsonb_value_parser.value();
276
                constant_default_value.size = default_jsonb_value_parser.size();
277
            }
278
        }
279
280
7
        auto col_to = ColumnString::create();
281
282
7
        col_to->reserve(input_rows_count);
283
284
7
        auto& null_map_data = null_map->get_data();
285
286
        // parser can be reused for performance
287
7
        JsonBinaryValue jsonb_value;
288
289
30
        for (size_t i = 0; i < input_rows_count; ++i) {
290
23
            if (is_nullable && null_map_data[i]) {
291
1
                col_to->insert_default();
292
1
                continue;
293
1
            }
294
295
22
            auto index = index_check_const(i, col_from_is_const);
296
22
            const auto& val = col_from_string->get_data_at(index);
297
22
            auto st = jsonb_value.from_json_string(val.data, val.size);
298
22
            if (st.ok()) {
299
                // insert jsonb format data
300
16
                col_to->insert_data(jsonb_value.value(), jsonb_value.size());
301
16
            } else {
302
6
                if constexpr (parse_error_handle_mode == JsonbParseErrorMode::FAIL) {
303
6
                    return Status::InvalidArgument(
304
6
                            "Parse json document failed at row {}, error: {}", i, st.to_string());
305
                } else if constexpr (parse_error_handle_mode == JsonbParseErrorMode::RETURN_NULL) {
306
                    null_map_data[i] = 1;
307
                    col_to->insert_default();
308
                } else {
309
                    if (default_value_const) {
310
                        if (default_value_null_const) {
311
                            null_map_data[i] = 1;
312
                            col_to->insert_default();
313
                        } else {
314
                            col_to->insert_data(constant_default_value.data,
315
                                                constant_default_value.size);
316
                        }
317
                    } else {
318
                        if (default_value_nullmap && (*default_value_nullmap)[i]) {
319
                            null_map_data[i] = 1;
320
                            col_to->insert_default();
321
                            continue;
322
                        }
323
                        auto value = default_value_str_col->get_data_at(i);
324
                        col_to->insert_data(value.data, value.size);
325
                    }
326
                }
327
6
            }
328
22
        }
329
330
7
        if (is_nullable) {
331
1
            block.replace_by_position(
332
1
                    result, ColumnNullable::create(std::move(col_to), std::move(null_map)));
333
6
        } else {
334
6
            block.replace_by_position(result, std::move(col_to));
335
6
        }
336
337
7
        return Status::OK();
338
7
    }
_ZNK5doris22FunctionJsonbParseBaseILNS_12NullalbeModeE0ELNS_19JsonbParseErrorModeE1EE12execute_implEPNS_15FunctionContextERNS_5BlockERKSt6vectorIjSaIjEEjm
Line
Count
Source
183
1
                        uint32_t result, size_t input_rows_count) const override {
184
1
        auto&& [col_from, col_from_is_const] =
185
1
                unpack_if_const(block.get_by_position(arguments[0]).column);
186
187
1
        if (col_from_is_const && col_from->is_null_at(0)) {
188
0
            auto col_str = ColumnString::create();
189
0
            col_str->insert_default();
190
0
            auto null_map = ColumnUInt8::create(1, 1);
191
0
            auto nullable_col = ColumnNullable::create(std::move(col_str), std::move(null_map));
192
0
            block.get_by_position(result).column =
193
0
                    ColumnConst::create(std::move(nullable_col), input_rows_count);
194
0
            return Status::OK();
195
0
        }
196
197
1
        auto null_map = ColumnUInt8::create(0, 0);
198
1
        bool is_nullable = false;
199
200
1
        switch (nullable_mode) {
201
1
        case NullalbeMode::NULLABLE: {
202
1
            is_nullable = true;
203
1
            break;
204
0
        }
205
0
        case NullalbeMode::FOLLOW_INPUT: {
206
0
            for (auto arg : arguments) {
207
0
                is_nullable |= block.get_by_position(arg).type->is_nullable();
208
0
            }
209
0
            break;
210
0
        }
211
1
        }
212
213
1
        if (is_nullable) {
214
1
            null_map = ColumnUInt8::create(input_rows_count, 0);
215
1
        }
216
217
1
        const ColumnString* col_from_string = nullptr;
218
1
        if (const auto* nullable_col = check_and_get_column<ColumnNullable>(col_from.get())) {
219
1
            VectorizedUtils::update_null_map(null_map->get_data(),
220
1
                                             nullable_col->get_null_map_data(), col_from_is_const);
221
1
            col_from_string =
222
1
                    assert_cast<const ColumnString*>(nullable_col->get_nested_column_ptr().get());
223
1
        } else {
224
0
            col_from_string = assert_cast<const ColumnString*>(col_from.get());
225
0
        }
226
227
1
        StringRef constant_default_value;
228
1
        bool default_value_const = false;
229
1
        bool default_value_null_const = false;
230
1
        ColumnPtr default_value_col;
231
1
        JsonBinaryValue default_jsonb_value_parser;
232
1
        const ColumnString* default_value_str_col = nullptr;
233
1
        const NullMap* default_value_nullmap = nullptr;
234
        if constexpr (parse_error_handle_mode == JsonbParseErrorMode::RETURN_VALUE) {
235
            auto* state = reinterpret_cast<FunctionJsonbParseState*>(
236
                    context->get_function_state(FunctionContext::FRAGMENT_LOCAL));
237
            if (state && state->has_const_default_value) {
238
                constant_default_value = state->default_value;
239
                default_value_null_const = state->default_is_null;
240
                default_value_const = true;
241
            } else if (arguments.size() > 1) {
242
                if (block.get_by_position(arguments[1]).type->get_primitive_type() !=
243
                    PrimitiveType::TYPE_JSONB) {
244
                    return Status::InvalidArgument(
245
                            "{} second argument should be jsonb type, but got {}", get_name(),
246
                            block.get_by_position(arguments[1]).type->get_name());
247
                }
248
                std::tie(default_value_col, default_value_const) =
249
                        unpack_if_const(block.get_by_position(arguments[1]).column);
250
                if (default_value_const) {
251
                    const JsonbDocument* default_value_doc = nullptr;
252
                    if (default_value_col->is_null_at(0)) {
253
                        default_value_null_const = true;
254
                    } else {
255
                        auto data = default_value_col->get_data_at(0);
256
                        RETURN_IF_ERROR(JsonbDocument::checkAndCreateDocument(data.data, data.size,
257
                                                                              &default_value_doc));
258
                        constant_default_value = data;
259
                    }
260
                } else {
261
                    if (const auto* nullable_col =
262
                                check_and_get_column<ColumnNullable>(default_value_col.get())) {
263
                        default_value_str_col = assert_cast<const ColumnString*>(
264
                                nullable_col->get_nested_column_ptr().get());
265
                        default_value_nullmap = &(nullable_col->get_null_map_data());
266
                    } else {
267
                        default_value_str_col =
268
                                assert_cast<const ColumnString*>(default_value_col.get());
269
                    }
270
                }
271
            } else if (arguments.size() == 1) {
272
                // parse default value '{}' should always success.
273
                RETURN_IF_ERROR(default_jsonb_value_parser.from_json_string(std::string("{}")));
274
                default_value_const = true;
275
                constant_default_value.data = default_jsonb_value_parser.value();
276
                constant_default_value.size = default_jsonb_value_parser.size();
277
            }
278
        }
279
280
1
        auto col_to = ColumnString::create();
281
282
1
        col_to->reserve(input_rows_count);
283
284
1
        auto& null_map_data = null_map->get_data();
285
286
        // parser can be reused for performance
287
1
        JsonBinaryValue jsonb_value;
288
289
24
        for (size_t i = 0; i < input_rows_count; ++i) {
290
23
            if (is_nullable && null_map_data[i]) {
291
1
                col_to->insert_default();
292
1
                continue;
293
1
            }
294
295
22
            auto index = index_check_const(i, col_from_is_const);
296
22
            const auto& val = col_from_string->get_data_at(index);
297
22
            auto st = jsonb_value.from_json_string(val.data, val.size);
298
22
            if (st.ok()) {
299
                // insert jsonb format data
300
16
                col_to->insert_data(jsonb_value.value(), jsonb_value.size());
301
16
            } else {
302
                if constexpr (parse_error_handle_mode == JsonbParseErrorMode::FAIL) {
303
                    return Status::InvalidArgument(
304
                            "Parse json document failed at row {}, error: {}", i, st.to_string());
305
6
                } else if constexpr (parse_error_handle_mode == JsonbParseErrorMode::RETURN_NULL) {
306
6
                    null_map_data[i] = 1;
307
6
                    col_to->insert_default();
308
                } else {
309
                    if (default_value_const) {
310
                        if (default_value_null_const) {
311
                            null_map_data[i] = 1;
312
                            col_to->insert_default();
313
                        } else {
314
                            col_to->insert_data(constant_default_value.data,
315
                                                constant_default_value.size);
316
                        }
317
                    } else {
318
                        if (default_value_nullmap && (*default_value_nullmap)[i]) {
319
                            null_map_data[i] = 1;
320
                            col_to->insert_default();
321
                            continue;
322
                        }
323
                        auto value = default_value_str_col->get_data_at(i);
324
                        col_to->insert_data(value.data, value.size);
325
                    }
326
                }
327
6
            }
328
22
        }
329
330
1
        if (is_nullable) {
331
1
            block.replace_by_position(
332
1
                    result, ColumnNullable::create(std::move(col_to), std::move(null_map)));
333
1
        } else {
334
0
            block.replace_by_position(result, std::move(col_to));
335
0
        }
336
337
1
        return Status::OK();
338
1
    }
_ZNK5doris22FunctionJsonbParseBaseILNS_12NullalbeModeE1ELNS_19JsonbParseErrorModeE2EE12execute_implEPNS_15FunctionContextERNS_5BlockERKSt6vectorIjSaIjEEjm
Line
Count
Source
183
3
                        uint32_t result, size_t input_rows_count) const override {
184
3
        auto&& [col_from, col_from_is_const] =
185
3
                unpack_if_const(block.get_by_position(arguments[0]).column);
186
187
3
        if (col_from_is_const && col_from->is_null_at(0)) {
188
0
            auto col_str = ColumnString::create();
189
0
            col_str->insert_default();
190
0
            auto null_map = ColumnUInt8::create(1, 1);
191
0
            auto nullable_col = ColumnNullable::create(std::move(col_str), std::move(null_map));
192
0
            block.get_by_position(result).column =
193
0
                    ColumnConst::create(std::move(nullable_col), input_rows_count);
194
0
            return Status::OK();
195
0
        }
196
197
3
        auto null_map = ColumnUInt8::create(0, 0);
198
3
        bool is_nullable = false;
199
200
3
        switch (nullable_mode) {
201
0
        case NullalbeMode::NULLABLE: {
202
0
            is_nullable = true;
203
0
            break;
204
0
        }
205
3
        case NullalbeMode::FOLLOW_INPUT: {
206
6
            for (auto arg : arguments) {
207
6
                is_nullable |= block.get_by_position(arg).type->is_nullable();
208
6
            }
209
3
            break;
210
0
        }
211
3
        }
212
213
3
        if (is_nullable) {
214
2
            null_map = ColumnUInt8::create(input_rows_count, 0);
215
2
        }
216
217
3
        const ColumnString* col_from_string = nullptr;
218
3
        if (const auto* nullable_col = check_and_get_column<ColumnNullable>(col_from.get())) {
219
2
            VectorizedUtils::update_null_map(null_map->get_data(),
220
2
                                             nullable_col->get_null_map_data(), col_from_is_const);
221
2
            col_from_string =
222
2
                    assert_cast<const ColumnString*>(nullable_col->get_nested_column_ptr().get());
223
2
        } else {
224
1
            col_from_string = assert_cast<const ColumnString*>(col_from.get());
225
1
        }
226
227
3
        StringRef constant_default_value;
228
3
        bool default_value_const = false;
229
3
        bool default_value_null_const = false;
230
3
        ColumnPtr default_value_col;
231
3
        JsonBinaryValue default_jsonb_value_parser;
232
3
        const ColumnString* default_value_str_col = nullptr;
233
3
        const NullMap* default_value_nullmap = nullptr;
234
3
        if constexpr (parse_error_handle_mode == JsonbParseErrorMode::RETURN_VALUE) {
235
3
            auto* state = reinterpret_cast<FunctionJsonbParseState*>(
236
3
                    context->get_function_state(FunctionContext::FRAGMENT_LOCAL));
237
3
            if (state && state->has_const_default_value) {
238
0
                constant_default_value = state->default_value;
239
0
                default_value_null_const = state->default_is_null;
240
0
                default_value_const = true;
241
3
            } else if (arguments.size() > 1) {
242
3
                if (block.get_by_position(arguments[1]).type->get_primitive_type() !=
243
3
                    PrimitiveType::TYPE_JSONB) {
244
1
                    return Status::InvalidArgument(
245
1
                            "{} second argument should be jsonb type, but got {}", get_name(),
246
1
                            block.get_by_position(arguments[1]).type->get_name());
247
1
                }
248
2
                std::tie(default_value_col, default_value_const) =
249
2
                        unpack_if_const(block.get_by_position(arguments[1]).column);
250
2
                if (default_value_const) {
251
0
                    const JsonbDocument* default_value_doc = nullptr;
252
0
                    if (default_value_col->is_null_at(0)) {
253
0
                        default_value_null_const = true;
254
0
                    } else {
255
0
                        auto data = default_value_col->get_data_at(0);
256
0
                        RETURN_IF_ERROR(JsonbDocument::checkAndCreateDocument(data.data, data.size,
257
0
                                                                              &default_value_doc));
258
0
                        constant_default_value = data;
259
0
                    }
260
2
                } else {
261
2
                    if (const auto* nullable_col =
262
2
                                check_and_get_column<ColumnNullable>(default_value_col.get())) {
263
1
                        default_value_str_col = assert_cast<const ColumnString*>(
264
1
                                nullable_col->get_nested_column_ptr().get());
265
1
                        default_value_nullmap = &(nullable_col->get_null_map_data());
266
1
                    } else {
267
1
                        default_value_str_col =
268
1
                                assert_cast<const ColumnString*>(default_value_col.get());
269
1
                    }
270
2
                }
271
2
            } else if (arguments.size() == 1) {
272
                // parse default value '{}' should always success.
273
0
                RETURN_IF_ERROR(default_jsonb_value_parser.from_json_string(std::string("{}")));
274
0
                default_value_const = true;
275
0
                constant_default_value.data = default_jsonb_value_parser.value();
276
0
                constant_default_value.size = default_jsonb_value_parser.size();
277
0
            }
278
3
        }
279
280
2
        auto col_to = ColumnString::create();
281
282
3
        col_to->reserve(input_rows_count);
283
284
3
        auto& null_map_data = null_map->get_data();
285
286
        // parser can be reused for performance
287
3
        JsonBinaryValue jsonb_value;
288
289
1.05k
        for (size_t i = 0; i < input_rows_count; ++i) {
290
1.04k
            if (is_nullable && null_map_data[i]) {
291
1
                col_to->insert_default();
292
1
                continue;
293
1
            }
294
295
1.04k
            auto index = index_check_const(i, col_from_is_const);
296
1.04k
            const auto& val = col_from_string->get_data_at(index);
297
1.04k
            auto st = jsonb_value.from_json_string(val.data, val.size);
298
1.04k
            if (st.ok()) {
299
                // insert jsonb format data
300
1.04k
                col_to->insert_data(jsonb_value.value(), jsonb_value.size());
301
1.04k
            } else {
302
                if constexpr (parse_error_handle_mode == JsonbParseErrorMode::FAIL) {
303
                    return Status::InvalidArgument(
304
                            "Parse json document failed at row {}, error: {}", i, st.to_string());
305
                } else if constexpr (parse_error_handle_mode == JsonbParseErrorMode::RETURN_NULL) {
306
                    null_map_data[i] = 1;
307
                    col_to->insert_default();
308
6
                } else {
309
6
                    if (default_value_const) {
310
0
                        if (default_value_null_const) {
311
0
                            null_map_data[i] = 1;
312
0
                            col_to->insert_default();
313
0
                        } else {
314
0
                            col_to->insert_data(constant_default_value.data,
315
0
                                                constant_default_value.size);
316
0
                        }
317
6
                    } else {
318
6
                        if (default_value_nullmap && (*default_value_nullmap)[i]) {
319
0
                            null_map_data[i] = 1;
320
0
                            col_to->insert_default();
321
0
                            continue;
322
0
                        }
323
6
                        auto value = default_value_str_col->get_data_at(i);
324
6
                        col_to->insert_data(value.data, value.size);
325
6
                    }
326
6
                }
327
6
            }
328
1.04k
        }
329
330
3
        if (is_nullable) {
331
2
            block.replace_by_position(
332
2
                    result, ColumnNullable::create(std::move(col_to), std::move(null_map)));
333
2
        } else {
334
1
            block.replace_by_position(result, std::move(col_to));
335
1
        }
336
337
3
        return Status::OK();
338
3
    }
339
};
340
341
// jsonb_parse return type nullable as input
342
using FunctionJsonbParse =
343
        FunctionJsonbParseBase<NullalbeMode::FOLLOW_INPUT, JsonbParseErrorMode::FAIL>;
344
using FunctionJsonbParseErrorNull =
345
        FunctionJsonbParseBase<NullalbeMode::NULLABLE, JsonbParseErrorMode::RETURN_NULL>;
346
using FunctionJsonbParseErrorValue =
347
        FunctionJsonbParseBase<NullalbeMode::FOLLOW_INPUT, JsonbParseErrorMode::RETURN_VALUE>;
348
349
// func(jsonb, [varchar, varchar, ...]) -> nullable(type)
350
template <typename Impl>
351
class FunctionJsonbExtract : public IFunction {
352
public:
353
    static constexpr auto name = Impl::name;
354
    static constexpr auto alias = Impl::alias;
355
13
    static FunctionPtr create() { return std::make_shared<FunctionJsonbExtract>(); }
_ZN5doris20FunctionJsonbExtractINS_13JsonbTypeImplEE6createEv
Line
Count
Source
355
2
    static FunctionPtr create() { return std::make_shared<FunctionJsonbExtract>(); }
_ZN5doris20FunctionJsonbExtractINS_18JsonbExtractIsnullEE6createEv
Line
Count
Source
355
2
    static FunctionPtr create() { return std::make_shared<FunctionJsonbExtract>(); }
_ZN5doris20FunctionJsonbExtractINS_17JsonbExtractJsonbEE6createEv
Line
Count
Source
355
7
    static FunctionPtr create() { return std::make_shared<FunctionJsonbExtract>(); }
_ZN5doris20FunctionJsonbExtractINS_25JsonbExtractJsonbNoQuotesEE6createEv
Line
Count
Source
355
2
    static FunctionPtr create() { return std::make_shared<FunctionJsonbExtract>(); }
356
0
    String get_name() const override { return name; }
Unexecuted instantiation: _ZNK5doris20FunctionJsonbExtractINS_13JsonbTypeImplEE8get_nameB5cxx11Ev
Unexecuted instantiation: _ZNK5doris20FunctionJsonbExtractINS_18JsonbExtractIsnullEE8get_nameB5cxx11Ev
Unexecuted instantiation: _ZNK5doris20FunctionJsonbExtractINS_17JsonbExtractJsonbEE8get_nameB5cxx11Ev
Unexecuted instantiation: _ZNK5doris20FunctionJsonbExtractINS_25JsonbExtractJsonbNoQuotesEE8get_nameB5cxx11Ev
357
10
    bool is_variadic() const override { return true; }
_ZNK5doris20FunctionJsonbExtractINS_13JsonbTypeImplEE11is_variadicEv
Line
Count
Source
357
1
    bool is_variadic() const override { return true; }
_ZNK5doris20FunctionJsonbExtractINS_18JsonbExtractIsnullEE11is_variadicEv
Line
Count
Source
357
1
    bool is_variadic() const override { return true; }
_ZNK5doris20FunctionJsonbExtractINS_17JsonbExtractJsonbEE11is_variadicEv
Line
Count
Source
357
7
    bool is_variadic() const override { return true; }
_ZNK5doris20FunctionJsonbExtractINS_25JsonbExtractJsonbNoQuotesEE11is_variadicEv
Line
Count
Source
357
1
    bool is_variadic() const override { return true; }
358
1
    size_t get_number_of_arguments() const override { return 0; }
Unexecuted instantiation: _ZNK5doris20FunctionJsonbExtractINS_13JsonbTypeImplEE23get_number_of_argumentsEv
Unexecuted instantiation: _ZNK5doris20FunctionJsonbExtractINS_18JsonbExtractIsnullEE23get_number_of_argumentsEv
_ZNK5doris20FunctionJsonbExtractINS_17JsonbExtractJsonbEE23get_number_of_argumentsEv
Line
Count
Source
358
1
    size_t get_number_of_arguments() const override { return 0; }
Unexecuted instantiation: _ZNK5doris20FunctionJsonbExtractINS_25JsonbExtractJsonbNoQuotesEE23get_number_of_argumentsEv
359
10
    bool use_default_implementation_for_nulls() const override { return false; }
Unexecuted instantiation: _ZNK5doris20FunctionJsonbExtractINS_13JsonbTypeImplEE36use_default_implementation_for_nullsEv
Unexecuted instantiation: _ZNK5doris20FunctionJsonbExtractINS_18JsonbExtractIsnullEE36use_default_implementation_for_nullsEv
_ZNK5doris20FunctionJsonbExtractINS_17JsonbExtractJsonbEE36use_default_implementation_for_nullsEv
Line
Count
Source
359
10
    bool use_default_implementation_for_nulls() const override { return false; }
Unexecuted instantiation: _ZNK5doris20FunctionJsonbExtractINS_25JsonbExtractJsonbNoQuotesEE36use_default_implementation_for_nullsEv
360
5
    DataTypePtr get_return_type_impl(const DataTypes& arguments) const override {
361
5
        return make_nullable(std::make_shared<typename Impl::ReturnType>());
362
5
    }
Unexecuted instantiation: _ZNK5doris20FunctionJsonbExtractINS_13JsonbTypeImplEE20get_return_type_implERKSt6vectorISt10shared_ptrIKNS_9IDataTypeEESaIS7_EE
Unexecuted instantiation: _ZNK5doris20FunctionJsonbExtractINS_18JsonbExtractIsnullEE20get_return_type_implERKSt6vectorISt10shared_ptrIKNS_9IDataTypeEESaIS7_EE
_ZNK5doris20FunctionJsonbExtractINS_17JsonbExtractJsonbEE20get_return_type_implERKSt6vectorISt10shared_ptrIKNS_9IDataTypeEESaIS7_EE
Line
Count
Source
360
5
    DataTypePtr get_return_type_impl(const DataTypes& arguments) const override {
361
5
        return make_nullable(std::make_shared<typename Impl::ReturnType>());
362
5
    }
Unexecuted instantiation: _ZNK5doris20FunctionJsonbExtractINS_25JsonbExtractJsonbNoQuotesEE20get_return_type_implERKSt6vectorISt10shared_ptrIKNS_9IDataTypeEESaIS7_EE
363
4
    DataTypes get_variadic_argument_types_impl() const override {
364
        if constexpr (HasGetVariadicArgumentTypesImpl<Impl>) {
365
            return Impl::get_variadic_argument_types_impl();
366
4
        } else {
367
4
            return {};
368
4
        }
369
4
    }
_ZNK5doris20FunctionJsonbExtractINS_13JsonbTypeImplEE32get_variadic_argument_types_implEv
Line
Count
Source
363
1
    DataTypes get_variadic_argument_types_impl() const override {
364
        if constexpr (HasGetVariadicArgumentTypesImpl<Impl>) {
365
            return Impl::get_variadic_argument_types_impl();
366
1
        } else {
367
1
            return {};
368
1
        }
369
1
    }
_ZNK5doris20FunctionJsonbExtractINS_18JsonbExtractIsnullEE32get_variadic_argument_types_implEv
Line
Count
Source
363
1
    DataTypes get_variadic_argument_types_impl() const override {
364
        if constexpr (HasGetVariadicArgumentTypesImpl<Impl>) {
365
            return Impl::get_variadic_argument_types_impl();
366
1
        } else {
367
1
            return {};
368
1
        }
369
1
    }
_ZNK5doris20FunctionJsonbExtractINS_17JsonbExtractJsonbEE32get_variadic_argument_types_implEv
Line
Count
Source
363
1
    DataTypes get_variadic_argument_types_impl() const override {
364
        if constexpr (HasGetVariadicArgumentTypesImpl<Impl>) {
365
            return Impl::get_variadic_argument_types_impl();
366
1
        } else {
367
1
            return {};
368
1
        }
369
1
    }
_ZNK5doris20FunctionJsonbExtractINS_25JsonbExtractJsonbNoQuotesEE32get_variadic_argument_types_implEv
Line
Count
Source
363
1
    DataTypes get_variadic_argument_types_impl() const override {
364
        if constexpr (HasGetVariadicArgumentTypesImpl<Impl>) {
365
            return Impl::get_variadic_argument_types_impl();
366
1
        } else {
367
1
            return {};
368
1
        }
369
1
    }
370
371
    Status execute_impl(FunctionContext* context, Block& block, const ColumnNumbers& arguments,
372
5
                        uint32_t result, size_t input_rows_count) const override {
373
5
        DORIS_CHECK_GE(arguments.size(), 2);
374
375
5
        ColumnPtr jsonb_data_column;
376
5
        bool jsonb_data_const = false;
377
5
        const NullMap* data_null_map = nullptr;
378
379
5
        if (block.get_by_position(arguments[0]).type->get_primitive_type() !=
380
5
            PrimitiveType::TYPE_JSONB) {
381
1
            return Status::InvalidArgument(
382
1
                    "jsonb_extract first argument should be json type, but got {}",
383
1
                    block.get_by_position(arguments[0]).type->get_name());
384
1
        }
385
386
        // prepare jsonb data column
387
4
        std::tie(jsonb_data_column, jsonb_data_const) =
388
4
                unpack_if_const(block.get_by_position(arguments[0]).column);
389
4
        if (const auto* nullable_column =
390
4
                    check_and_get_column<ColumnNullable>(jsonb_data_column.get())) {
391
4
            jsonb_data_column = nullable_column->get_nested_column_ptr();
392
4
            data_null_map = &nullable_column->get_null_map_data();
393
4
        }
394
4
        const auto& ldata = assert_cast<const ColumnString*>(jsonb_data_column.get())->get_chars();
395
4
        const auto& loffsets =
396
4
                assert_cast<const ColumnString*>(jsonb_data_column.get())->get_offsets();
397
398
        // prepare parse path column prepare
399
4
        std::vector<const ColumnString*> jsonb_path_columns;
400
4
        std::vector<bool> path_const(arguments.size() - 1);
401
4
        std::vector<const NullMap*> path_null_maps(arguments.size() - 1, nullptr);
402
8
        for (int i = 0; i < arguments.size() - 1; ++i) {
403
4
            ColumnPtr path_column;
404
4
            bool is_const = false;
405
4
            std::tie(path_column, is_const) =
406
4
                    unpack_if_const(block.get_by_position(arguments[i + 1]).column);
407
4
            path_const[i] = is_const;
408
4
            if (const auto* nullable_column =
409
4
                        check_and_get_column<ColumnNullable>(path_column.get())) {
410
4
                path_column = nullable_column->get_nested_column_ptr();
411
4
                path_null_maps[i] = &nullable_column->get_null_map_data();
412
4
            }
413
4
            jsonb_path_columns.push_back(assert_cast<const ColumnString*>(path_column.get()));
414
4
        }
415
416
4
        auto null_map = ColumnUInt8::create(input_rows_count, 0);
417
4
        auto res = Impl::ColumnType::create();
418
419
        // execute Impl
420
        if constexpr (std::is_same_v<typename Impl::ReturnType, DataTypeString> ||
421
4
                      std::is_same_v<typename Impl::ReturnType, DataTypeJsonb>) {
422
4
            auto& res_data = res->get_chars();
423
4
            auto& res_offsets = res->get_offsets();
424
4
            RETURN_IF_ERROR(Impl::vector_vector_v2(
425
4
                    context, ldata, loffsets, data_null_map, jsonb_data_const, jsonb_path_columns,
426
4
                    path_null_maps, path_const, res_data, res_offsets, null_map->get_data()));
427
4
        } else {
428
            // not support other extract type for now (e.g. int, double, ...)
429
0
            DORIS_CHECK_EQ(jsonb_path_columns.size(), 1);
430
0
            const auto& rdata = jsonb_path_columns[0]->get_chars();
431
0
            const auto& roffsets = jsonb_path_columns[0]->get_offsets();
432
433
0
            auto create_all_null_result = [&]() {
434
0
                res = Impl::ColumnType::create();
435
0
                res->insert_default();
436
0
                auto nullable_column =
437
0
                        ColumnNullable::create(std::move(res), ColumnUInt8::create(1, 1));
438
0
                auto const_column =
439
0
                        ColumnConst::create(std::move(nullable_column), input_rows_count);
440
0
                block.get_by_position(result).column = std::move(const_column);
441
0
                return Status::OK();
442
0
            };
443
444
0
            if (jsonb_data_const) {
445
0
                if (data_null_map && (*data_null_map)[0]) {
446
0
                    return create_all_null_result();
447
0
                }
448
449
0
                RETURN_IF_ERROR(Impl::scalar_vector(context, jsonb_data_column->get_data_at(0),
450
0
                                                    rdata, roffsets, path_null_maps[0],
451
0
                                                    res->get_data(), null_map->get_data()));
452
0
            } else if (path_const[0]) {
453
0
                if (path_null_maps[0] && (*path_null_maps[0])[0]) {
454
0
                    return create_all_null_result();
455
0
                }
456
0
                RETURN_IF_ERROR(Impl::vector_scalar(context, ldata, loffsets, data_null_map,
457
0
                                                    jsonb_path_columns[0]->get_data_at(0),
458
0
                                                    res->get_data(), null_map->get_data()));
459
0
            } else {
460
0
                RETURN_IF_ERROR(Impl::vector_vector(context, ldata, loffsets, data_null_map, rdata,
461
0
                                                    roffsets, path_null_maps[0], res->get_data(),
462
0
                                                    null_map->get_data()));
463
0
            }
464
0
        }
465
466
4
        block.get_by_position(result).column =
467
4
                ColumnNullable::create(std::move(res), std::move(null_map));
468
4
        return Status::OK();
469
5
    }
Unexecuted instantiation: _ZNK5doris20FunctionJsonbExtractINS_13JsonbTypeImplEE12execute_implEPNS_15FunctionContextERNS_5BlockERKSt6vectorIjSaIjEEjm
Unexecuted instantiation: _ZNK5doris20FunctionJsonbExtractINS_18JsonbExtractIsnullEE12execute_implEPNS_15FunctionContextERNS_5BlockERKSt6vectorIjSaIjEEjm
_ZNK5doris20FunctionJsonbExtractINS_17JsonbExtractJsonbEE12execute_implEPNS_15FunctionContextERNS_5BlockERKSt6vectorIjSaIjEEjm
Line
Count
Source
372
5
                        uint32_t result, size_t input_rows_count) const override {
373
5
        DORIS_CHECK_GE(arguments.size(), 2);
374
375
5
        ColumnPtr jsonb_data_column;
376
5
        bool jsonb_data_const = false;
377
5
        const NullMap* data_null_map = nullptr;
378
379
5
        if (block.get_by_position(arguments[0]).type->get_primitive_type() !=
380
5
            PrimitiveType::TYPE_JSONB) {
381
1
            return Status::InvalidArgument(
382
1
                    "jsonb_extract first argument should be json type, but got {}",
383
1
                    block.get_by_position(arguments[0]).type->get_name());
384
1
        }
385
386
        // prepare jsonb data column
387
4
        std::tie(jsonb_data_column, jsonb_data_const) =
388
4
                unpack_if_const(block.get_by_position(arguments[0]).column);
389
4
        if (const auto* nullable_column =
390
4
                    check_and_get_column<ColumnNullable>(jsonb_data_column.get())) {
391
4
            jsonb_data_column = nullable_column->get_nested_column_ptr();
392
4
            data_null_map = &nullable_column->get_null_map_data();
393
4
        }
394
4
        const auto& ldata = assert_cast<const ColumnString*>(jsonb_data_column.get())->get_chars();
395
4
        const auto& loffsets =
396
4
                assert_cast<const ColumnString*>(jsonb_data_column.get())->get_offsets();
397
398
        // prepare parse path column prepare
399
4
        std::vector<const ColumnString*> jsonb_path_columns;
400
4
        std::vector<bool> path_const(arguments.size() - 1);
401
4
        std::vector<const NullMap*> path_null_maps(arguments.size() - 1, nullptr);
402
8
        for (int i = 0; i < arguments.size() - 1; ++i) {
403
4
            ColumnPtr path_column;
404
4
            bool is_const = false;
405
4
            std::tie(path_column, is_const) =
406
4
                    unpack_if_const(block.get_by_position(arguments[i + 1]).column);
407
4
            path_const[i] = is_const;
408
4
            if (const auto* nullable_column =
409
4
                        check_and_get_column<ColumnNullable>(path_column.get())) {
410
4
                path_column = nullable_column->get_nested_column_ptr();
411
4
                path_null_maps[i] = &nullable_column->get_null_map_data();
412
4
            }
413
4
            jsonb_path_columns.push_back(assert_cast<const ColumnString*>(path_column.get()));
414
4
        }
415
416
4
        auto null_map = ColumnUInt8::create(input_rows_count, 0);
417
4
        auto res = Impl::ColumnType::create();
418
419
        // execute Impl
420
        if constexpr (std::is_same_v<typename Impl::ReturnType, DataTypeString> ||
421
4
                      std::is_same_v<typename Impl::ReturnType, DataTypeJsonb>) {
422
4
            auto& res_data = res->get_chars();
423
4
            auto& res_offsets = res->get_offsets();
424
4
            RETURN_IF_ERROR(Impl::vector_vector_v2(
425
4
                    context, ldata, loffsets, data_null_map, jsonb_data_const, jsonb_path_columns,
426
4
                    path_null_maps, path_const, res_data, res_offsets, null_map->get_data()));
427
        } else {
428
            // not support other extract type for now (e.g. int, double, ...)
429
            DORIS_CHECK_EQ(jsonb_path_columns.size(), 1);
430
            const auto& rdata = jsonb_path_columns[0]->get_chars();
431
            const auto& roffsets = jsonb_path_columns[0]->get_offsets();
432
433
            auto create_all_null_result = [&]() {
434
                res = Impl::ColumnType::create();
435
                res->insert_default();
436
                auto nullable_column =
437
                        ColumnNullable::create(std::move(res), ColumnUInt8::create(1, 1));
438
                auto const_column =
439
                        ColumnConst::create(std::move(nullable_column), input_rows_count);
440
                block.get_by_position(result).column = std::move(const_column);
441
                return Status::OK();
442
            };
443
444
            if (jsonb_data_const) {
445
                if (data_null_map && (*data_null_map)[0]) {
446
                    return create_all_null_result();
447
                }
448
449
                RETURN_IF_ERROR(Impl::scalar_vector(context, jsonb_data_column->get_data_at(0),
450
                                                    rdata, roffsets, path_null_maps[0],
451
                                                    res->get_data(), null_map->get_data()));
452
            } else if (path_const[0]) {
453
                if (path_null_maps[0] && (*path_null_maps[0])[0]) {
454
                    return create_all_null_result();
455
                }
456
                RETURN_IF_ERROR(Impl::vector_scalar(context, ldata, loffsets, data_null_map,
457
                                                    jsonb_path_columns[0]->get_data_at(0),
458
                                                    res->get_data(), null_map->get_data()));
459
            } else {
460
                RETURN_IF_ERROR(Impl::vector_vector(context, ldata, loffsets, data_null_map, rdata,
461
                                                    roffsets, path_null_maps[0], res->get_data(),
462
                                                    null_map->get_data()));
463
            }
464
        }
465
466
4
        block.get_by_position(result).column =
467
4
                ColumnNullable::create(std::move(res), std::move(null_map));
468
4
        return Status::OK();
469
5
    }
Unexecuted instantiation: _ZNK5doris20FunctionJsonbExtractINS_25JsonbExtractJsonbNoQuotesEE12execute_implEPNS_15FunctionContextERNS_5BlockERKSt6vectorIjSaIjEEjm
470
};
471
472
class FunctionJsonbKeys : public IFunction {
473
public:
474
    static constexpr auto name = "json_keys";
475
    static constexpr auto alias = "jsonb_keys";
476
4
    static FunctionPtr create() { return std::make_shared<FunctionJsonbKeys>(); }
477
0
    String get_name() const override { return name; }
478
3
    bool is_variadic() const override { return true; }
479
0
    size_t get_number_of_arguments() const override { return 0; }
480
481
4
    bool use_default_implementation_for_nulls() const override { return false; }
482
483
2
    DataTypePtr get_return_type_impl(const DataTypes& arguments) const override {
484
2
        return make_nullable(
485
2
                std::make_shared<DataTypeArray>(make_nullable(std::make_shared<DataTypeString>())));
486
2
    }
487
488
    Status execute_impl(FunctionContext* context, Block& block, const ColumnNumbers& arguments,
489
2
                        uint32_t result, size_t input_rows_count) const override {
490
2
        DORIS_CHECK_GE(arguments.size(), 1);
491
2
        DORIS_CHECK(arguments.size() == 1 || arguments.size() == 2)
492
0
                << "json_keys should have 1 or 2 arguments, but got " << arguments.size();
493
494
2
        const NullMap* data_null_map = nullptr;
495
2
        const ColumnString* col_from_string = nullptr;
496
        // prepare jsonb data column
497
2
        auto&& [jsonb_data_column, json_data_const] =
498
2
                unpack_if_const(block.get_by_position(arguments[0]).column);
499
2
        if (const auto* nullable = check_and_get_column<ColumnNullable>(jsonb_data_column.get())) {
500
0
            col_from_string =
501
0
                    assert_cast<const ColumnString*>(nullable->get_nested_column_ptr().get());
502
0
            data_null_map = &nullable->get_null_map_data();
503
2
        } else {
504
2
            col_from_string = assert_cast<const ColumnString*>(jsonb_data_column.get());
505
2
        }
506
507
        // prepare parse path column prepare, maybe we do not have path column
508
2
        ColumnPtr jsonb_path_column = nullptr;
509
2
        const ColumnString* jsonb_path_col = nullptr;
510
2
        bool path_const = false;
511
2
        const NullMap* path_null_map = nullptr;
512
2
        if (arguments.size() == 2) {
513
            // we have should have a ColumnString for path
514
2
            std::tie(jsonb_path_column, path_const) =
515
2
                    unpack_if_const(block.get_by_position(arguments[1]).column);
516
2
            if (const auto* nullable =
517
2
                        check_and_get_column<ColumnNullable>(jsonb_path_column.get())) {
518
0
                jsonb_path_column = nullable->get_nested_column_ptr();
519
0
                path_null_map = &nullable->get_null_map_data();
520
0
            }
521
2
            jsonb_path_col = check_and_get_column<ColumnString>(jsonb_path_column.get());
522
2
        }
523
524
2
        auto null_map = ColumnUInt8::create(input_rows_count, 0);
525
2
        NullMap& res_null_map = null_map->get_data();
526
527
2
        auto dst_arr = ColumnArray::create(
528
2
                ColumnNullable::create(ColumnString::create(), ColumnUInt8::create()),
529
2
                ColumnArray::ColumnOffsets::create());
530
2
        auto& dst_nested_column = assert_cast<ColumnNullable&>(dst_arr->get_data());
531
532
2
        Status st = std::visit(
533
2
                [&](auto data_const, auto has_path, auto path_const) {
534
2
                    return inner_loop_impl<data_const, has_path, path_const>(
535
2
                            input_rows_count, *dst_arr, dst_nested_column, res_null_map,
536
2
                            *col_from_string, data_null_map, jsonb_path_col, path_null_map);
537
2
                },
Unexecuted instantiation: _ZZNK5doris17FunctionJsonbKeys12execute_implEPNS_15FunctionContextERNS_5BlockERKSt6vectorIjSaIjEEjmENKUlT_T0_T1_E_clISt17integral_constantIbLb0EESG_SG_EEDaSA_SB_SC_
Unexecuted instantiation: _ZZNK5doris17FunctionJsonbKeys12execute_implEPNS_15FunctionContextERNS_5BlockERKSt6vectorIjSaIjEEjmENKUlT_T0_T1_E_clISt17integral_constantIbLb0EESG_SF_IbLb1EEEEDaSA_SB_SC_
_ZZNK5doris17FunctionJsonbKeys12execute_implEPNS_15FunctionContextERNS_5BlockERKSt6vectorIjSaIjEEjmENKUlT_T0_T1_E_clISt17integral_constantIbLb0EESF_IbLb1EESG_EEDaSA_SB_SC_
Line
Count
Source
533
1
                [&](auto data_const, auto has_path, auto path_const) {
534
1
                    return inner_loop_impl<data_const, has_path, path_const>(
535
1
                            input_rows_count, *dst_arr, dst_nested_column, res_null_map,
536
1
                            *col_from_string, data_null_map, jsonb_path_col, path_null_map);
537
1
                },
_ZZNK5doris17FunctionJsonbKeys12execute_implEPNS_15FunctionContextERNS_5BlockERKSt6vectorIjSaIjEEjmENKUlT_T0_T1_E_clISt17integral_constantIbLb0EESF_IbLb1EESH_EEDaSA_SB_SC_
Line
Count
Source
533
1
                [&](auto data_const, auto has_path, auto path_const) {
534
1
                    return inner_loop_impl<data_const, has_path, path_const>(
535
1
                            input_rows_count, *dst_arr, dst_nested_column, res_null_map,
536
1
                            *col_from_string, data_null_map, jsonb_path_col, path_null_map);
537
1
                },
Unexecuted instantiation: _ZZNK5doris17FunctionJsonbKeys12execute_implEPNS_15FunctionContextERNS_5BlockERKSt6vectorIjSaIjEEjmENKUlT_T0_T1_E_clISt17integral_constantIbLb1EESF_IbLb0EESH_EEDaSA_SB_SC_
Unexecuted instantiation: _ZZNK5doris17FunctionJsonbKeys12execute_implEPNS_15FunctionContextERNS_5BlockERKSt6vectorIjSaIjEEjmENKUlT_T0_T1_E_clISt17integral_constantIbLb1EESF_IbLb0EESG_EEDaSA_SB_SC_
Unexecuted instantiation: _ZZNK5doris17FunctionJsonbKeys12execute_implEPNS_15FunctionContextERNS_5BlockERKSt6vectorIjSaIjEEjmENKUlT_T0_T1_E_clISt17integral_constantIbLb1EESG_SF_IbLb0EEEEDaSA_SB_SC_
Unexecuted instantiation: _ZZNK5doris17FunctionJsonbKeys12execute_implEPNS_15FunctionContextERNS_5BlockERKSt6vectorIjSaIjEEjmENKUlT_T0_T1_E_clISt17integral_constantIbLb1EESG_SG_EEDaSA_SB_SC_
538
2
                make_bool_variant(json_data_const), make_bool_variant(jsonb_path_column),
539
2
                make_bool_variant(path_const));
540
2
        if (!st.ok()) {
541
2
            return st;
542
2
        }
543
0
        block.get_by_position(result).column =
544
0
                ColumnNullable::create(std::move(dst_arr), std::move(null_map));
545
0
        return st;
546
2
    }
547
548
private:
549
    template <bool JSONB_DATA_CONST, bool JSONB_PATH_PARAM, bool JSON_PATH_CONST>
550
    static ALWAYS_INLINE Status inner_loop_impl(size_t input_rows_count, ColumnArray& dst_arr,
551
                                                ColumnNullable& dst_nested_column,
552
                                                NullMap& res_null_map,
553
                                                const ColumnString& col_from_string,
554
                                                const NullMap* jsonb_data_nullmap,
555
                                                const ColumnString* jsonb_path_column,
556
2
                                                const NullMap* path_null_map) {
557
        // if path is const, we just need to parse it once
558
2
        JsonbPath const_path;
559
2
        if constexpr (JSONB_PATH_PARAM && JSON_PATH_CONST) {
560
1
            StringRef r_raw_ref = jsonb_path_column->get_data_at(0);
561
1
            if (!const_path.seek(r_raw_ref.data, r_raw_ref.size)) {
562
0
                return Status::InvalidArgument("Json path error: Invalid Json Path for value: {}",
563
0
                                               r_raw_ref.to_string());
564
0
            }
565
566
1
            if (const_path.is_wildcard() || const_path.is_supper_wildcard()) {
567
1
                return Status::InvalidJsonPath(
568
1
                        "In this situation, path expressions may not contain the * and ** tokens "
569
1
                        "or an array range.");
570
1
            }
571
1
        }
572
573
4
        for (size_t i = 0; i < input_rows_count; ++i) {
574
2
            auto index = index_check_const(i, JSONB_DATA_CONST);
575
            // if jsonb data is null or path column is null , we should return null
576
2
            if (jsonb_data_nullmap && (*jsonb_data_nullmap)[index]) {
577
0
                res_null_map[i] = 1;
578
0
                dst_arr.insert_default();
579
0
                continue;
580
0
            }
581
2
            if constexpr (JSONB_PATH_PARAM && !JSON_PATH_CONST) {
582
2
                if (path_null_map && (*path_null_map)[i]) {
583
0
                    res_null_map[i] = 1;
584
0
                    dst_arr.insert_default();
585
0
                    continue;
586
0
                }
587
2
            }
588
589
2
            auto json_data = col_from_string.get_data_at(index);
590
2
            const JsonbDocument* doc = nullptr;
591
2
            auto st = JsonbDocument::checkAndCreateDocument(json_data.data, json_data.size, &doc);
592
2
            if (!st.ok() || !doc || !doc->getValue()) [[unlikely]] {
593
0
                dst_arr.clear();
594
0
                return Status::InvalidArgument("jsonb data is invalid");
595
0
            }
596
2
            const JsonbValue* obj_val;
597
2
            JsonbFindResult find_result;
598
2
            if constexpr (JSONB_PATH_PARAM) {
599
2
                if constexpr (!JSON_PATH_CONST) {
600
2
                    auto data = jsonb_path_column->get_data_at(i);
601
2
                    JsonbPath path;
602
2
                    if (!path.seek(data.data, data.size)) {
603
0
                        return Status::InvalidArgument(
604
0
                                "Json path error: Invalid Json Path for value: {} at row: {}",
605
0
                                std::string_view(data.data, data.size), i);
606
0
                    }
607
608
2
                    if (path.is_wildcard() || path.is_supper_wildcard()) {
609
1
                        return Status::InvalidJsonPath(
610
1
                                "In this situation, path expressions may not contain the * and ** "
611
1
                                "tokens "
612
1
                                "or an array range. at row: {}",
613
1
                                i);
614
1
                    }
615
1
                    find_result = doc->getValue()->findValue(path);
616
1
                } else {
617
0
                    find_result = doc->getValue()->findValue(const_path);
618
0
                }
619
0
                obj_val = find_result.value;
620
2
            } else {
621
0
                obj_val = doc->getValue();
622
0
            }
623
624
2
            if (!obj_val || !obj_val->isObject()) {
625
                // if jsonb data is not object we should return null
626
0
                res_null_map[i] = 1;
627
0
                dst_arr.insert_default();
628
0
                continue;
629
0
            }
630
2
            const auto* obj = obj_val->unpack<ObjectVal>();
631
2
            for (const auto& it : *obj) {
632
1
                dst_nested_column.insert_data(it.getKeyStr(), it.klen());
633
1
            }
634
2
            dst_arr.get_offsets().push_back(dst_nested_column.size());
635
2
        } //for
636
2
        return Status::OK();
637
2
    }
Unexecuted instantiation: _ZN5doris17FunctionJsonbKeys15inner_loop_implILb0ELb0ELb0EEENS_6StatusEmRNS_11ColumnArrayERNS_14ColumnNullableERNS_8PODArrayIhLm4096ENS_9AllocatorILb0ELb0ELb0ENS_22DefaultMemoryAllocatorELb1EEELm16ELm15EEERKNS_9ColumnStrIjEEPKSB_PSF_SI_
Unexecuted instantiation: _ZN5doris17FunctionJsonbKeys15inner_loop_implILb0ELb0ELb1EEENS_6StatusEmRNS_11ColumnArrayERNS_14ColumnNullableERNS_8PODArrayIhLm4096ENS_9AllocatorILb0ELb0ELb0ENS_22DefaultMemoryAllocatorELb1EEELm16ELm15EEERKNS_9ColumnStrIjEEPKSB_PSF_SI_
_ZN5doris17FunctionJsonbKeys15inner_loop_implILb0ELb1ELb0EEENS_6StatusEmRNS_11ColumnArrayERNS_14ColumnNullableERNS_8PODArrayIhLm4096ENS_9AllocatorILb0ELb0ELb0ENS_22DefaultMemoryAllocatorELb1EEELm16ELm15EEERKNS_9ColumnStrIjEEPKSB_PSF_SI_
Line
Count
Source
556
1
                                                const NullMap* path_null_map) {
557
        // if path is const, we just need to parse it once
558
1
        JsonbPath const_path;
559
        if constexpr (JSONB_PATH_PARAM && JSON_PATH_CONST) {
560
            StringRef r_raw_ref = jsonb_path_column->get_data_at(0);
561
            if (!const_path.seek(r_raw_ref.data, r_raw_ref.size)) {
562
                return Status::InvalidArgument("Json path error: Invalid Json Path for value: {}",
563
                                               r_raw_ref.to_string());
564
            }
565
566
            if (const_path.is_wildcard() || const_path.is_supper_wildcard()) {
567
                return Status::InvalidJsonPath(
568
                        "In this situation, path expressions may not contain the * and ** tokens "
569
                        "or an array range.");
570
            }
571
        }
572
573
3
        for (size_t i = 0; i < input_rows_count; ++i) {
574
2
            auto index = index_check_const(i, JSONB_DATA_CONST);
575
            // if jsonb data is null or path column is null , we should return null
576
2
            if (jsonb_data_nullmap && (*jsonb_data_nullmap)[index]) {
577
0
                res_null_map[i] = 1;
578
0
                dst_arr.insert_default();
579
0
                continue;
580
0
            }
581
2
            if constexpr (JSONB_PATH_PARAM && !JSON_PATH_CONST) {
582
2
                if (path_null_map && (*path_null_map)[i]) {
583
0
                    res_null_map[i] = 1;
584
0
                    dst_arr.insert_default();
585
0
                    continue;
586
0
                }
587
2
            }
588
589
2
            auto json_data = col_from_string.get_data_at(index);
590
2
            const JsonbDocument* doc = nullptr;
591
2
            auto st = JsonbDocument::checkAndCreateDocument(json_data.data, json_data.size, &doc);
592
2
            if (!st.ok() || !doc || !doc->getValue()) [[unlikely]] {
593
0
                dst_arr.clear();
594
0
                return Status::InvalidArgument("jsonb data is invalid");
595
0
            }
596
2
            const JsonbValue* obj_val;
597
2
            JsonbFindResult find_result;
598
2
            if constexpr (JSONB_PATH_PARAM) {
599
2
                if constexpr (!JSON_PATH_CONST) {
600
2
                    auto data = jsonb_path_column->get_data_at(i);
601
2
                    JsonbPath path;
602
2
                    if (!path.seek(data.data, data.size)) {
603
0
                        return Status::InvalidArgument(
604
0
                                "Json path error: Invalid Json Path for value: {} at row: {}",
605
0
                                std::string_view(data.data, data.size), i);
606
0
                    }
607
608
2
                    if (path.is_wildcard() || path.is_supper_wildcard()) {
609
1
                        return Status::InvalidJsonPath(
610
1
                                "In this situation, path expressions may not contain the * and ** "
611
1
                                "tokens "
612
1
                                "or an array range. at row: {}",
613
1
                                i);
614
1
                    }
615
1
                    find_result = doc->getValue()->findValue(path);
616
                } else {
617
                    find_result = doc->getValue()->findValue(const_path);
618
                }
619
0
                obj_val = find_result.value;
620
            } else {
621
                obj_val = doc->getValue();
622
            }
623
624
2
            if (!obj_val || !obj_val->isObject()) {
625
                // if jsonb data is not object we should return null
626
0
                res_null_map[i] = 1;
627
0
                dst_arr.insert_default();
628
0
                continue;
629
0
            }
630
2
            const auto* obj = obj_val->unpack<ObjectVal>();
631
2
            for (const auto& it : *obj) {
632
1
                dst_nested_column.insert_data(it.getKeyStr(), it.klen());
633
1
            }
634
2
            dst_arr.get_offsets().push_back(dst_nested_column.size());
635
2
        } //for
636
1
        return Status::OK();
637
1
    }
_ZN5doris17FunctionJsonbKeys15inner_loop_implILb0ELb1ELb1EEENS_6StatusEmRNS_11ColumnArrayERNS_14ColumnNullableERNS_8PODArrayIhLm4096ENS_9AllocatorILb0ELb0ELb0ENS_22DefaultMemoryAllocatorELb1EEELm16ELm15EEERKNS_9ColumnStrIjEEPKSB_PSF_SI_
Line
Count
Source
556
1
                                                const NullMap* path_null_map) {
557
        // if path is const, we just need to parse it once
558
1
        JsonbPath const_path;
559
1
        if constexpr (JSONB_PATH_PARAM && JSON_PATH_CONST) {
560
1
            StringRef r_raw_ref = jsonb_path_column->get_data_at(0);
561
1
            if (!const_path.seek(r_raw_ref.data, r_raw_ref.size)) {
562
0
                return Status::InvalidArgument("Json path error: Invalid Json Path for value: {}",
563
0
                                               r_raw_ref.to_string());
564
0
            }
565
566
1
            if (const_path.is_wildcard() || const_path.is_supper_wildcard()) {
567
1
                return Status::InvalidJsonPath(
568
1
                        "In this situation, path expressions may not contain the * and ** tokens "
569
1
                        "or an array range.");
570
1
            }
571
1
        }
572
573
1
        for (size_t i = 0; i < input_rows_count; ++i) {
574
0
            auto index = index_check_const(i, JSONB_DATA_CONST);
575
            // if jsonb data is null or path column is null , we should return null
576
0
            if (jsonb_data_nullmap && (*jsonb_data_nullmap)[index]) {
577
0
                res_null_map[i] = 1;
578
0
                dst_arr.insert_default();
579
0
                continue;
580
0
            }
581
            if constexpr (JSONB_PATH_PARAM && !JSON_PATH_CONST) {
582
                if (path_null_map && (*path_null_map)[i]) {
583
                    res_null_map[i] = 1;
584
                    dst_arr.insert_default();
585
                    continue;
586
                }
587
            }
588
589
0
            auto json_data = col_from_string.get_data_at(index);
590
0
            const JsonbDocument* doc = nullptr;
591
0
            auto st = JsonbDocument::checkAndCreateDocument(json_data.data, json_data.size, &doc);
592
0
            if (!st.ok() || !doc || !doc->getValue()) [[unlikely]] {
593
0
                dst_arr.clear();
594
0
                return Status::InvalidArgument("jsonb data is invalid");
595
0
            }
596
0
            const JsonbValue* obj_val;
597
0
            JsonbFindResult find_result;
598
0
            if constexpr (JSONB_PATH_PARAM) {
599
                if constexpr (!JSON_PATH_CONST) {
600
                    auto data = jsonb_path_column->get_data_at(i);
601
                    JsonbPath path;
602
                    if (!path.seek(data.data, data.size)) {
603
                        return Status::InvalidArgument(
604
                                "Json path error: Invalid Json Path for value: {} at row: {}",
605
                                std::string_view(data.data, data.size), i);
606
                    }
607
608
                    if (path.is_wildcard() || path.is_supper_wildcard()) {
609
                        return Status::InvalidJsonPath(
610
                                "In this situation, path expressions may not contain the * and ** "
611
                                "tokens "
612
                                "or an array range. at row: {}",
613
                                i);
614
                    }
615
                    find_result = doc->getValue()->findValue(path);
616
0
                } else {
617
0
                    find_result = doc->getValue()->findValue(const_path);
618
0
                }
619
0
                obj_val = find_result.value;
620
            } else {
621
                obj_val = doc->getValue();
622
            }
623
624
0
            if (!obj_val || !obj_val->isObject()) {
625
                // if jsonb data is not object we should return null
626
0
                res_null_map[i] = 1;
627
0
                dst_arr.insert_default();
628
0
                continue;
629
0
            }
630
0
            const auto* obj = obj_val->unpack<ObjectVal>();
631
0
            for (const auto& it : *obj) {
632
0
                dst_nested_column.insert_data(it.getKeyStr(), it.klen());
633
0
            }
634
0
            dst_arr.get_offsets().push_back(dst_nested_column.size());
635
0
        } //for
636
1
        return Status::OK();
637
1
    }
Unexecuted instantiation: _ZN5doris17FunctionJsonbKeys15inner_loop_implILb1ELb0ELb0EEENS_6StatusEmRNS_11ColumnArrayERNS_14ColumnNullableERNS_8PODArrayIhLm4096ENS_9AllocatorILb0ELb0ELb0ENS_22DefaultMemoryAllocatorELb1EEELm16ELm15EEERKNS_9ColumnStrIjEEPKSB_PSF_SI_
Unexecuted instantiation: _ZN5doris17FunctionJsonbKeys15inner_loop_implILb1ELb0ELb1EEENS_6StatusEmRNS_11ColumnArrayERNS_14ColumnNullableERNS_8PODArrayIhLm4096ENS_9AllocatorILb0ELb0ELb0ENS_22DefaultMemoryAllocatorELb1EEELm16ELm15EEERKNS_9ColumnStrIjEEPKSB_PSF_SI_
Unexecuted instantiation: _ZN5doris17FunctionJsonbKeys15inner_loop_implILb1ELb1ELb0EEENS_6StatusEmRNS_11ColumnArrayERNS_14ColumnNullableERNS_8PODArrayIhLm4096ENS_9AllocatorILb0ELb0ELb0ENS_22DefaultMemoryAllocatorELb1EEELm16ELm15EEERKNS_9ColumnStrIjEEPKSB_PSF_SI_
Unexecuted instantiation: _ZN5doris17FunctionJsonbKeys15inner_loop_implILb1ELb1ELb1EEENS_6StatusEmRNS_11ColumnArrayERNS_14ColumnNullableERNS_8PODArrayIhLm4096ENS_9AllocatorILb0ELb0ELb0ENS_22DefaultMemoryAllocatorELb1EEELm16ELm15EEERKNS_9ColumnStrIjEEPKSB_PSF_SI_
638
};
639
640
class FunctionJsonbExtractPath : public IFunction {
641
public:
642
    static constexpr auto name = "json_exists_path";
643
    static constexpr auto alias = "jsonb_exists_path";
644
    using ColumnType = ColumnUInt8;
645
    using Container = typename ColumnType::Container;
646
2
    static FunctionPtr create() { return std::make_shared<FunctionJsonbExtractPath>(); }
647
1
    String get_name() const override { return name; }
648
0
    size_t get_number_of_arguments() const override { return 2; }
649
0
    DataTypePtr get_return_type_impl(const DataTypes& arguments) const override {
650
        // it only needs to indicate existence and does not need to return nullable values.
651
0
        const auto nullable = std::ranges::any_of(
652
0
                arguments, [](const DataTypePtr& type) { return type->is_nullable(); });
653
0
        if (nullable) {
654
0
            return make_nullable(std::make_shared<DataTypeUInt8>());
655
0
        } else {
656
0
            return std::make_shared<DataTypeUInt8>();
657
0
        }
658
0
    }
659
660
0
    bool use_default_implementation_for_nulls() const override { return false; }
661
662
    Status execute_impl(FunctionContext* context, Block& block, const ColumnNumbers& arguments,
663
0
                        uint32_t result, size_t input_rows_count) const override {
664
        // prepare jsonb data column
665
0
        auto&& [jsonb_data_column, jsonb_data_const] =
666
0
                unpack_if_const(block.get_by_position(arguments[0]).column);
667
668
0
        const NullMap* data_null_map = nullptr;
669
0
        const ColumnString* data_col = nullptr;
670
0
        if (const auto* nullable = check_and_get_column<ColumnNullable>(jsonb_data_column.get())) {
671
0
            data_col = assert_cast<const ColumnString*>(nullable->get_nested_column_ptr().get());
672
0
            data_null_map = &nullable->get_null_map_data();
673
0
        } else {
674
0
            data_col = assert_cast<const ColumnString*>(jsonb_data_column.get());
675
0
        }
676
677
0
        const auto& ldata = data_col->get_chars();
678
0
        const auto& loffsets = data_col->get_offsets();
679
680
        // prepare parse path column prepare
681
0
        auto&& [path_column, path_const] =
682
0
                unpack_if_const(block.get_by_position(arguments[1]).column);
683
0
        const ColumnString* path_col = nullptr;
684
0
        const NullMap* path_null_map = nullptr;
685
0
        if (const auto* nullable = check_and_get_column<ColumnNullable>(path_column.get())) {
686
0
            path_col = assert_cast<const ColumnString*>(nullable->get_nested_column_ptr().get());
687
0
            path_null_map = &nullable->get_null_map_data();
688
0
        } else {
689
0
            path_col = assert_cast<const ColumnString*>(path_column.get());
690
0
        }
691
692
0
        DORIS_CHECK(!(jsonb_data_const && path_const))
693
0
                << "jsonb_data_const and path_const should not be both const";
694
695
0
        auto create_all_null_result = [&]() {
696
0
            auto res = ColumnType::create();
697
0
            res->insert_default();
698
0
            auto nullable_column =
699
0
                    ColumnNullable::create(std::move(res), ColumnUInt8::create(1, 1));
700
0
            auto const_column = ColumnConst::create(std::move(nullable_column), input_rows_count);
701
0
            block.get_by_position(result).column = std::move(const_column);
702
0
            return Status::OK();
703
0
        };
704
705
0
        ColumnUInt8::MutablePtr result_null_map_column;
706
0
        NullMap* result_null_map = nullptr;
707
0
        if (data_null_map || path_null_map) {
708
0
            result_null_map_column = ColumnUInt8::create(input_rows_count, 0);
709
0
            result_null_map = &result_null_map_column->get_data();
710
711
0
            if (data_null_map) {
712
0
                VectorizedUtils::update_null_map(*result_null_map, *data_null_map,
713
0
                                                 jsonb_data_const);
714
0
            }
715
716
0
            if (path_null_map) {
717
0
                VectorizedUtils::update_null_map(*result_null_map, *path_null_map, path_const);
718
0
            }
719
720
0
            if (!simd::contain_zero(result_null_map->data(), input_rows_count)) {
721
0
                return create_all_null_result();
722
0
            }
723
0
        }
724
725
0
        auto res = ColumnType::create();
726
727
0
        bool is_invalid_json_path = false;
728
729
0
        const auto& rdata = path_col->get_chars();
730
0
        const auto& roffsets = path_col->get_offsets();
731
0
        if (jsonb_data_const) {
732
0
            if (data_null_map && (*data_null_map)[0]) {
733
0
                return create_all_null_result();
734
0
            }
735
0
            scalar_vector(context, data_col->get_data_at(0), rdata, roffsets, res->get_data(),
736
0
                          result_null_map, is_invalid_json_path);
737
0
        } else if (path_const) {
738
0
            if (path_null_map && (*path_null_map)[0]) {
739
0
                return create_all_null_result();
740
0
            }
741
0
            vector_scalar(context, ldata, loffsets, path_col->get_data_at(0), res->get_data(),
742
0
                          result_null_map, is_invalid_json_path);
743
0
        } else {
744
0
            vector_vector(context, ldata, loffsets, rdata, roffsets, res->get_data(),
745
0
                          result_null_map, is_invalid_json_path);
746
0
        }
747
0
        if (is_invalid_json_path) {
748
0
            return Status::InvalidArgument(
749
0
                    "Json path error: Invalid Json Path for value: {}",
750
0
                    std::string_view(reinterpret_cast<const char*>(rdata.data()), rdata.size()));
751
0
        }
752
753
0
        if (result_null_map) {
754
0
            auto nullabel_col =
755
0
                    ColumnNullable::create(std::move(res), std::move(result_null_map_column));
756
0
            block.get_by_position(result).column = std::move(nullabel_col);
757
0
        } else {
758
0
            block.get_by_position(result).column = std::move(res);
759
0
        }
760
0
        return Status::OK();
761
0
    }
762
763
private:
764
    static ALWAYS_INLINE void inner_loop_impl(size_t i, Container& res, const char* l_raw_str,
765
0
                                              size_t l_str_size, JsonbPath& path) {
766
        // doc is NOT necessary to be deleted since JsonbDocument will not allocate memory
767
0
        const JsonbDocument* doc = nullptr;
768
0
        auto st = JsonbDocument::checkAndCreateDocument(l_raw_str, l_str_size, &doc);
769
0
        if (!st.ok() || !doc || !doc->getValue()) [[unlikely]] {
770
0
            return;
771
0
        }
772
773
        // value is NOT necessary to be deleted since JsonbValue will not allocate memory
774
0
        auto result = doc->getValue()->findValue(path);
775
776
0
        if (result.value) {
777
0
            res[i] = 1;
778
0
        }
779
0
    }
780
    static void vector_vector(FunctionContext* context, const ColumnString::Chars& ldata,
781
                              const ColumnString::Offsets& loffsets,
782
                              const ColumnString::Chars& rdata,
783
                              const ColumnString::Offsets& roffsets, Container& res,
784
0
                              const NullMap* result_null_map, bool& is_invalid_json_path) {
785
0
        const size_t size = loffsets.size();
786
0
        res.resize_fill(size, 0);
787
788
0
        for (size_t i = 0; i < size; i++) {
789
0
            if (result_null_map && (*result_null_map)[i]) {
790
0
                continue;
791
0
            }
792
793
0
            const char* l_raw_str = reinterpret_cast<const char*>(&ldata[loffsets[i - 1]]);
794
0
            int l_str_size = loffsets[i] - loffsets[i - 1];
795
796
0
            const char* r_raw_str = reinterpret_cast<const char*>(&rdata[roffsets[i - 1]]);
797
0
            int r_str_size = roffsets[i] - roffsets[i - 1];
798
799
0
            JsonbPath path;
800
0
            if (!path.seek(r_raw_str, r_str_size)) {
801
0
                is_invalid_json_path = true;
802
0
                return;
803
0
            }
804
805
0
            inner_loop_impl(i, res, l_raw_str, l_str_size, path);
806
0
        }
807
0
    }
808
    static void scalar_vector(FunctionContext* context, const StringRef& ldata,
809
                              const ColumnString::Chars& rdata,
810
                              const ColumnString::Offsets& roffsets, Container& res,
811
0
                              const NullMap* result_null_map, bool& is_invalid_json_path) {
812
0
        const size_t size = roffsets.size();
813
0
        res.resize_fill(size, 0);
814
815
0
        for (size_t i = 0; i < size; i++) {
816
0
            if (result_null_map && (*result_null_map)[i]) {
817
0
                continue;
818
0
            }
819
0
            const char* r_raw_str = reinterpret_cast<const char*>(&rdata[roffsets[i - 1]]);
820
0
            int r_str_size = roffsets[i] - roffsets[i - 1];
821
822
0
            JsonbPath path;
823
0
            if (!path.seek(r_raw_str, r_str_size)) {
824
0
                is_invalid_json_path = true;
825
0
                return;
826
0
            }
827
828
0
            inner_loop_impl(i, res, ldata.data, ldata.size, path);
829
0
        }
830
0
    }
831
    static void vector_scalar(FunctionContext* context, const ColumnString::Chars& ldata,
832
                              const ColumnString::Offsets& loffsets, const StringRef& rdata,
833
                              Container& res, const NullMap* result_null_map,
834
0
                              bool& is_invalid_json_path) {
835
0
        const size_t size = loffsets.size();
836
0
        res.resize_fill(size, 0);
837
838
0
        JsonbPath path;
839
0
        if (!path.seek(rdata.data, rdata.size)) {
840
0
            is_invalid_json_path = true;
841
0
            return;
842
0
        }
843
844
0
        for (size_t i = 0; i < size; i++) {
845
0
            if (result_null_map && (*result_null_map)[i]) {
846
0
                continue;
847
0
            }
848
0
            const char* l_raw_str = reinterpret_cast<const char*>(&ldata[loffsets[i - 1]]);
849
0
            int l_str_size = loffsets[i] - loffsets[i - 1];
850
851
0
            inner_loop_impl(i, res, l_raw_str, l_str_size, path);
852
0
        }
853
0
    }
854
};
855
856
template <typename ValueType>
857
struct JsonbExtractStringImpl {
858
    using ReturnType = typename ValueType::ReturnType;
859
    using ColumnType = typename ValueType::ColumnType;
860
861
private:
862
    static ALWAYS_INLINE void inner_loop_impl(JsonbWriter* writer, size_t i,
863
                                              ColumnString::Chars& res_data,
864
                                              ColumnString::Offsets& res_offsets, NullMap& null_map,
865
90
                                              const char* l_raw, size_t l_size, JsonbPath& path) {
866
        // doc is NOT necessary to be deleted since JsonbDocument will not allocate memory
867
90
        const JsonbDocument* doc = nullptr;
868
90
        auto st = JsonbDocument::checkAndCreateDocument(l_raw, l_size, &doc);
869
90
        if (!st.ok() || !doc || !doc->getValue()) [[unlikely]] {
870
0
            StringOP::push_null_string(i, res_data, res_offsets, null_map);
871
0
            return;
872
0
        }
873
874
        // value is NOT necessary to be deleted since JsonbValue will not allocate memory
875
90
        auto find_result = doc->getValue()->findValue(path);
876
877
90
        if (UNLIKELY(!find_result.value)) {
878
46
            StringOP::push_null_string(i, res_data, res_offsets, null_map);
879
46
            return;
880
46
        }
881
882
44
        if constexpr (ValueType::only_get_type) {
883
0
            StringOP::push_value_string(std::string_view(find_result.value->typeName()), i,
884
0
                                        res_data, res_offsets);
885
0
            return;
886
44
        } else {
887
44
            static_assert(std::is_same_v<DataTypeJsonb, ReturnType>);
888
44
            if constexpr (ValueType::no_quotes) {
889
0
                if (find_result.value->isString()) {
890
0
                    const auto* str_value = find_result.value->unpack<JsonbStringVal>();
891
0
                    const auto* blob = str_value->getBlob();
892
0
                    if (str_value->length() > 1 && blob[0] == '"' &&
893
0
                        blob[str_value->length() - 1] == '"') {
894
0
                        writer->writeStartString();
895
0
                        writer->writeString(blob + 1, str_value->length() - 2);
896
0
                        writer->writeEndString();
897
0
                        StringOP::push_value_string(
898
0
                                std::string_view(writer->getOutput()->getBuffer(),
899
0
                                                 writer->getOutput()->getSize()),
900
0
                                i, res_data, res_offsets);
901
0
                        return;
902
0
                    }
903
0
                }
904
0
            }
905
0
            writer->writeValueSimple(find_result.value);
906
44
            StringOP::push_value_string(std::string_view(writer->getOutput()->getBuffer(),
907
44
                                                         writer->getOutput()->getSize()),
908
44
                                        i, res_data, res_offsets);
909
44
        }
910
44
    }
Unexecuted instantiation: _ZN5doris22JsonbExtractStringImplINS_13JsonbTypeTypeEE15inner_loop_implEPNS_12JsonbWriterTINS_14JsonbOutStreamEEEmRNS_8PODArrayIhLm4096ENS_9AllocatorILb0ELb0ELb0ENS_22DefaultMemoryAllocatorELb1EEELm16ELm15EEERNS7_IjLm4096ESA_Lm16ELm15EEESC_PKcmRNS_9JsonbPathE
_ZN5doris22JsonbExtractStringImplINS_13JsonbTypeJsonEE15inner_loop_implEPNS_12JsonbWriterTINS_14JsonbOutStreamEEEmRNS_8PODArrayIhLm4096ENS_9AllocatorILb0ELb0ELb0ENS_22DefaultMemoryAllocatorELb1EEELm16ELm15EEERNS7_IjLm4096ESA_Lm16ELm15EEESC_PKcmRNS_9JsonbPathE
Line
Count
Source
865
90
                                              const char* l_raw, size_t l_size, JsonbPath& path) {
866
        // doc is NOT necessary to be deleted since JsonbDocument will not allocate memory
867
90
        const JsonbDocument* doc = nullptr;
868
90
        auto st = JsonbDocument::checkAndCreateDocument(l_raw, l_size, &doc);
869
90
        if (!st.ok() || !doc || !doc->getValue()) [[unlikely]] {
870
0
            StringOP::push_null_string(i, res_data, res_offsets, null_map);
871
0
            return;
872
0
        }
873
874
        // value is NOT necessary to be deleted since JsonbValue will not allocate memory
875
90
        auto find_result = doc->getValue()->findValue(path);
876
877
90
        if (UNLIKELY(!find_result.value)) {
878
46
            StringOP::push_null_string(i, res_data, res_offsets, null_map);
879
46
            return;
880
46
        }
881
882
        if constexpr (ValueType::only_get_type) {
883
            StringOP::push_value_string(std::string_view(find_result.value->typeName()), i,
884
                                        res_data, res_offsets);
885
            return;
886
44
        } else {
887
44
            static_assert(std::is_same_v<DataTypeJsonb, ReturnType>);
888
            if constexpr (ValueType::no_quotes) {
889
                if (find_result.value->isString()) {
890
                    const auto* str_value = find_result.value->unpack<JsonbStringVal>();
891
                    const auto* blob = str_value->getBlob();
892
                    if (str_value->length() > 1 && blob[0] == '"' &&
893
                        blob[str_value->length() - 1] == '"') {
894
                        writer->writeStartString();
895
                        writer->writeString(blob + 1, str_value->length() - 2);
896
                        writer->writeEndString();
897
                        StringOP::push_value_string(
898
                                std::string_view(writer->getOutput()->getBuffer(),
899
                                                 writer->getOutput()->getSize()),
900
                                i, res_data, res_offsets);
901
                        return;
902
                    }
903
                }
904
            }
905
44
            writer->writeValueSimple(find_result.value);
906
44
            StringOP::push_value_string(std::string_view(writer->getOutput()->getBuffer(),
907
44
                                                         writer->getOutput()->getSize()),
908
44
                                        i, res_data, res_offsets);
909
44
        }
910
44
    }
Unexecuted instantiation: _ZN5doris22JsonbExtractStringImplINS_21JsonbTypeJsonNoQuotesEE15inner_loop_implEPNS_12JsonbWriterTINS_14JsonbOutStreamEEEmRNS_8PODArrayIhLm4096ENS_9AllocatorILb0ELb0ELb0ENS_22DefaultMemoryAllocatorELb1EEELm16ELm15EEERNS7_IjLm4096ESA_Lm16ELm15EEESC_PKcmRNS_9JsonbPathE
911
912
public:
913
    // for jsonb_extract_string
914
    static Status vector_vector_v2(
915
            FunctionContext* context, const ColumnString::Chars& ldata,
916
            const ColumnString::Offsets& loffsets, const NullMap* l_null_map,
917
            const bool& json_data_const,
918
            const std::vector<const ColumnString*>& rdata_columns, // here we can support more paths
919
            const std::vector<const NullMap*>& r_null_maps, const std::vector<bool>& path_const,
920
4
            ColumnString::Chars& res_data, ColumnString::Offsets& res_offsets, NullMap& null_map) {
921
4
        const size_t input_rows_count = null_map.size();
922
4
        res_offsets.resize(input_rows_count);
923
924
4
        auto writer = std::make_unique<JsonbWriter>();
925
926
        // reuseable json path list, espacially for const path
927
4
        std::vector<JsonbPath> json_path_list;
928
4
        json_path_list.resize(rdata_columns.size());
929
930
        // lambda function to parse json path for row i and path pi
931
90
        auto parse_json_path = [&](size_t i, size_t pi) -> Status {
932
90
            const auto index = index_check_const(i, path_const[pi]);
933
934
90
            const ColumnString* path_col = rdata_columns[pi];
935
90
            const ColumnString::Chars& rdata = path_col->get_chars();
936
90
            const ColumnString::Offsets& roffsets = path_col->get_offsets();
937
90
            size_t r_off = roffsets[index - 1];
938
90
            size_t r_size = roffsets[index] - r_off;
939
90
            const char* r_raw = reinterpret_cast<const char*>(&rdata[r_off]);
940
941
90
            JsonbPath path;
942
90
            if (!path.seek(r_raw, r_size)) {
943
0
                return Status::InvalidArgument("Json path error: Invalid Json Path for value: {}",
944
0
                                               std::string_view(r_raw, r_size));
945
0
            }
946
947
90
            json_path_list[pi] = std::move(path);
948
949
90
            return Status::OK();
950
90
        };
Unexecuted instantiation: _ZZN5doris22JsonbExtractStringImplINS_13JsonbTypeTypeEE16vector_vector_v2EPNS_15FunctionContextERKNS_8PODArrayIhLm4096ENS_9AllocatorILb0ELb0ELb0ENS_22DefaultMemoryAllocatorELb1EEELm16ELm15EEERKNS5_IjLm4096ES8_Lm16ELm15EEEPSA_RKbRKSt6vectorIPKNS_9ColumnStrIjEESaISM_EERKSI_ISF_SaISF_EERKSI_IbSaIbEERS9_RSC_SZ_ENKUlmmE_clEmm
_ZZN5doris22JsonbExtractStringImplINS_13JsonbTypeJsonEE16vector_vector_v2EPNS_15FunctionContextERKNS_8PODArrayIhLm4096ENS_9AllocatorILb0ELb0ELb0ENS_22DefaultMemoryAllocatorELb1EEELm16ELm15EEERKNS5_IjLm4096ES8_Lm16ELm15EEEPSA_RKbRKSt6vectorIPKNS_9ColumnStrIjEESaISM_EERKSI_ISF_SaISF_EERKSI_IbSaIbEERS9_RSC_SZ_ENKUlmmE_clEmm
Line
Count
Source
931
90
        auto parse_json_path = [&](size_t i, size_t pi) -> Status {
932
90
            const auto index = index_check_const(i, path_const[pi]);
933
934
90
            const ColumnString* path_col = rdata_columns[pi];
935
90
            const ColumnString::Chars& rdata = path_col->get_chars();
936
90
            const ColumnString::Offsets& roffsets = path_col->get_offsets();
937
90
            size_t r_off = roffsets[index - 1];
938
90
            size_t r_size = roffsets[index] - r_off;
939
90
            const char* r_raw = reinterpret_cast<const char*>(&rdata[r_off]);
940
941
90
            JsonbPath path;
942
90
            if (!path.seek(r_raw, r_size)) {
943
0
                return Status::InvalidArgument("Json path error: Invalid Json Path for value: {}",
944
0
                                               std::string_view(r_raw, r_size));
945
0
            }
946
947
90
            json_path_list[pi] = std::move(path);
948
949
90
            return Status::OK();
950
90
        };
Unexecuted instantiation: _ZZN5doris22JsonbExtractStringImplINS_21JsonbTypeJsonNoQuotesEE16vector_vector_v2EPNS_15FunctionContextERKNS_8PODArrayIhLm4096ENS_9AllocatorILb0ELb0ELb0ENS_22DefaultMemoryAllocatorELb1EEELm16ELm15EEERKNS5_IjLm4096ES8_Lm16ELm15EEEPSA_RKbRKSt6vectorIPKNS_9ColumnStrIjEESaISM_EERKSI_ISF_SaISF_EERKSI_IbSaIbEERS9_RSC_SZ_ENKUlmmE_clEmm
951
952
8
        for (size_t pi = 0; pi < rdata_columns.size(); pi++) {
953
4
            if (path_const[pi]) {
954
0
                if (r_null_maps[pi] && (*r_null_maps[pi])[0]) {
955
0
                    continue;
956
0
                }
957
0
                RETURN_IF_ERROR(parse_json_path(0, pi));
958
0
            }
959
4
        }
960
961
4
        res_data.reserve(ldata.size());
962
98
        for (size_t i = 0; i < input_rows_count; ++i) {
963
94
            if (null_map[i]) {
964
0
                continue;
965
0
            }
966
967
94
            const auto data_index = index_check_const(i, json_data_const);
968
94
            if (l_null_map && (*l_null_map)[data_index]) {
969
4
                StringOP::push_null_string(i, res_data, res_offsets, null_map);
970
4
                continue;
971
4
            }
972
973
90
            size_t l_off = loffsets[data_index - 1];
974
90
            size_t l_size = loffsets[data_index] - l_off;
975
90
            const char* l_raw = reinterpret_cast<const char*>(&ldata[l_off]);
976
90
            if (rdata_columns.size() == 1) { // just return origin value
977
90
                const auto path_index = index_check_const(i, path_const[0]);
978
90
                if (r_null_maps[0] && (*r_null_maps[0])[path_index]) {
979
0
                    StringOP::push_null_string(i, res_data, res_offsets, null_map);
980
0
                    continue;
981
0
                }
982
983
90
                if (!path_const[0]) {
984
90
                    RETURN_IF_ERROR(parse_json_path(i, 0));
985
90
                }
986
987
90
                writer->reset();
988
90
                inner_loop_impl(writer.get(), i, res_data, res_offsets, null_map, l_raw, l_size,
989
90
                                json_path_list[0]);
990
90
            } else { // will make array string to user
991
0
                writer->reset();
992
0
                bool has_value = false;
993
994
                // doc is NOT necessary to be deleted since JsonbDocument will not allocate memory
995
0
                const JsonbDocument* doc = nullptr;
996
0
                auto st = JsonbDocument::checkAndCreateDocument(l_raw, l_size, &doc);
997
998
0
                for (size_t pi = 0; pi < rdata_columns.size(); ++pi) {
999
0
                    if (!st.ok() || !doc || !doc->getValue()) [[unlikely]] {
1000
0
                        continue;
1001
0
                    }
1002
1003
0
                    const auto path_index = index_check_const(i, path_const[pi]);
1004
0
                    if (r_null_maps[pi] && (*r_null_maps[pi])[path_index]) {
1005
0
                        StringOP::push_null_string(i, res_data, res_offsets, null_map);
1006
0
                        break;
1007
0
                    }
1008
1009
0
                    if (!path_const[pi]) {
1010
0
                        RETURN_IF_ERROR(parse_json_path(i, pi));
1011
0
                    }
1012
1013
0
                    auto find_result = doc->getValue()->findValue(json_path_list[pi]);
1014
1015
0
                    if (find_result.value) {
1016
0
                        if (!has_value) {
1017
0
                            has_value = true;
1018
0
                            writer->writeStartArray();
1019
0
                        }
1020
0
                        if (find_result.value->isArray() && find_result.is_wildcard) {
1021
                            // To avoid getting results of nested array like [[1, 2, 3], [4, 5, 6]],
1022
                            // if value is array, we should write all items in array, instead of write the array itself.
1023
                            // finaly we will get results like [1, 2, 3, 4, 5, 6]
1024
0
                            for (const auto& item : *find_result.value->unpack<ArrayVal>()) {
1025
0
                                writer->writeValue(&item);
1026
0
                            }
1027
0
                        } else {
1028
0
                            writer->writeValue(find_result.value);
1029
0
                        }
1030
0
                    }
1031
0
                }
1032
0
                if (has_value) {
1033
0
                    writer->writeEndArray();
1034
0
                    StringOP::push_value_string(std::string_view(writer->getOutput()->getBuffer(),
1035
0
                                                                 writer->getOutput()->getSize()),
1036
0
                                                i, res_data, res_offsets);
1037
0
                } else {
1038
0
                    StringOP::push_null_string(i, res_data, res_offsets, null_map);
1039
0
                }
1040
0
            }
1041
90
        } //for
1042
4
        return Status::OK();
1043
4
    }
Unexecuted instantiation: _ZN5doris22JsonbExtractStringImplINS_13JsonbTypeTypeEE16vector_vector_v2EPNS_15FunctionContextERKNS_8PODArrayIhLm4096ENS_9AllocatorILb0ELb0ELb0ENS_22DefaultMemoryAllocatorELb1EEELm16ELm15EEERKNS5_IjLm4096ES8_Lm16ELm15EEEPSA_RKbRKSt6vectorIPKNS_9ColumnStrIjEESaISM_EERKSI_ISF_SaISF_EERKSI_IbSaIbEERS9_RSC_SZ_
_ZN5doris22JsonbExtractStringImplINS_13JsonbTypeJsonEE16vector_vector_v2EPNS_15FunctionContextERKNS_8PODArrayIhLm4096ENS_9AllocatorILb0ELb0ELb0ENS_22DefaultMemoryAllocatorELb1EEELm16ELm15EEERKNS5_IjLm4096ES8_Lm16ELm15EEEPSA_RKbRKSt6vectorIPKNS_9ColumnStrIjEESaISM_EERKSI_ISF_SaISF_EERKSI_IbSaIbEERS9_RSC_SZ_
Line
Count
Source
920
4
            ColumnString::Chars& res_data, ColumnString::Offsets& res_offsets, NullMap& null_map) {
921
4
        const size_t input_rows_count = null_map.size();
922
4
        res_offsets.resize(input_rows_count);
923
924
4
        auto writer = std::make_unique<JsonbWriter>();
925
926
        // reuseable json path list, espacially for const path
927
4
        std::vector<JsonbPath> json_path_list;
928
4
        json_path_list.resize(rdata_columns.size());
929
930
        // lambda function to parse json path for row i and path pi
931
4
        auto parse_json_path = [&](size_t i, size_t pi) -> Status {
932
4
            const auto index = index_check_const(i, path_const[pi]);
933
934
4
            const ColumnString* path_col = rdata_columns[pi];
935
4
            const ColumnString::Chars& rdata = path_col->get_chars();
936
4
            const ColumnString::Offsets& roffsets = path_col->get_offsets();
937
4
            size_t r_off = roffsets[index - 1];
938
4
            size_t r_size = roffsets[index] - r_off;
939
4
            const char* r_raw = reinterpret_cast<const char*>(&rdata[r_off]);
940
941
4
            JsonbPath path;
942
4
            if (!path.seek(r_raw, r_size)) {
943
4
                return Status::InvalidArgument("Json path error: Invalid Json Path for value: {}",
944
4
                                               std::string_view(r_raw, r_size));
945
4
            }
946
947
4
            json_path_list[pi] = std::move(path);
948
949
4
            return Status::OK();
950
4
        };
951
952
8
        for (size_t pi = 0; pi < rdata_columns.size(); pi++) {
953
4
            if (path_const[pi]) {
954
0
                if (r_null_maps[pi] && (*r_null_maps[pi])[0]) {
955
0
                    continue;
956
0
                }
957
0
                RETURN_IF_ERROR(parse_json_path(0, pi));
958
0
            }
959
4
        }
960
961
4
        res_data.reserve(ldata.size());
962
98
        for (size_t i = 0; i < input_rows_count; ++i) {
963
94
            if (null_map[i]) {
964
0
                continue;
965
0
            }
966
967
94
            const auto data_index = index_check_const(i, json_data_const);
968
94
            if (l_null_map && (*l_null_map)[data_index]) {
969
4
                StringOP::push_null_string(i, res_data, res_offsets, null_map);
970
4
                continue;
971
4
            }
972
973
90
            size_t l_off = loffsets[data_index - 1];
974
90
            size_t l_size = loffsets[data_index] - l_off;
975
90
            const char* l_raw = reinterpret_cast<const char*>(&ldata[l_off]);
976
90
            if (rdata_columns.size() == 1) { // just return origin value
977
90
                const auto path_index = index_check_const(i, path_const[0]);
978
90
                if (r_null_maps[0] && (*r_null_maps[0])[path_index]) {
979
0
                    StringOP::push_null_string(i, res_data, res_offsets, null_map);
980
0
                    continue;
981
0
                }
982
983
90
                if (!path_const[0]) {
984
90
                    RETURN_IF_ERROR(parse_json_path(i, 0));
985
90
                }
986
987
90
                writer->reset();
988
90
                inner_loop_impl(writer.get(), i, res_data, res_offsets, null_map, l_raw, l_size,
989
90
                                json_path_list[0]);
990
90
            } else { // will make array string to user
991
0
                writer->reset();
992
0
                bool has_value = false;
993
994
                // doc is NOT necessary to be deleted since JsonbDocument will not allocate memory
995
0
                const JsonbDocument* doc = nullptr;
996
0
                auto st = JsonbDocument::checkAndCreateDocument(l_raw, l_size, &doc);
997
998
0
                for (size_t pi = 0; pi < rdata_columns.size(); ++pi) {
999
0
                    if (!st.ok() || !doc || !doc->getValue()) [[unlikely]] {
1000
0
                        continue;
1001
0
                    }
1002
1003
0
                    const auto path_index = index_check_const(i, path_const[pi]);
1004
0
                    if (r_null_maps[pi] && (*r_null_maps[pi])[path_index]) {
1005
0
                        StringOP::push_null_string(i, res_data, res_offsets, null_map);
1006
0
                        break;
1007
0
                    }
1008
1009
0
                    if (!path_const[pi]) {
1010
0
                        RETURN_IF_ERROR(parse_json_path(i, pi));
1011
0
                    }
1012
1013
0
                    auto find_result = doc->getValue()->findValue(json_path_list[pi]);
1014
1015
0
                    if (find_result.value) {
1016
0
                        if (!has_value) {
1017
0
                            has_value = true;
1018
0
                            writer->writeStartArray();
1019
0
                        }
1020
0
                        if (find_result.value->isArray() && find_result.is_wildcard) {
1021
                            // To avoid getting results of nested array like [[1, 2, 3], [4, 5, 6]],
1022
                            // if value is array, we should write all items in array, instead of write the array itself.
1023
                            // finaly we will get results like [1, 2, 3, 4, 5, 6]
1024
0
                            for (const auto& item : *find_result.value->unpack<ArrayVal>()) {
1025
0
                                writer->writeValue(&item);
1026
0
                            }
1027
0
                        } else {
1028
0
                            writer->writeValue(find_result.value);
1029
0
                        }
1030
0
                    }
1031
0
                }
1032
0
                if (has_value) {
1033
0
                    writer->writeEndArray();
1034
0
                    StringOP::push_value_string(std::string_view(writer->getOutput()->getBuffer(),
1035
0
                                                                 writer->getOutput()->getSize()),
1036
0
                                                i, res_data, res_offsets);
1037
0
                } else {
1038
0
                    StringOP::push_null_string(i, res_data, res_offsets, null_map);
1039
0
                }
1040
0
            }
1041
90
        } //for
1042
4
        return Status::OK();
1043
4
    }
Unexecuted instantiation: _ZN5doris22JsonbExtractStringImplINS_21JsonbTypeJsonNoQuotesEE16vector_vector_v2EPNS_15FunctionContextERKNS_8PODArrayIhLm4096ENS_9AllocatorILb0ELb0ELb0ENS_22DefaultMemoryAllocatorELb1EEELm16ELm15EEERKNS5_IjLm4096ES8_Lm16ELm15EEEPSA_RKbRKSt6vectorIPKNS_9ColumnStrIjEESaISM_EERKSI_ISF_SaISF_EERKSI_IbSaIbEERS9_RSC_SZ_
1044
1045
    static Status vector_vector(FunctionContext* context, const ColumnString::Chars& ldata,
1046
                                const ColumnString::Offsets& loffsets, const NullMap* l_null_map,
1047
                                const ColumnString::Chars& rdata,
1048
                                const ColumnString::Offsets& roffsets, const NullMap* r_null_map,
1049
                                ColumnString::Chars& res_data, ColumnString::Offsets& res_offsets,
1050
                                NullMap& null_map) {
1051
        size_t input_rows_count = loffsets.size();
1052
        res_offsets.resize(input_rows_count);
1053
1054
        JsonbWriter writer;
1055
        for (size_t i = 0; i < input_rows_count; ++i) {
1056
            if (l_null_map && (*l_null_map)[i]) {
1057
                StringOP::push_null_string(i, res_data, res_offsets, null_map);
1058
                continue;
1059
            }
1060
1061
            if (r_null_map && (*r_null_map)[i]) {
1062
                StringOP::push_null_string(i, res_data, res_offsets, null_map);
1063
                continue;
1064
            }
1065
1066
            int l_size = loffsets[i] - loffsets[i - 1];
1067
            const char* l_raw = reinterpret_cast<const char*>(&ldata[loffsets[i - 1]]);
1068
1069
            int r_size = roffsets[i] - roffsets[i - 1];
1070
            const char* r_raw = reinterpret_cast<const char*>(&rdata[roffsets[i - 1]]);
1071
1072
            JsonbPath path;
1073
            if (!path.seek(r_raw, r_size)) {
1074
                return Status::InvalidArgument(
1075
                        "Json path error: Invalid Json Path for value: {} at row: {}",
1076
                        std::string_view(r_raw, r_size), i);
1077
            }
1078
1079
            writer.reset();
1080
            inner_loop_impl(&writer, i, res_data, res_offsets, null_map, l_raw, l_size, path);
1081
        } //for
1082
        return Status::OK();
1083
    } //function
1084
1085
    static Status vector_scalar(FunctionContext* context, const ColumnString::Chars& ldata,
1086
                                const ColumnString::Offsets& loffsets, const NullMap* l_null_map,
1087
                                const StringRef& rdata, ColumnString::Chars& res_data,
1088
                                ColumnString::Offsets& res_offsets, NullMap& null_map) {
1089
        size_t input_rows_count = loffsets.size();
1090
        res_offsets.resize(input_rows_count);
1091
1092
        JsonbPath path;
1093
        if (!path.seek(rdata.data, rdata.size)) {
1094
            return Status::InvalidArgument("Json path error: Invalid Json Path for value: {}",
1095
                                           std::string_view(rdata.data, rdata.size));
1096
        }
1097
1098
        JsonbWriter writer;
1099
        for (size_t i = 0; i < input_rows_count; ++i) {
1100
            if (l_null_map && (*l_null_map)[i]) {
1101
                StringOP::push_null_string(i, res_data, res_offsets, null_map);
1102
                continue;
1103
            }
1104
1105
            int l_size = loffsets[i] - loffsets[i - 1];
1106
            const char* l_raw = reinterpret_cast<const char*>(&ldata[loffsets[i - 1]]);
1107
1108
            writer.reset();
1109
            inner_loop_impl(&writer, i, res_data, res_offsets, null_map, l_raw, l_size, path);
1110
        } //for
1111
        return Status::OK();
1112
    } //function
1113
1114
    static Status scalar_vector(FunctionContext* context, const StringRef& ldata,
1115
                                const ColumnString::Chars& rdata,
1116
                                const ColumnString::Offsets& roffsets, const NullMap* r_null_map,
1117
                                ColumnString::Chars& res_data, ColumnString::Offsets& res_offsets,
1118
                                NullMap& null_map) {
1119
        size_t input_rows_count = roffsets.size();
1120
        res_offsets.resize(input_rows_count);
1121
1122
        JsonbWriter writer;
1123
1124
        for (size_t i = 0; i < input_rows_count; ++i) {
1125
            if (r_null_map && (*r_null_map)[i]) {
1126
                StringOP::push_null_string(i, res_data, res_offsets, null_map);
1127
                continue;
1128
            }
1129
1130
            int r_size = roffsets[i] - roffsets[i - 1];
1131
            const char* r_raw = reinterpret_cast<const char*>(&rdata[roffsets[i - 1]]);
1132
1133
            JsonbPath path;
1134
            if (!path.seek(r_raw, r_size)) {
1135
                return Status::InvalidArgument(
1136
                        "Json path error: Invalid Json Path for value: {} at row: {}",
1137
                        std::string_view(r_raw, r_size), i);
1138
            }
1139
1140
            writer.reset();
1141
            inner_loop_impl(&writer, i, res_data, res_offsets, null_map, ldata.data, ldata.size,
1142
                            path);
1143
        } //for
1144
        return Status::OK();
1145
    } //function
1146
};
1147
1148
struct JsonbExtractIsnull {
1149
    static constexpr auto name = "json_extract_isnull";
1150
    static constexpr auto alias = "jsonb_extract_isnull";
1151
1152
    using ReturnType = DataTypeUInt8;
1153
    using ColumnType = ColumnUInt8;
1154
    using Container = typename ColumnType::Container;
1155
1156
private:
1157
    static ALWAYS_INLINE void inner_loop_impl(size_t i, Container& res, NullMap& null_map,
1158
                                              const char* l_raw_str, size_t l_str_size,
1159
0
                                              JsonbPath& path) {
1160
0
        if (null_map[i]) {
1161
0
            res[i] = 0;
1162
0
            return;
1163
0
        }
1164
1165
        // doc is NOT necessary to be deleted since JsonbDocument will not allocate memory
1166
0
        const JsonbDocument* doc = nullptr;
1167
0
        auto st = JsonbDocument::checkAndCreateDocument(l_raw_str, l_str_size, &doc);
1168
0
        if (!st.ok() || !doc || !doc->getValue()) [[unlikely]] {
1169
0
            null_map[i] = 1;
1170
0
            res[i] = 0;
1171
0
            return;
1172
0
        }
1173
1174
        // value is NOT necessary to be deleted since JsonbValue will not allocate memory
1175
0
        auto find_result = doc->getValue()->findValue(path);
1176
0
        const auto* value = find_result.value;
1177
1178
0
        if (UNLIKELY(!value)) {
1179
0
            null_map[i] = 1;
1180
0
            res[i] = 0;
1181
0
            return;
1182
0
        }
1183
1184
0
        res[i] = value->isNull();
1185
0
    }
1186
1187
public:
1188
    // for jsonb_extract_int/int64/double
1189
    static Status vector_vector(FunctionContext* context, const ColumnString::Chars& ldata,
1190
                                const ColumnString::Offsets& loffsets, const NullMap* l_null_map,
1191
                                const ColumnString::Chars& rdata,
1192
                                const ColumnString::Offsets& roffsets, const NullMap* r_null_map,
1193
0
                                Container& res, NullMap& null_map) {
1194
0
        size_t size = loffsets.size();
1195
0
        res.resize(size);
1196
1197
0
        for (size_t i = 0; i < loffsets.size(); i++) {
1198
0
            if ((l_null_map && (*l_null_map)[i]) || (r_null_map && (*r_null_map)[i])) {
1199
0
                res[i] = 0;
1200
0
                null_map[i] = 1;
1201
0
                continue;
1202
0
            }
1203
1204
0
            const char* l_raw_str = reinterpret_cast<const char*>(&ldata[loffsets[i - 1]]);
1205
0
            int l_str_size = loffsets[i] - loffsets[i - 1];
1206
1207
0
            const char* r_raw_str = reinterpret_cast<const char*>(&rdata[roffsets[i - 1]]);
1208
0
            int r_str_size = roffsets[i] - roffsets[i - 1];
1209
1210
0
            JsonbPath path;
1211
0
            if (!path.seek(r_raw_str, r_str_size)) {
1212
0
                return Status::InvalidArgument(
1213
0
                        "Json path error: Invalid Json Path for value: {} at row: {}",
1214
0
                        std::string_view(r_raw_str, r_str_size), i);
1215
0
            }
1216
1217
0
            inner_loop_impl(i, res, null_map, l_raw_str, l_str_size, path);
1218
0
        } //for
1219
0
        return Status::OK();
1220
0
    } //function
1221
1222
    static Status scalar_vector(FunctionContext* context, const StringRef& ldata,
1223
                                const ColumnString::Chars& rdata,
1224
                                const ColumnString::Offsets& roffsets, const NullMap* r_null_map,
1225
0
                                Container& res, NullMap& null_map) {
1226
0
        size_t size = roffsets.size();
1227
0
        res.resize(size);
1228
1229
0
        for (size_t i = 0; i < size; i++) {
1230
0
            if (r_null_map && (*r_null_map)[i]) {
1231
0
                res[i] = 0;
1232
0
                null_map[i] = 1;
1233
0
                continue;
1234
0
            }
1235
1236
0
            const char* r_raw_str = reinterpret_cast<const char*>(&rdata[roffsets[i - 1]]);
1237
0
            int r_str_size = roffsets[i] - roffsets[i - 1];
1238
1239
0
            JsonbPath path;
1240
0
            if (!path.seek(r_raw_str, r_str_size)) {
1241
0
                return Status::InvalidArgument(
1242
0
                        "Json path error: Invalid Json Path for value: {} at row: {}",
1243
0
                        std::string_view(r_raw_str, r_str_size), i);
1244
0
            }
1245
1246
0
            inner_loop_impl(i, res, null_map, ldata.data, ldata.size, path);
1247
0
        } //for
1248
0
        return Status::OK();
1249
0
    } //function
1250
1251
    static Status vector_scalar(FunctionContext* context, const ColumnString::Chars& ldata,
1252
                                const ColumnString::Offsets& loffsets, const NullMap* l_null_map,
1253
0
                                const StringRef& rdata, Container& res, NullMap& null_map) {
1254
0
        size_t size = loffsets.size();
1255
0
        res.resize(size);
1256
1257
0
        JsonbPath path;
1258
0
        if (!path.seek(rdata.data, rdata.size)) {
1259
0
            return Status::InvalidArgument("Json path error: Invalid Json Path for value: {}",
1260
0
                                           std::string_view(rdata.data, rdata.size));
1261
0
        }
1262
1263
0
        for (size_t i = 0; i < loffsets.size(); i++) {
1264
0
            if (l_null_map && (*l_null_map)[i]) {
1265
0
                res[i] = 0;
1266
0
                null_map[i] = 1;
1267
0
                continue;
1268
0
            }
1269
1270
0
            const char* l_raw_str = reinterpret_cast<const char*>(&ldata[loffsets[i - 1]]);
1271
0
            int l_str_size = loffsets[i] - loffsets[i - 1];
1272
1273
0
            inner_loop_impl(i, res, null_map, l_raw_str, l_str_size, path);
1274
0
        } //for
1275
0
        return Status::OK();
1276
0
    } //function
1277
};
1278
1279
struct JsonbTypeJson {
1280
    using T = std::string;
1281
    using ReturnType = DataTypeJsonb;
1282
    using ColumnType = ColumnString;
1283
    static const bool only_get_type = false;
1284
    static const bool no_quotes = false;
1285
};
1286
1287
struct JsonbTypeJsonNoQuotes {
1288
    using T = std::string;
1289
    using ReturnType = DataTypeJsonb;
1290
    using ColumnType = ColumnString;
1291
    static const bool only_get_type = false;
1292
    static const bool no_quotes = true;
1293
};
1294
1295
struct JsonbTypeType {
1296
    using T = std::string;
1297
    using ReturnType = DataTypeString;
1298
    using ColumnType = ColumnString;
1299
    static const bool only_get_type = true;
1300
    static const bool no_quotes = false;
1301
};
1302
1303
struct JsonbExtractJsonb : public JsonbExtractStringImpl<JsonbTypeJson> {
1304
    static constexpr auto name = "jsonb_extract";
1305
    static constexpr auto alias = "json_extract";
1306
};
1307
1308
struct JsonbExtractJsonbNoQuotes : public JsonbExtractStringImpl<JsonbTypeJsonNoQuotes> {
1309
    static constexpr auto name = "jsonb_extract_no_quotes";
1310
    static constexpr auto alias = "json_extract_no_quotes";
1311
};
1312
1313
struct JsonbTypeImpl : public JsonbExtractStringImpl<JsonbTypeType> {
1314
    static constexpr auto name = "json_type";
1315
    static constexpr auto alias = "jsonb_type";
1316
};
1317
1318
using FunctionJsonbExists = FunctionJsonbExtractPath;
1319
using FunctionJsonbType = FunctionJsonbExtract<JsonbTypeImpl>;
1320
1321
using FunctionJsonbExtractIsnull = FunctionJsonbExtract<JsonbExtractIsnull>;
1322
using FunctionJsonbExtractJsonb = FunctionJsonbExtract<JsonbExtractJsonb>;
1323
using FunctionJsonbExtractJsonbNoQuotes = FunctionJsonbExtract<JsonbExtractJsonbNoQuotes>;
1324
1325
template <typename Impl>
1326
class FunctionJsonbLength : public IFunction {
1327
public:
1328
    static constexpr auto name = "json_length";
1329
1
    String get_name() const override { return name; }
1330
4
    static FunctionPtr create() { return std::make_shared<FunctionJsonbLength<Impl>>(); }
1331
1332
2
    DataTypePtr get_return_type_impl(const DataTypes& arguments) const override {
1333
2
        return make_nullable(std::make_shared<DataTypeInt32>());
1334
2
    }
1335
3
    DataTypes get_variadic_argument_types_impl() const override {
1336
3
        return Impl::get_variadic_argument_types();
1337
3
    }
1338
2
    size_t get_number_of_arguments() const override {
1339
2
        return get_variadic_argument_types_impl().size();
1340
2
    }
1341
1342
4
    bool use_default_implementation_for_nulls() const override { return false; }
1343
    Status execute_impl(FunctionContext* context, Block& block, const ColumnNumbers& arguments,
1344
2
                        uint32_t result, size_t input_rows_count) const override {
1345
2
        return Impl::execute_impl(context, block, arguments, result, input_rows_count);
1346
2
    }
1347
};
1348
1349
struct JsonbLengthUtil {
1350
    static Status jsonb_length_execute(FunctionContext* context, Block& block,
1351
                                       const ColumnNumbers& arguments, uint32_t result,
1352
2
                                       size_t input_rows_count) {
1353
2
        DORIS_CHECK_GE(arguments.size(), 2);
1354
2
        ColumnPtr jsonb_data_column;
1355
2
        bool jsonb_data_const = false;
1356
        // prepare jsonb data column
1357
2
        std::tie(jsonb_data_column, jsonb_data_const) =
1358
2
                unpack_if_const(block.get_by_position(arguments[0]).column);
1359
2
        ColumnPtr path_column;
1360
2
        bool is_const = false;
1361
2
        std::tie(path_column, is_const) =
1362
2
                unpack_if_const(block.get_by_position(arguments[1]).column);
1363
1364
2
        auto null_map = ColumnUInt8::create(input_rows_count, 0);
1365
2
        auto return_type = block.get_data_type(result);
1366
2
        MutableColumnPtr res = return_type->create_column();
1367
1368
2
        JsonbPath path;
1369
2
        if (is_const) {
1370
1
            if (path_column->is_null_at(0)) {
1371
2
                for (size_t i = 0; i < input_rows_count; ++i) {
1372
1
                    null_map->get_data()[i] = 1;
1373
1
                    res->insert_data(nullptr, 0);
1374
1
                }
1375
1376
1
                block.replace_by_position(
1377
1
                        result, ColumnNullable::create(std::move(res), std::move(null_map)));
1378
1
                return Status::OK();
1379
1
            }
1380
1381
0
            auto path_value = path_column->get_data_at(0);
1382
0
            if (!path.seek(path_value.data, path_value.size)) {
1383
0
                return Status::InvalidArgument("Json path error: Invalid Json Path for value: {}",
1384
0
                                               std::string_view(path_value.data, path_value.size));
1385
0
            }
1386
0
        }
1387
1388
5
        for (size_t i = 0; i < input_rows_count; ++i) {
1389
4
            if (jsonb_data_column->is_null_at(i) || path_column->is_null_at(i) ||
1390
4
                (jsonb_data_column->get_data_at(i).size == 0)) {
1391
1
                null_map->get_data()[i] = 1;
1392
1
                res->insert_data(nullptr, 0);
1393
1
                continue;
1394
1
            }
1395
3
            if (!is_const) {
1396
3
                auto path_value = path_column->get_data_at(i);
1397
3
                path.clean();
1398
3
                if (!path.seek(path_value.data, path_value.size)) {
1399
0
                    return Status::InvalidArgument(
1400
0
                            "Json path error: Invalid Json Path for value: {}",
1401
0
                            std::string_view(path_value.data, path_value.size));
1402
0
                }
1403
3
            }
1404
3
            auto jsonb_value = jsonb_data_column->get_data_at(i);
1405
            // doc is NOT necessary to be deleted since JsonbDocument will not allocate memory
1406
3
            const JsonbDocument* doc = nullptr;
1407
3
            RETURN_IF_ERROR(JsonbDocument::checkAndCreateDocument(jsonb_value.data,
1408
3
                                                                  jsonb_value.size, &doc));
1409
3
            auto find_result = doc->getValue()->findValue(path);
1410
3
            const auto* value = find_result.value;
1411
3
            if (UNLIKELY(!value)) {
1412
0
                null_map->get_data()[i] = 1;
1413
0
                res->insert_data(nullptr, 0);
1414
0
                continue;
1415
0
            }
1416
3
            auto length = value->numElements();
1417
3
            res->insert_data(const_cast<const char*>((char*)&length), 0);
1418
3
        }
1419
1
        block.replace_by_position(result,
1420
1
                                  ColumnNullable::create(std::move(res), std::move(null_map)));
1421
1
        return Status::OK();
1422
1
    }
1423
};
1424
1425
struct JsonbLengthAndPathImpl {
1426
3
    static DataTypes get_variadic_argument_types() {
1427
3
        return {std::make_shared<DataTypeJsonb>(), std::make_shared<DataTypeString>()};
1428
3
    }
1429
1430
    static Status execute_impl(FunctionContext* context, Block& block,
1431
                               const ColumnNumbers& arguments, uint32_t result,
1432
2
                               size_t input_rows_count) {
1433
2
        return JsonbLengthUtil::jsonb_length_execute(context, block, arguments, result,
1434
2
                                                     input_rows_count);
1435
2
    }
1436
};
1437
1438
template <typename Impl>
1439
class FunctionJsonbContains : public IFunction {
1440
public:
1441
    static constexpr auto name = "json_contains";
1442
1
    String get_name() const override { return name; }
1443
4
    static FunctionPtr create() { return std::make_shared<FunctionJsonbContains<Impl>>(); }
1444
1445
2
    DataTypePtr get_return_type_impl(const DataTypes& arguments) const override {
1446
2
        return make_nullable(std::make_shared<DataTypeUInt8>());
1447
2
    }
1448
3
    DataTypes get_variadic_argument_types_impl() const override {
1449
3
        return Impl::get_variadic_argument_types();
1450
3
    }
1451
2
    size_t get_number_of_arguments() const override {
1452
2
        return get_variadic_argument_types_impl().size();
1453
2
    }
1454
1455
4
    bool use_default_implementation_for_nulls() const override { return false; }
1456
1457
    Status execute_impl(FunctionContext* context, Block& block, const ColumnNumbers& arguments,
1458
2
                        uint32_t result, size_t input_rows_count) const override {
1459
2
        return Impl::execute_impl(context, block, arguments, result, input_rows_count);
1460
2
    }
1461
};
1462
1463
struct JsonbContainsUtil {
1464
    static Status jsonb_contains_execute(FunctionContext* context, Block& block,
1465
                                         const ColumnNumbers& arguments, uint32_t result,
1466
2
                                         size_t input_rows_count) {
1467
2
        DORIS_CHECK_GE(arguments.size(), 3);
1468
1469
2
        auto jsonb_data1_column = block.get_by_position(arguments[0]).column;
1470
2
        auto jsonb_data2_column = block.get_by_position(arguments[1]).column;
1471
1472
2
        ColumnPtr path_column;
1473
2
        bool is_const = false;
1474
2
        std::tie(path_column, is_const) =
1475
2
                unpack_if_const(block.get_by_position(arguments[2]).column);
1476
1477
2
        auto null_map = ColumnUInt8::create(input_rows_count, 0);
1478
2
        auto return_type = block.get_data_type(result);
1479
2
        MutableColumnPtr res = return_type->create_column();
1480
1481
2
        JsonbPath path;
1482
2
        if (is_const) {
1483
1
            if (path_column->is_null_at(0)) {
1484
2
                for (size_t i = 0; i < input_rows_count; ++i) {
1485
1
                    null_map->get_data()[i] = 1;
1486
1
                    res->insert_data(nullptr, 0);
1487
1
                }
1488
1489
1
                block.replace_by_position(
1490
1
                        result, ColumnNullable::create(std::move(res), std::move(null_map)));
1491
1
                return Status::OK();
1492
1
            }
1493
1494
0
            auto path_value = path_column->get_data_at(0);
1495
0
            if (!path.seek(path_value.data, path_value.size)) {
1496
0
                return Status::InvalidArgument("Json path error: Invalid Json Path for value: {}",
1497
0
                                               std::string_view(path_value.data, path_value.size));
1498
0
            }
1499
0
        }
1500
1501
5
        for (size_t i = 0; i < input_rows_count; ++i) {
1502
4
            if (jsonb_data1_column->is_null_at(i) || jsonb_data2_column->is_null_at(i) ||
1503
4
                path_column->is_null_at(i)) {
1504
1
                null_map->get_data()[i] = 1;
1505
1
                res->insert_data(nullptr, 0);
1506
1
                continue;
1507
1
            }
1508
1509
3
            if (!is_const) {
1510
3
                auto path_value = path_column->get_data_at(i);
1511
3
                path.clean();
1512
3
                if (!path.seek(path_value.data, path_value.size)) {
1513
0
                    return Status::InvalidArgument(
1514
0
                            "Json path error: Invalid Json Path for value: {}",
1515
0
                            std::string_view(path_value.data, path_value.size));
1516
0
                }
1517
3
            }
1518
1519
3
            auto jsonb_value1 = jsonb_data1_column->get_data_at(i);
1520
3
            auto jsonb_value2 = jsonb_data2_column->get_data_at(i);
1521
1522
3
            if (jsonb_value1.size == 0 || jsonb_value2.size == 0) {
1523
1
                null_map->get_data()[i] = 1;
1524
1
                res->insert_data(nullptr, 0);
1525
1
                continue;
1526
1
            }
1527
            // doc is NOT necessary to be deleted since JsonbDocument will not allocate memory
1528
2
            const JsonbDocument* doc1 = nullptr;
1529
2
            RETURN_IF_ERROR(JsonbDocument::checkAndCreateDocument(jsonb_value1.data,
1530
2
                                                                  jsonb_value1.size, &doc1));
1531
2
            const JsonbDocument* doc2 = nullptr;
1532
2
            RETURN_IF_ERROR(JsonbDocument::checkAndCreateDocument(jsonb_value2.data,
1533
2
                                                                  jsonb_value2.size, &doc2));
1534
1535
2
            auto find_result = doc1->getValue()->findValue(path);
1536
2
            const auto* value1 = find_result.value;
1537
2
            const JsonbValue* value2 = doc2->getValue();
1538
2
            if (!value1 || !value2) {
1539
0
                null_map->get_data()[i] = 1;
1540
0
                res->insert_data(nullptr, 0);
1541
0
                continue;
1542
0
            }
1543
2
            auto contains_value = value1->contains(value2);
1544
2
            res->insert_data(const_cast<const char*>((char*)&contains_value), 0);
1545
2
        }
1546
1547
1
        block.replace_by_position(result,
1548
1
                                  ColumnNullable::create(std::move(res), std::move(null_map)));
1549
1
        return Status::OK();
1550
1
    }
1551
};
1552
1553
template <bool ignore_null>
1554
class FunctionJsonbArray : public IFunction {
1555
public:
1556
    static constexpr auto name = "json_array";
1557
    static constexpr auto alias = "jsonb_array";
1558
1559
6
    static FunctionPtr create() { return std::make_shared<FunctionJsonbArray>(); }
_ZN5doris18FunctionJsonbArrayILb0EE6createEv
Line
Count
Source
1559
3
    static FunctionPtr create() { return std::make_shared<FunctionJsonbArray>(); }
_ZN5doris18FunctionJsonbArrayILb1EE6createEv
Line
Count
Source
1559
3
    static FunctionPtr create() { return std::make_shared<FunctionJsonbArray>(); }
1560
1561
0
    String get_name() const override { return name; }
Unexecuted instantiation: _ZNK5doris18FunctionJsonbArrayILb0EE8get_nameB5cxx11Ev
Unexecuted instantiation: _ZNK5doris18FunctionJsonbArrayILb1EE8get_nameB5cxx11Ev
1562
1563
0
    size_t get_number_of_arguments() const override { return 0; }
Unexecuted instantiation: _ZNK5doris18FunctionJsonbArrayILb0EE23get_number_of_argumentsEv
Unexecuted instantiation: _ZNK5doris18FunctionJsonbArrayILb1EE23get_number_of_argumentsEv
1564
4
    bool is_variadic() const override { return true; }
_ZNK5doris18FunctionJsonbArrayILb0EE11is_variadicEv
Line
Count
Source
1564
2
    bool is_variadic() const override { return true; }
_ZNK5doris18FunctionJsonbArrayILb1EE11is_variadicEv
Line
Count
Source
1564
2
    bool is_variadic() const override { return true; }
1565
1566
4
    bool use_default_implementation_for_nulls() const override { return false; }
_ZNK5doris18FunctionJsonbArrayILb0EE36use_default_implementation_for_nullsEv
Line
Count
Source
1566
2
    bool use_default_implementation_for_nulls() const override { return false; }
_ZNK5doris18FunctionJsonbArrayILb1EE36use_default_implementation_for_nullsEv
Line
Count
Source
1566
2
    bool use_default_implementation_for_nulls() const override { return false; }
1567
1568
2
    DataTypePtr get_return_type_impl(const DataTypes& arguments) const override {
1569
2
        return std::make_shared<DataTypeJsonb>();
1570
2
    }
_ZNK5doris18FunctionJsonbArrayILb0EE20get_return_type_implERKSt6vectorISt10shared_ptrIKNS_9IDataTypeEESaIS6_EE
Line
Count
Source
1568
1
    DataTypePtr get_return_type_impl(const DataTypes& arguments) const override {
1569
1
        return std::make_shared<DataTypeJsonb>();
1570
1
    }
_ZNK5doris18FunctionJsonbArrayILb1EE20get_return_type_implERKSt6vectorISt10shared_ptrIKNS_9IDataTypeEESaIS6_EE
Line
Count
Source
1568
1
    DataTypePtr get_return_type_impl(const DataTypes& arguments) const override {
1569
1
        return std::make_shared<DataTypeJsonb>();
1570
1
    }
1571
1572
    Status execute_impl(FunctionContext* context, Block& block, const ColumnNumbers& arguments,
1573
2
                        uint32_t result, size_t input_rows_count) const override {
1574
2
        auto return_data_type = std::make_shared<DataTypeJsonb>();
1575
2
        auto column = return_data_type->create_column();
1576
2
        column->reserve(input_rows_count);
1577
1578
2
        JsonbWriter writer;
1579
23
        for (size_t i = 0; i < input_rows_count; ++i) {
1580
20
            writer.writeStartArray();
1581
20
            for (auto argument : arguments) {
1582
20
                auto&& [arg_column, is_const] =
1583
20
                        unpack_if_const(block.get_by_position(argument).column);
1584
20
                if (const auto* nullable_column =
1585
20
                            check_and_get_column<ColumnNullable>(arg_column.get())) {
1586
20
                    const auto& null_map = nullable_column->get_null_map_data();
1587
20
                    const auto& nested_column = nullable_column->get_nested_column();
1588
20
                    const auto& jsonb_column =
1589
20
                            assert_cast<const ColumnString&, TypeCheckOnRelease::DISABLE>(
1590
20
                                    nested_column);
1591
1592
20
                    auto index = index_check_const(i, is_const);
1593
20
                    if (null_map[index]) {
1594
2
                        if constexpr (ignore_null) {
1595
1
                            continue;
1596
1
                        } else {
1597
1
                            writer.writeNull();
1598
1
                        }
1599
18
                    } else {
1600
18
                        auto jsonb_binary = jsonb_column.get_data_at(index);
1601
18
                        const JsonbDocument* doc = nullptr;
1602
18
                        auto st = JsonbDocument::checkAndCreateDocument(jsonb_binary.data,
1603
18
                                                                        jsonb_binary.size, &doc);
1604
18
                        if (!st.ok() || !doc || !doc->getValue()) [[unlikely]] {
1605
0
                            if constexpr (ignore_null) {
1606
0
                                continue;
1607
0
                            } else {
1608
0
                                writer.writeNull();
1609
0
                            }
1610
18
                        } else {
1611
18
                            writer.writeValue(doc->getValue());
1612
18
                        }
1613
18
                    }
1614
20
                } else {
1615
0
                    const auto& jsonb_column =
1616
0
                            assert_cast<const ColumnString&, TypeCheckOnRelease::DISABLE>(
1617
0
                                    *arg_column);
1618
1619
0
                    auto index = index_check_const(i, is_const);
1620
0
                    auto jsonb_binary = jsonb_column.get_data_at(index);
1621
0
                    const JsonbDocument* doc = nullptr;
1622
0
                    auto st = JsonbDocument::checkAndCreateDocument(jsonb_binary.data,
1623
0
                                                                    jsonb_binary.size, &doc);
1624
0
                    if (!st.ok() || !doc || !doc->getValue()) [[unlikely]] {
1625
0
                        if constexpr (ignore_null) {
1626
0
                            continue;
1627
0
                        } else {
1628
0
                            writer.writeNull();
1629
0
                        }
1630
0
                    } else {
1631
0
                        writer.writeValue(doc->getValue());
1632
0
                    }
1633
0
                }
1634
20
            }
1635
11
            writer.writeEndArray();
1636
11
            column->insert_data(writer.getOutput()->getBuffer(), writer.getOutput()->getSize());
1637
11
            writer.reset();
1638
11
        }
1639
1640
2
        block.get_by_position(result).column = std::move(column);
1641
2
        return Status::OK();
1642
2
    }
_ZNK5doris18FunctionJsonbArrayILb0EE12execute_implEPNS_15FunctionContextERNS_5BlockERKSt6vectorIjSaIjEEjm
Line
Count
Source
1573
1
                        uint32_t result, size_t input_rows_count) const override {
1574
1
        auto return_data_type = std::make_shared<DataTypeJsonb>();
1575
1
        auto column = return_data_type->create_column();
1576
1
        column->reserve(input_rows_count);
1577
1578
1
        JsonbWriter writer;
1579
11
        for (size_t i = 0; i < input_rows_count; ++i) {
1580
10
            writer.writeStartArray();
1581
10
            for (auto argument : arguments) {
1582
10
                auto&& [arg_column, is_const] =
1583
10
                        unpack_if_const(block.get_by_position(argument).column);
1584
10
                if (const auto* nullable_column =
1585
10
                            check_and_get_column<ColumnNullable>(arg_column.get())) {
1586
10
                    const auto& null_map = nullable_column->get_null_map_data();
1587
10
                    const auto& nested_column = nullable_column->get_nested_column();
1588
10
                    const auto& jsonb_column =
1589
10
                            assert_cast<const ColumnString&, TypeCheckOnRelease::DISABLE>(
1590
10
                                    nested_column);
1591
1592
10
                    auto index = index_check_const(i, is_const);
1593
10
                    if (null_map[index]) {
1594
                        if constexpr (ignore_null) {
1595
                            continue;
1596
1
                        } else {
1597
1
                            writer.writeNull();
1598
1
                        }
1599
9
                    } else {
1600
9
                        auto jsonb_binary = jsonb_column.get_data_at(index);
1601
9
                        const JsonbDocument* doc = nullptr;
1602
9
                        auto st = JsonbDocument::checkAndCreateDocument(jsonb_binary.data,
1603
9
                                                                        jsonb_binary.size, &doc);
1604
9
                        if (!st.ok() || !doc || !doc->getValue()) [[unlikely]] {
1605
                            if constexpr (ignore_null) {
1606
                                continue;
1607
0
                            } else {
1608
0
                                writer.writeNull();
1609
0
                            }
1610
9
                        } else {
1611
9
                            writer.writeValue(doc->getValue());
1612
9
                        }
1613
9
                    }
1614
10
                } else {
1615
0
                    const auto& jsonb_column =
1616
0
                            assert_cast<const ColumnString&, TypeCheckOnRelease::DISABLE>(
1617
0
                                    *arg_column);
1618
1619
0
                    auto index = index_check_const(i, is_const);
1620
0
                    auto jsonb_binary = jsonb_column.get_data_at(index);
1621
0
                    const JsonbDocument* doc = nullptr;
1622
0
                    auto st = JsonbDocument::checkAndCreateDocument(jsonb_binary.data,
1623
0
                                                                    jsonb_binary.size, &doc);
1624
0
                    if (!st.ok() || !doc || !doc->getValue()) [[unlikely]] {
1625
                        if constexpr (ignore_null) {
1626
                            continue;
1627
0
                        } else {
1628
0
                            writer.writeNull();
1629
0
                        }
1630
0
                    } else {
1631
0
                        writer.writeValue(doc->getValue());
1632
0
                    }
1633
0
                }
1634
10
            }
1635
10
            writer.writeEndArray();
1636
10
            column->insert_data(writer.getOutput()->getBuffer(), writer.getOutput()->getSize());
1637
10
            writer.reset();
1638
10
        }
1639
1640
1
        block.get_by_position(result).column = std::move(column);
1641
1
        return Status::OK();
1642
1
    }
_ZNK5doris18FunctionJsonbArrayILb1EE12execute_implEPNS_15FunctionContextERNS_5BlockERKSt6vectorIjSaIjEEjm
Line
Count
Source
1573
1
                        uint32_t result, size_t input_rows_count) const override {
1574
1
        auto return_data_type = std::make_shared<DataTypeJsonb>();
1575
1
        auto column = return_data_type->create_column();
1576
1
        column->reserve(input_rows_count);
1577
1578
1
        JsonbWriter writer;
1579
12
        for (size_t i = 0; i < input_rows_count; ++i) {
1580
10
            writer.writeStartArray();
1581
10
            for (auto argument : arguments) {
1582
10
                auto&& [arg_column, is_const] =
1583
10
                        unpack_if_const(block.get_by_position(argument).column);
1584
10
                if (const auto* nullable_column =
1585
10
                            check_and_get_column<ColumnNullable>(arg_column.get())) {
1586
10
                    const auto& null_map = nullable_column->get_null_map_data();
1587
10
                    const auto& nested_column = nullable_column->get_nested_column();
1588
10
                    const auto& jsonb_column =
1589
10
                            assert_cast<const ColumnString&, TypeCheckOnRelease::DISABLE>(
1590
10
                                    nested_column);
1591
1592
10
                    auto index = index_check_const(i, is_const);
1593
10
                    if (null_map[index]) {
1594
1
                        if constexpr (ignore_null) {
1595
1
                            continue;
1596
                        } else {
1597
                            writer.writeNull();
1598
                        }
1599
9
                    } else {
1600
9
                        auto jsonb_binary = jsonb_column.get_data_at(index);
1601
9
                        const JsonbDocument* doc = nullptr;
1602
9
                        auto st = JsonbDocument::checkAndCreateDocument(jsonb_binary.data,
1603
9
                                                                        jsonb_binary.size, &doc);
1604
9
                        if (!st.ok() || !doc || !doc->getValue()) [[unlikely]] {
1605
0
                            if constexpr (ignore_null) {
1606
0
                                continue;
1607
                            } else {
1608
                                writer.writeNull();
1609
                            }
1610
9
                        } else {
1611
9
                            writer.writeValue(doc->getValue());
1612
9
                        }
1613
9
                    }
1614
10
                } else {
1615
0
                    const auto& jsonb_column =
1616
0
                            assert_cast<const ColumnString&, TypeCheckOnRelease::DISABLE>(
1617
0
                                    *arg_column);
1618
1619
0
                    auto index = index_check_const(i, is_const);
1620
0
                    auto jsonb_binary = jsonb_column.get_data_at(index);
1621
0
                    const JsonbDocument* doc = nullptr;
1622
0
                    auto st = JsonbDocument::checkAndCreateDocument(jsonb_binary.data,
1623
0
                                                                    jsonb_binary.size, &doc);
1624
0
                    if (!st.ok() || !doc || !doc->getValue()) [[unlikely]] {
1625
0
                        if constexpr (ignore_null) {
1626
0
                            continue;
1627
                        } else {
1628
                            writer.writeNull();
1629
                        }
1630
0
                    } else {
1631
0
                        writer.writeValue(doc->getValue());
1632
0
                    }
1633
0
                }
1634
10
            }
1635
11
            writer.writeEndArray();
1636
11
            column->insert_data(writer.getOutput()->getBuffer(), writer.getOutput()->getSize());
1637
11
            writer.reset();
1638
11
        }
1639
1640
2
        block.get_by_position(result).column = std::move(column);
1641
2
        return Status::OK();
1642
1
    }
1643
};
1644
1645
class FunctionJsonbObject : public IFunction {
1646
public:
1647
    static constexpr auto name = "json_object";
1648
    static constexpr auto alias = "jsonb_object";
1649
1650
2
    static FunctionPtr create() { return std::make_shared<FunctionJsonbObject>(); }
1651
1652
0
    String get_name() const override { return name; }
1653
1654
0
    size_t get_number_of_arguments() const override { return 0; }
1655
1
    bool is_variadic() const override { return true; }
1656
1657
0
    bool use_default_implementation_for_nulls() const override { return false; }
1658
1659
0
    DataTypePtr get_return_type_impl(const DataTypes& arguments) const override {
1660
0
        return std::make_shared<DataTypeJsonb>();
1661
0
    }
1662
1663
    Status execute_impl(FunctionContext* context, Block& block, const ColumnNumbers& arguments,
1664
0
                        uint32_t result, size_t input_rows_count) const override {
1665
0
        if (arguments.size() % 2 != 0) {
1666
0
            return Status::InvalidArgument(
1667
0
                    "JSON object must have an even number of arguments, but got: {}",
1668
0
                    arguments.size());
1669
0
        }
1670
1671
0
        auto return_data_type = std::make_shared<DataTypeJsonb>();
1672
1673
0
        auto write_key = [](JsonbWriter& writer, const ColumnString& key_col, const bool is_const,
1674
0
                            const NullMap* null_map, const size_t arg_index, const size_t row_idx) {
1675
0
            auto index = index_check_const(row_idx, is_const);
1676
0
            if (null_map && (*null_map)[index]) {
1677
0
                return Status::InvalidArgument(
1678
0
                        "JSON documents may not contain NULL member name(argument "
1679
0
                        "index:  "
1680
0
                        "{}, row index: {})",
1681
0
                        row_idx, arg_index);
1682
0
            }
1683
1684
0
            auto key_string = key_col.get_data_at(index);
1685
0
            if (key_string.size > 255) {
1686
0
                return Status::InvalidArgument(
1687
0
                        "JSON object keys(argument index: {}) must be less than 256 "
1688
0
                        "bytes, but got size: {}",
1689
0
                        arg_index, key_string.size);
1690
0
            }
1691
0
            writer.writeKey(key_string.data, static_cast<uint8_t>(key_string.size));
1692
0
            return Status::OK();
1693
0
        };
1694
1695
0
        auto write_value = [](JsonbWriter& writer, const ColumnString& value_col,
1696
0
                              const bool is_const, const NullMap* null_map, const size_t arg_index,
1697
0
                              const size_t row_idx) {
1698
0
            auto index = index_check_const(row_idx, is_const);
1699
0
            if (null_map && (*null_map)[index]) {
1700
0
                writer.writeNull();
1701
0
                return Status::OK();
1702
0
            }
1703
1704
0
            auto value_string = value_col.get_data_at(index);
1705
0
            const JsonbDocument* doc = nullptr;
1706
0
            RETURN_IF_ERROR(JsonbDocument::checkAndCreateDocument(value_string.data,
1707
0
                                                                  value_string.size, &doc));
1708
0
            writer.writeValue(doc->getValue());
1709
0
            return Status::OK();
1710
0
        };
1711
1712
0
        for (size_t arg_idx = 0; arg_idx != arguments.size(); arg_idx += 2) {
1713
0
            auto key_argument = arguments[arg_idx];
1714
0
            auto value_argument = arguments[arg_idx + 1];
1715
1716
0
            auto& key_data_type = block.get_by_position(key_argument).type;
1717
0
            auto& value_data_type = block.get_by_position(value_argument).type;
1718
0
            if (!is_string_type(key_data_type->get_primitive_type())) {
1719
0
                return Status::InvalidArgument(
1720
0
                        "JSON object key(argument index: {}) must be String, but got type: "
1721
0
                        "{}(primitive type: {})",
1722
0
                        arg_idx, key_data_type->get_name(),
1723
0
                        static_cast<int>(key_data_type->get_primitive_type()));
1724
0
            }
1725
1726
0
            if (value_data_type->get_primitive_type() != PrimitiveType::TYPE_JSONB) {
1727
0
                return Status::InvalidArgument(
1728
0
                        "JSON object value(argument index: {}) must be JSON, but got type: {}",
1729
0
                        arg_idx, value_data_type->get_name());
1730
0
            }
1731
0
        }
1732
1733
0
        auto column = return_data_type->create_column();
1734
0
        column->reserve(input_rows_count);
1735
1736
0
        JsonbWriter writer;
1737
0
        for (size_t i = 0; i != input_rows_count; ++i) {
1738
0
            writer.writeStartObject();
1739
0
            for (size_t arg_idx = 0; arg_idx != arguments.size(); arg_idx += 2) {
1740
0
                auto key_argument = arguments[arg_idx];
1741
0
                auto value_argument = arguments[arg_idx + 1];
1742
0
                auto&& [key_column, key_const] =
1743
0
                        unpack_if_const(block.get_by_position(key_argument).column);
1744
0
                auto&& [value_column, value_const] =
1745
0
                        unpack_if_const(block.get_by_position(value_argument).column);
1746
1747
0
                if (const auto* nullable_column =
1748
0
                            check_and_get_column<ColumnNullable>(key_column.get())) {
1749
0
                    const auto& null_map = nullable_column->get_null_map_data();
1750
0
                    const auto& nested_column = nullable_column->get_nested_column();
1751
0
                    const auto& key_arg_column =
1752
0
                            assert_cast<const ColumnString&, TypeCheckOnRelease::DISABLE>(
1753
0
                                    nested_column);
1754
1755
0
                    RETURN_IF_ERROR(
1756
0
                            write_key(writer, key_arg_column, key_const, &null_map, arg_idx, i));
1757
0
                } else {
1758
0
                    const auto& key_arg_column =
1759
0
                            assert_cast<const ColumnString&, TypeCheckOnRelease::DISABLE>(
1760
0
                                    *key_column);
1761
0
                    RETURN_IF_ERROR(
1762
0
                            write_key(writer, key_arg_column, key_const, nullptr, arg_idx, i));
1763
0
                }
1764
1765
0
                if (const auto* nullable_column =
1766
0
                            check_and_get_column<ColumnNullable>(value_column.get())) {
1767
0
                    const auto& null_map = nullable_column->get_null_map_data();
1768
0
                    const auto& nested_column = nullable_column->get_nested_column();
1769
0
                    const auto& value_arg_column =
1770
0
                            assert_cast<const ColumnString&, TypeCheckOnRelease::DISABLE>(
1771
0
                                    nested_column);
1772
1773
0
                    RETURN_IF_ERROR(write_value(writer, value_arg_column, value_const, &null_map,
1774
0
                                                arg_idx + 1, i));
1775
0
                } else {
1776
0
                    const auto& value_arg_column =
1777
0
                            assert_cast<const ColumnString&, TypeCheckOnRelease::DISABLE>(
1778
0
                                    *value_column);
1779
0
                    RETURN_IF_ERROR(write_value(writer, value_arg_column, value_const, nullptr,
1780
0
                                                arg_idx + 1, i));
1781
0
                }
1782
0
            }
1783
1784
0
            writer.writeEndObject();
1785
0
            column->insert_data(writer.getOutput()->getBuffer(), writer.getOutput()->getSize());
1786
0
            writer.reset();
1787
0
        }
1788
1789
0
        block.get_by_position(result).column = std::move(column);
1790
0
        return Status::OK();
1791
0
    }
1792
};
1793
1794
enum class JsonbModifyType { Insert, Set, Replace };
1795
1796
template <JsonbModifyType modify_type>
1797
struct JsonbModifyName {
1798
    static constexpr auto name = "jsonb_modify";
1799
    static constexpr auto alias = "json_modify";
1800
};
1801
1802
template <>
1803
struct JsonbModifyName<JsonbModifyType::Insert> {
1804
    static constexpr auto name = "jsonb_insert";
1805
    static constexpr auto alias = "json_insert";
1806
};
1807
template <>
1808
struct JsonbModifyName<JsonbModifyType::Set> {
1809
    static constexpr auto name = "jsonb_set";
1810
    static constexpr auto alias = "json_set";
1811
};
1812
template <>
1813
struct JsonbModifyName<JsonbModifyType::Replace> {
1814
    static constexpr auto name = "jsonb_replace";
1815
    static constexpr auto alias = "json_replace";
1816
};
1817
1818
template <JsonbModifyType modify_type>
1819
class FunctionJsonbModify : public IFunction {
1820
public:
1821
    static constexpr auto name = JsonbModifyName<modify_type>::name;
1822
    static constexpr auto alias = JsonbModifyName<modify_type>::alias;
1823
1824
8
    static FunctionPtr create() { return std::make_shared<FunctionJsonbModify<modify_type>>(); }
_ZN5doris19FunctionJsonbModifyILNS_15JsonbModifyTypeE0EE6createEv
Line
Count
Source
1824
3
    static FunctionPtr create() { return std::make_shared<FunctionJsonbModify<modify_type>>(); }
_ZN5doris19FunctionJsonbModifyILNS_15JsonbModifyTypeE1EE6createEv
Line
Count
Source
1824
3
    static FunctionPtr create() { return std::make_shared<FunctionJsonbModify<modify_type>>(); }
_ZN5doris19FunctionJsonbModifyILNS_15JsonbModifyTypeE2EE6createEv
Line
Count
Source
1824
2
    static FunctionPtr create() { return std::make_shared<FunctionJsonbModify<modify_type>>(); }
1825
1826
0
    String get_name() const override { return name; }
Unexecuted instantiation: _ZNK5doris19FunctionJsonbModifyILNS_15JsonbModifyTypeE0EE8get_nameB5cxx11Ev
Unexecuted instantiation: _ZNK5doris19FunctionJsonbModifyILNS_15JsonbModifyTypeE1EE8get_nameB5cxx11Ev
Unexecuted instantiation: _ZNK5doris19FunctionJsonbModifyILNS_15JsonbModifyTypeE2EE8get_nameB5cxx11Ev
1827
1828
0
    size_t get_number_of_arguments() const override { return 0; }
Unexecuted instantiation: _ZNK5doris19FunctionJsonbModifyILNS_15JsonbModifyTypeE0EE23get_number_of_argumentsEv
Unexecuted instantiation: _ZNK5doris19FunctionJsonbModifyILNS_15JsonbModifyTypeE1EE23get_number_of_argumentsEv
Unexecuted instantiation: _ZNK5doris19FunctionJsonbModifyILNS_15JsonbModifyTypeE2EE23get_number_of_argumentsEv
1829
5
    bool is_variadic() const override { return true; }
_ZNK5doris19FunctionJsonbModifyILNS_15JsonbModifyTypeE0EE11is_variadicEv
Line
Count
Source
1829
2
    bool is_variadic() const override { return true; }
_ZNK5doris19FunctionJsonbModifyILNS_15JsonbModifyTypeE1EE11is_variadicEv
Line
Count
Source
1829
2
    bool is_variadic() const override { return true; }
_ZNK5doris19FunctionJsonbModifyILNS_15JsonbModifyTypeE2EE11is_variadicEv
Line
Count
Source
1829
1
    bool is_variadic() const override { return true; }
1830
1831
4
    bool use_default_implementation_for_nulls() const override { return false; }
_ZNK5doris19FunctionJsonbModifyILNS_15JsonbModifyTypeE0EE36use_default_implementation_for_nullsEv
Line
Count
Source
1831
2
    bool use_default_implementation_for_nulls() const override { return false; }
_ZNK5doris19FunctionJsonbModifyILNS_15JsonbModifyTypeE1EE36use_default_implementation_for_nullsEv
Line
Count
Source
1831
2
    bool use_default_implementation_for_nulls() const override { return false; }
Unexecuted instantiation: _ZNK5doris19FunctionJsonbModifyILNS_15JsonbModifyTypeE2EE36use_default_implementation_for_nullsEv
1832
1833
2
    DataTypePtr get_return_type_impl(const DataTypes& arguments) const override {
1834
2
        return make_nullable(std::make_shared<DataTypeJsonb>());
1835
2
    }
_ZNK5doris19FunctionJsonbModifyILNS_15JsonbModifyTypeE0EE20get_return_type_implERKSt6vectorISt10shared_ptrIKNS_9IDataTypeEESaIS7_EE
Line
Count
Source
1833
1
    DataTypePtr get_return_type_impl(const DataTypes& arguments) const override {
1834
1
        return make_nullable(std::make_shared<DataTypeJsonb>());
1835
1
    }
_ZNK5doris19FunctionJsonbModifyILNS_15JsonbModifyTypeE1EE20get_return_type_implERKSt6vectorISt10shared_ptrIKNS_9IDataTypeEESaIS7_EE
Line
Count
Source
1833
1
    DataTypePtr get_return_type_impl(const DataTypes& arguments) const override {
1834
1
        return make_nullable(std::make_shared<DataTypeJsonb>());
1835
1
    }
Unexecuted instantiation: _ZNK5doris19FunctionJsonbModifyILNS_15JsonbModifyTypeE2EE20get_return_type_implERKSt6vectorISt10shared_ptrIKNS_9IDataTypeEESaIS7_EE
1836
1837
    Status create_all_null_result(const DataTypePtr& return_data_type, Block& block,
1838
0
                                  uint32_t result, size_t input_rows_count) const {
1839
0
        auto result_column = return_data_type->create_column();
1840
0
        result_column->insert_default();
1841
0
        auto const_column = ColumnConst::create(std::move(result_column), input_rows_count);
1842
0
        block.get_by_position(result).column = std::move(const_column);
1843
0
        return Status::OK();
1844
0
    }
Unexecuted instantiation: _ZNK5doris19FunctionJsonbModifyILNS_15JsonbModifyTypeE0EE22create_all_null_resultERKSt10shared_ptrIKNS_9IDataTypeEERNS_5BlockEjm
Unexecuted instantiation: _ZNK5doris19FunctionJsonbModifyILNS_15JsonbModifyTypeE1EE22create_all_null_resultERKSt10shared_ptrIKNS_9IDataTypeEERNS_5BlockEjm
Unexecuted instantiation: _ZNK5doris19FunctionJsonbModifyILNS_15JsonbModifyTypeE2EE22create_all_null_resultERKSt10shared_ptrIKNS_9IDataTypeEERNS_5BlockEjm
1845
1846
    Status execute_impl(FunctionContext* context, Block& block, const ColumnNumbers& arguments,
1847
2
                        uint32_t result, size_t input_rows_count) const override {
1848
2
        if (arguments.size() % 2 != 1 || arguments.size() < 3) {
1849
0
            return Status::InvalidArgument(
1850
0
                    "Function {} must have an odd number of arguments and more than 2 arguments, "
1851
0
                    "but got: {}",
1852
0
                    name, arguments.size());
1853
0
        }
1854
1855
2
        const size_t keys_count = (arguments.size() - 1) / 2;
1856
1857
2
        auto return_data_type = make_nullable(std::make_shared<DataTypeJsonb>());
1858
1859
2
        auto result_column = return_data_type->create_column();
1860
2
        auto& result_nullable_col = assert_cast<ColumnNullable&>(*result_column);
1861
2
        auto& null_map = result_nullable_col.get_null_map_data();
1862
2
        auto& res_string_column =
1863
2
                assert_cast<ColumnString&>(result_nullable_col.get_nested_column());
1864
2
        auto& res_chars = res_string_column.get_chars();
1865
2
        auto& res_offsets = res_string_column.get_offsets();
1866
1867
2
        null_map.resize_fill(input_rows_count, 0);
1868
2
        res_offsets.resize(input_rows_count);
1869
2
        auto&& [json_data_arg_column, json_data_const] =
1870
2
                unpack_if_const(block.get_by_position(arguments[0]).column);
1871
1872
2
        if (json_data_const) {
1873
0
            if (json_data_arg_column->is_null_at(0)) {
1874
0
                return create_all_null_result(return_data_type, block, result, input_rows_count);
1875
0
            }
1876
0
        }
1877
1878
2
        std::vector<const ColumnString*> json_path_columns(keys_count);
1879
2
        std::vector<bool> json_path_constant(keys_count);
1880
2
        std::vector<const NullMap*> json_path_null_maps(keys_count, nullptr);
1881
1882
2
        std::vector<const ColumnString*> json_value_columns(keys_count);
1883
2
        std::vector<bool> json_value_constant(keys_count);
1884
2
        std::vector<const NullMap*> json_value_null_maps(keys_count, nullptr);
1885
1886
2
        const NullMap* json_data_null_map = nullptr;
1887
2
        const ColumnString* json_data_column;
1888
2
        if (const auto* nullable_column =
1889
2
                    check_and_get_column<ColumnNullable>(json_data_arg_column.get())) {
1890
2
            json_data_null_map = &nullable_column->get_null_map_data();
1891
2
            const auto& nested_column = nullable_column->get_nested_column();
1892
2
            json_data_column = assert_cast<const ColumnString*>(&nested_column);
1893
2
        } else {
1894
0
            json_data_column = assert_cast<const ColumnString*>(json_data_arg_column.get());
1895
0
        }
1896
1897
4
        for (size_t i = 1; i < arguments.size(); i += 2) {
1898
2
            auto&& [path_column, path_const] =
1899
2
                    unpack_if_const(block.get_by_position(arguments[i]).column);
1900
2
            auto&& [value_column, value_const] =
1901
2
                    unpack_if_const(block.get_by_position(arguments[i + 1]).column);
1902
1903
2
            if (path_const) {
1904
0
                if (path_column->is_null_at(0)) {
1905
0
                    return create_all_null_result(return_data_type, block, result,
1906
0
                                                  input_rows_count);
1907
0
                }
1908
0
            }
1909
1910
2
            json_path_constant[i / 2] = path_const;
1911
2
            if (const auto* nullable_column =
1912
2
                        check_and_get_column<ColumnNullable>(path_column.get())) {
1913
2
                json_path_null_maps[i / 2] = &nullable_column->get_null_map_data();
1914
2
                const auto& nested_column = nullable_column->get_nested_column();
1915
2
                json_path_columns[i / 2] = assert_cast<const ColumnString*>(&nested_column);
1916
2
            } else {
1917
0
                json_path_columns[i / 2] = assert_cast<const ColumnString*>(path_column.get());
1918
0
            }
1919
1920
2
            json_value_constant[i / 2] = value_const;
1921
2
            if (const auto* nullable_column =
1922
2
                        check_and_get_column<ColumnNullable>(value_column.get())) {
1923
2
                json_value_null_maps[i / 2] = &nullable_column->get_null_map_data();
1924
2
                const auto& nested_column = nullable_column->get_nested_column();
1925
2
                json_value_columns[i / 2] = assert_cast<const ColumnString*>(&nested_column);
1926
2
            } else {
1927
0
                json_value_columns[i / 2] = assert_cast<const ColumnString*>(value_column.get());
1928
0
            }
1929
2
        }
1930
1931
2
        DorisVector<const JsonbDocument*> json_documents(input_rows_count);
1932
2
        if (json_data_const) {
1933
0
            auto json_data_string = json_data_column->get_data_at(0);
1934
0
            const JsonbDocument* doc = nullptr;
1935
0
            RETURN_IF_ERROR(JsonbDocument::checkAndCreateDocument(json_data_string.data,
1936
0
                                                                  json_data_string.size, &doc));
1937
0
            if (!doc || !doc->getValue()) [[unlikely]] {
1938
0
                return create_all_null_result(return_data_type, block, result, input_rows_count);
1939
0
            }
1940
0
            for (size_t i = 0; i != input_rows_count; ++i) {
1941
0
                json_documents[i] = doc;
1942
0
            }
1943
2
        } else {
1944
8
            for (size_t i = 0; i != input_rows_count; ++i) {
1945
6
                if (json_data_null_map && (*json_data_null_map)[i]) {
1946
0
                    null_map[i] = 1;
1947
0
                    json_documents[i] = nullptr;
1948
0
                    continue;
1949
0
                }
1950
1951
6
                auto json_data_string = json_data_column->get_data_at(i);
1952
6
                const JsonbDocument* doc = nullptr;
1953
6
                RETURN_IF_ERROR(JsonbDocument::checkAndCreateDocument(json_data_string.data,
1954
6
                                                                      json_data_string.size, &doc));
1955
6
                if (!doc || !doc->getValue()) [[unlikely]] {
1956
0
                    null_map[i] = 1;
1957
0
                    continue;
1958
0
                }
1959
6
                json_documents[i] = doc;
1960
6
            }
1961
2
        }
1962
1963
2
        DorisVector<DorisVector<JsonbPath>> json_paths(keys_count);
1964
2
        DorisVector<DorisVector<const JsonbValue*>> json_values(keys_count);
1965
1966
2
        RETURN_IF_ERROR(parse_paths_and_values(json_paths, json_values, arguments, input_rows_count,
1967
2
                                               json_path_columns, json_path_constant,
1968
2
                                               json_path_null_maps, json_value_columns,
1969
2
                                               json_value_constant, json_value_null_maps));
1970
1971
2
        JsonbWriter writer;
1972
2
        struct DocumentBuffer {
1973
2
            DorisUniqueBufferPtr<char> ptr;
1974
2
            size_t size = 0;
1975
2
            size_t capacity = 0;
1976
2
        };
1977
1978
2
        DocumentBuffer tmp_buffer;
1979
1980
8
        for (size_t row_idx = 0; row_idx != input_rows_count; ++row_idx) {
1981
12
            for (size_t i = 1; i < arguments.size(); i += 2) {
1982
6
                const size_t index = i / 2;
1983
6
                auto& json_path = json_paths[index];
1984
6
                auto& json_value = json_values[index];
1985
1986
6
                const auto path_index = index_check_const(row_idx, json_path_constant[index]);
1987
6
                const auto value_index = index_check_const(row_idx, json_value_constant[index]);
1988
1989
6
                if (null_map[row_idx]) {
1990
0
                    continue;
1991
0
                }
1992
1993
6
                if (json_documents[row_idx] == nullptr) {
1994
0
                    null_map[row_idx] = 1;
1995
0
                    continue;
1996
0
                }
1997
1998
6
                if (json_path_null_maps[index] && (*json_path_null_maps[index])[path_index]) {
1999
0
                    null_map[row_idx] = 1;
2000
0
                    continue;
2001
0
                }
2002
2003
6
                auto find_result =
2004
6
                        json_documents[row_idx]->getValue()->findValue(json_path[path_index]);
2005
2006
6
                if (find_result.is_wildcard) {
2007
0
                    return Status::InvalidArgument(
2008
0
                            " In this situation, path expressions may not contain the * and ** "
2009
0
                            "tokens or an array range, argument index: {}, row index: {}",
2010
0
                            i, row_idx);
2011
0
                }
2012
2013
6
                if constexpr (modify_type == JsonbModifyType::Insert) {
2014
3
                    if (find_result.value) {
2015
0
                        continue;
2016
0
                    }
2017
3
                } else if constexpr (modify_type == JsonbModifyType::Replace) {
2018
0
                    if (!find_result.value) {
2019
0
                        continue;
2020
0
                    }
2021
0
                }
2022
2023
3
                std::vector<const JsonbValue*> parents;
2024
2025
6
                bool replace = false;
2026
6
                parents.emplace_back(json_documents[row_idx]->getValue());
2027
6
                const auto legs_count = json_path[path_index].get_leg_vector_size();
2028
6
                if (find_result.value) {
2029
                    // find target path, replace it with the new value.
2030
0
                    replace = true;
2031
0
                    if (!build_parents_by_path(json_documents[row_idx]->getValue(),
2032
0
                                               json_path[path_index], parents)) {
2033
0
                        continue;
2034
0
                    }
2035
6
                } else {
2036
                    // does not find target path, insert the new value.
2037
6
                    JsonbPath new_path;
2038
6
                    DCHECK_GT(legs_count, 0);
2039
10
                    for (size_t j = 0; j + 1 < legs_count; ++j) {
2040
4
                        auto* current_leg = json_path[path_index].get_leg_from_leg_vector(j);
2041
4
                        std::unique_ptr<leg_info> leg = std::make_unique<leg_info>(
2042
4
                                current_leg->leg_ptr, current_leg->leg_len,
2043
4
                                current_leg->array_index, current_leg->type);
2044
4
                        new_path.add_leg_to_leg_vector(std::move(leg));
2045
4
                    }
2046
2047
6
                    if (!build_parents_by_path(json_documents[row_idx]->getValue(), new_path,
2048
6
                                               parents)) {
2049
0
                        continue;
2050
0
                    }
2051
6
                }
2052
2053
6
                leg_info* last_leg =
2054
6
                        legs_count > 0
2055
6
                                ? json_path[path_index].get_leg_from_leg_vector(legs_count - 1)
2056
6
                                : nullptr;
2057
6
                RETURN_IF_ERROR(write_json_value(json_documents[row_idx]->getValue(), parents, 0,
2058
6
                                                 json_value[value_index], replace, last_leg,
2059
6
                                                 writer));
2060
2061
6
                auto* writer_output = writer.getOutput();
2062
6
                if (writer_output->getSize() > tmp_buffer.capacity) {
2063
2
                    tmp_buffer.capacity =
2064
2
                            ((size_t(writer_output->getSize()) + 1024 - 1) / 1024) * 1024;
2065
2
                    tmp_buffer.ptr = make_unique_buffer<char>(tmp_buffer.capacity);
2066
2
                    DCHECK_LE(writer_output->getSize(), tmp_buffer.capacity);
2067
2
                }
2068
2069
6
                memcpy(tmp_buffer.ptr.get(), writer_output->getBuffer(), writer_output->getSize());
2070
6
                tmp_buffer.size = writer_output->getSize();
2071
2072
6
                writer.reset();
2073
2074
6
                RETURN_IF_ERROR(JsonbDocument::checkAndCreateDocument(
2075
6
                        tmp_buffer.ptr.get(), tmp_buffer.size, &json_documents[row_idx]));
2076
6
            }
2077
2078
6
            if (!null_map[row_idx]) {
2079
6
                const auto* jsonb_document = json_documents[row_idx];
2080
6
                const auto size = jsonb_document->numPackedBytes();
2081
6
                res_chars.insert(reinterpret_cast<const char*>(jsonb_document),
2082
6
                                 reinterpret_cast<const char*>(jsonb_document) + size);
2083
6
            }
2084
2085
6
            res_offsets[row_idx] = static_cast<uint32_t>(res_chars.size());
2086
2087
6
            if (!null_map[row_idx]) {
2088
6
                auto* ptr = res_chars.data() + res_offsets[row_idx - 1];
2089
6
                auto size = res_offsets[row_idx] - res_offsets[row_idx - 1];
2090
6
                const JsonbDocument* doc = nullptr;
2091
6
                THROW_IF_ERROR(JsonbDocument::checkAndCreateDocument(
2092
6
                        reinterpret_cast<const char*>(ptr), size, &doc));
2093
6
            }
2094
6
        }
2095
2096
2
        block.get_by_position(result).column = std::move(result_column);
2097
2
        return Status::OK();
2098
2
    }
_ZNK5doris19FunctionJsonbModifyILNS_15JsonbModifyTypeE0EE12execute_implEPNS_15FunctionContextERNS_5BlockERKSt6vectorIjSaIjEEjm
Line
Count
Source
1847
1
                        uint32_t result, size_t input_rows_count) const override {
1848
1
        if (arguments.size() % 2 != 1 || arguments.size() < 3) {
1849
0
            return Status::InvalidArgument(
1850
0
                    "Function {} must have an odd number of arguments and more than 2 arguments, "
1851
0
                    "but got: {}",
1852
0
                    name, arguments.size());
1853
0
        }
1854
1855
1
        const size_t keys_count = (arguments.size() - 1) / 2;
1856
1857
1
        auto return_data_type = make_nullable(std::make_shared<DataTypeJsonb>());
1858
1859
1
        auto result_column = return_data_type->create_column();
1860
1
        auto& result_nullable_col = assert_cast<ColumnNullable&>(*result_column);
1861
1
        auto& null_map = result_nullable_col.get_null_map_data();
1862
1
        auto& res_string_column =
1863
1
                assert_cast<ColumnString&>(result_nullable_col.get_nested_column());
1864
1
        auto& res_chars = res_string_column.get_chars();
1865
1
        auto& res_offsets = res_string_column.get_offsets();
1866
1867
1
        null_map.resize_fill(input_rows_count, 0);
1868
1
        res_offsets.resize(input_rows_count);
1869
1
        auto&& [json_data_arg_column, json_data_const] =
1870
1
                unpack_if_const(block.get_by_position(arguments[0]).column);
1871
1872
1
        if (json_data_const) {
1873
0
            if (json_data_arg_column->is_null_at(0)) {
1874
0
                return create_all_null_result(return_data_type, block, result, input_rows_count);
1875
0
            }
1876
0
        }
1877
1878
1
        std::vector<const ColumnString*> json_path_columns(keys_count);
1879
1
        std::vector<bool> json_path_constant(keys_count);
1880
1
        std::vector<const NullMap*> json_path_null_maps(keys_count, nullptr);
1881
1882
1
        std::vector<const ColumnString*> json_value_columns(keys_count);
1883
1
        std::vector<bool> json_value_constant(keys_count);
1884
1
        std::vector<const NullMap*> json_value_null_maps(keys_count, nullptr);
1885
1886
1
        const NullMap* json_data_null_map = nullptr;
1887
1
        const ColumnString* json_data_column;
1888
1
        if (const auto* nullable_column =
1889
1
                    check_and_get_column<ColumnNullable>(json_data_arg_column.get())) {
1890
1
            json_data_null_map = &nullable_column->get_null_map_data();
1891
1
            const auto& nested_column = nullable_column->get_nested_column();
1892
1
            json_data_column = assert_cast<const ColumnString*>(&nested_column);
1893
1
        } else {
1894
0
            json_data_column = assert_cast<const ColumnString*>(json_data_arg_column.get());
1895
0
        }
1896
1897
2
        for (size_t i = 1; i < arguments.size(); i += 2) {
1898
1
            auto&& [path_column, path_const] =
1899
1
                    unpack_if_const(block.get_by_position(arguments[i]).column);
1900
1
            auto&& [value_column, value_const] =
1901
1
                    unpack_if_const(block.get_by_position(arguments[i + 1]).column);
1902
1903
1
            if (path_const) {
1904
0
                if (path_column->is_null_at(0)) {
1905
0
                    return create_all_null_result(return_data_type, block, result,
1906
0
                                                  input_rows_count);
1907
0
                }
1908
0
            }
1909
1910
1
            json_path_constant[i / 2] = path_const;
1911
1
            if (const auto* nullable_column =
1912
1
                        check_and_get_column<ColumnNullable>(path_column.get())) {
1913
1
                json_path_null_maps[i / 2] = &nullable_column->get_null_map_data();
1914
1
                const auto& nested_column = nullable_column->get_nested_column();
1915
1
                json_path_columns[i / 2] = assert_cast<const ColumnString*>(&nested_column);
1916
1
            } else {
1917
0
                json_path_columns[i / 2] = assert_cast<const ColumnString*>(path_column.get());
1918
0
            }
1919
1920
1
            json_value_constant[i / 2] = value_const;
1921
1
            if (const auto* nullable_column =
1922
1
                        check_and_get_column<ColumnNullable>(value_column.get())) {
1923
1
                json_value_null_maps[i / 2] = &nullable_column->get_null_map_data();
1924
1
                const auto& nested_column = nullable_column->get_nested_column();
1925
1
                json_value_columns[i / 2] = assert_cast<const ColumnString*>(&nested_column);
1926
1
            } else {
1927
0
                json_value_columns[i / 2] = assert_cast<const ColumnString*>(value_column.get());
1928
0
            }
1929
1
        }
1930
1931
1
        DorisVector<const JsonbDocument*> json_documents(input_rows_count);
1932
1
        if (json_data_const) {
1933
0
            auto json_data_string = json_data_column->get_data_at(0);
1934
0
            const JsonbDocument* doc = nullptr;
1935
0
            RETURN_IF_ERROR(JsonbDocument::checkAndCreateDocument(json_data_string.data,
1936
0
                                                                  json_data_string.size, &doc));
1937
0
            if (!doc || !doc->getValue()) [[unlikely]] {
1938
0
                return create_all_null_result(return_data_type, block, result, input_rows_count);
1939
0
            }
1940
0
            for (size_t i = 0; i != input_rows_count; ++i) {
1941
0
                json_documents[i] = doc;
1942
0
            }
1943
1
        } else {
1944
4
            for (size_t i = 0; i != input_rows_count; ++i) {
1945
3
                if (json_data_null_map && (*json_data_null_map)[i]) {
1946
0
                    null_map[i] = 1;
1947
0
                    json_documents[i] = nullptr;
1948
0
                    continue;
1949
0
                }
1950
1951
3
                auto json_data_string = json_data_column->get_data_at(i);
1952
3
                const JsonbDocument* doc = nullptr;
1953
3
                RETURN_IF_ERROR(JsonbDocument::checkAndCreateDocument(json_data_string.data,
1954
3
                                                                      json_data_string.size, &doc));
1955
3
                if (!doc || !doc->getValue()) [[unlikely]] {
1956
0
                    null_map[i] = 1;
1957
0
                    continue;
1958
0
                }
1959
3
                json_documents[i] = doc;
1960
3
            }
1961
1
        }
1962
1963
1
        DorisVector<DorisVector<JsonbPath>> json_paths(keys_count);
1964
1
        DorisVector<DorisVector<const JsonbValue*>> json_values(keys_count);
1965
1966
1
        RETURN_IF_ERROR(parse_paths_and_values(json_paths, json_values, arguments, input_rows_count,
1967
1
                                               json_path_columns, json_path_constant,
1968
1
                                               json_path_null_maps, json_value_columns,
1969
1
                                               json_value_constant, json_value_null_maps));
1970
1971
1
        JsonbWriter writer;
1972
1
        struct DocumentBuffer {
1973
1
            DorisUniqueBufferPtr<char> ptr;
1974
1
            size_t size = 0;
1975
1
            size_t capacity = 0;
1976
1
        };
1977
1978
1
        DocumentBuffer tmp_buffer;
1979
1980
4
        for (size_t row_idx = 0; row_idx != input_rows_count; ++row_idx) {
1981
6
            for (size_t i = 1; i < arguments.size(); i += 2) {
1982
3
                const size_t index = i / 2;
1983
3
                auto& json_path = json_paths[index];
1984
3
                auto& json_value = json_values[index];
1985
1986
3
                const auto path_index = index_check_const(row_idx, json_path_constant[index]);
1987
3
                const auto value_index = index_check_const(row_idx, json_value_constant[index]);
1988
1989
3
                if (null_map[row_idx]) {
1990
0
                    continue;
1991
0
                }
1992
1993
3
                if (json_documents[row_idx] == nullptr) {
1994
0
                    null_map[row_idx] = 1;
1995
0
                    continue;
1996
0
                }
1997
1998
3
                if (json_path_null_maps[index] && (*json_path_null_maps[index])[path_index]) {
1999
0
                    null_map[row_idx] = 1;
2000
0
                    continue;
2001
0
                }
2002
2003
3
                auto find_result =
2004
3
                        json_documents[row_idx]->getValue()->findValue(json_path[path_index]);
2005
2006
3
                if (find_result.is_wildcard) {
2007
0
                    return Status::InvalidArgument(
2008
0
                            " In this situation, path expressions may not contain the * and ** "
2009
0
                            "tokens or an array range, argument index: {}, row index: {}",
2010
0
                            i, row_idx);
2011
0
                }
2012
2013
3
                if constexpr (modify_type == JsonbModifyType::Insert) {
2014
3
                    if (find_result.value) {
2015
0
                        continue;
2016
0
                    }
2017
                } else if constexpr (modify_type == JsonbModifyType::Replace) {
2018
                    if (!find_result.value) {
2019
                        continue;
2020
                    }
2021
                }
2022
2023
3
                std::vector<const JsonbValue*> parents;
2024
2025
3
                bool replace = false;
2026
3
                parents.emplace_back(json_documents[row_idx]->getValue());
2027
3
                const auto legs_count = json_path[path_index].get_leg_vector_size();
2028
3
                if (find_result.value) {
2029
                    // find target path, replace it with the new value.
2030
0
                    replace = true;
2031
0
                    if (!build_parents_by_path(json_documents[row_idx]->getValue(),
2032
0
                                               json_path[path_index], parents)) {
2033
0
                        continue;
2034
0
                    }
2035
3
                } else {
2036
                    // does not find target path, insert the new value.
2037
3
                    JsonbPath new_path;
2038
3
                    DCHECK_GT(legs_count, 0);
2039
5
                    for (size_t j = 0; j + 1 < legs_count; ++j) {
2040
2
                        auto* current_leg = json_path[path_index].get_leg_from_leg_vector(j);
2041
2
                        std::unique_ptr<leg_info> leg = std::make_unique<leg_info>(
2042
2
                                current_leg->leg_ptr, current_leg->leg_len,
2043
2
                                current_leg->array_index, current_leg->type);
2044
2
                        new_path.add_leg_to_leg_vector(std::move(leg));
2045
2
                    }
2046
2047
3
                    if (!build_parents_by_path(json_documents[row_idx]->getValue(), new_path,
2048
3
                                               parents)) {
2049
0
                        continue;
2050
0
                    }
2051
3
                }
2052
2053
3
                leg_info* last_leg =
2054
3
                        legs_count > 0
2055
3
                                ? json_path[path_index].get_leg_from_leg_vector(legs_count - 1)
2056
3
                                : nullptr;
2057
3
                RETURN_IF_ERROR(write_json_value(json_documents[row_idx]->getValue(), parents, 0,
2058
3
                                                 json_value[value_index], replace, last_leg,
2059
3
                                                 writer));
2060
2061
3
                auto* writer_output = writer.getOutput();
2062
3
                if (writer_output->getSize() > tmp_buffer.capacity) {
2063
1
                    tmp_buffer.capacity =
2064
1
                            ((size_t(writer_output->getSize()) + 1024 - 1) / 1024) * 1024;
2065
1
                    tmp_buffer.ptr = make_unique_buffer<char>(tmp_buffer.capacity);
2066
1
                    DCHECK_LE(writer_output->getSize(), tmp_buffer.capacity);
2067
1
                }
2068
2069
3
                memcpy(tmp_buffer.ptr.get(), writer_output->getBuffer(), writer_output->getSize());
2070
3
                tmp_buffer.size = writer_output->getSize();
2071
2072
3
                writer.reset();
2073
2074
3
                RETURN_IF_ERROR(JsonbDocument::checkAndCreateDocument(
2075
3
                        tmp_buffer.ptr.get(), tmp_buffer.size, &json_documents[row_idx]));
2076
3
            }
2077
2078
3
            if (!null_map[row_idx]) {
2079
3
                const auto* jsonb_document = json_documents[row_idx];
2080
3
                const auto size = jsonb_document->numPackedBytes();
2081
3
                res_chars.insert(reinterpret_cast<const char*>(jsonb_document),
2082
3
                                 reinterpret_cast<const char*>(jsonb_document) + size);
2083
3
            }
2084
2085
3
            res_offsets[row_idx] = static_cast<uint32_t>(res_chars.size());
2086
2087
3
            if (!null_map[row_idx]) {
2088
3
                auto* ptr = res_chars.data() + res_offsets[row_idx - 1];
2089
3
                auto size = res_offsets[row_idx] - res_offsets[row_idx - 1];
2090
3
                const JsonbDocument* doc = nullptr;
2091
3
                THROW_IF_ERROR(JsonbDocument::checkAndCreateDocument(
2092
3
                        reinterpret_cast<const char*>(ptr), size, &doc));
2093
3
            }
2094
3
        }
2095
2096
1
        block.get_by_position(result).column = std::move(result_column);
2097
1
        return Status::OK();
2098
1
    }
_ZNK5doris19FunctionJsonbModifyILNS_15JsonbModifyTypeE1EE12execute_implEPNS_15FunctionContextERNS_5BlockERKSt6vectorIjSaIjEEjm
Line
Count
Source
1847
1
                        uint32_t result, size_t input_rows_count) const override {
1848
1
        if (arguments.size() % 2 != 1 || arguments.size() < 3) {
1849
0
            return Status::InvalidArgument(
1850
0
                    "Function {} must have an odd number of arguments and more than 2 arguments, "
1851
0
                    "but got: {}",
1852
0
                    name, arguments.size());
1853
0
        }
1854
1855
1
        const size_t keys_count = (arguments.size() - 1) / 2;
1856
1857
1
        auto return_data_type = make_nullable(std::make_shared<DataTypeJsonb>());
1858
1859
1
        auto result_column = return_data_type->create_column();
1860
1
        auto& result_nullable_col = assert_cast<ColumnNullable&>(*result_column);
1861
1
        auto& null_map = result_nullable_col.get_null_map_data();
1862
1
        auto& res_string_column =
1863
1
                assert_cast<ColumnString&>(result_nullable_col.get_nested_column());
1864
1
        auto& res_chars = res_string_column.get_chars();
1865
1
        auto& res_offsets = res_string_column.get_offsets();
1866
1867
1
        null_map.resize_fill(input_rows_count, 0);
1868
1
        res_offsets.resize(input_rows_count);
1869
1
        auto&& [json_data_arg_column, json_data_const] =
1870
1
                unpack_if_const(block.get_by_position(arguments[0]).column);
1871
1872
1
        if (json_data_const) {
1873
0
            if (json_data_arg_column->is_null_at(0)) {
1874
0
                return create_all_null_result(return_data_type, block, result, input_rows_count);
1875
0
            }
1876
0
        }
1877
1878
1
        std::vector<const ColumnString*> json_path_columns(keys_count);
1879
1
        std::vector<bool> json_path_constant(keys_count);
1880
1
        std::vector<const NullMap*> json_path_null_maps(keys_count, nullptr);
1881
1882
1
        std::vector<const ColumnString*> json_value_columns(keys_count);
1883
1
        std::vector<bool> json_value_constant(keys_count);
1884
1
        std::vector<const NullMap*> json_value_null_maps(keys_count, nullptr);
1885
1886
1
        const NullMap* json_data_null_map = nullptr;
1887
1
        const ColumnString* json_data_column;
1888
1
        if (const auto* nullable_column =
1889
1
                    check_and_get_column<ColumnNullable>(json_data_arg_column.get())) {
1890
1
            json_data_null_map = &nullable_column->get_null_map_data();
1891
1
            const auto& nested_column = nullable_column->get_nested_column();
1892
1
            json_data_column = assert_cast<const ColumnString*>(&nested_column);
1893
1
        } else {
1894
0
            json_data_column = assert_cast<const ColumnString*>(json_data_arg_column.get());
1895
0
        }
1896
1897
2
        for (size_t i = 1; i < arguments.size(); i += 2) {
1898
1
            auto&& [path_column, path_const] =
1899
1
                    unpack_if_const(block.get_by_position(arguments[i]).column);
1900
1
            auto&& [value_column, value_const] =
1901
1
                    unpack_if_const(block.get_by_position(arguments[i + 1]).column);
1902
1903
1
            if (path_const) {
1904
0
                if (path_column->is_null_at(0)) {
1905
0
                    return create_all_null_result(return_data_type, block, result,
1906
0
                                                  input_rows_count);
1907
0
                }
1908
0
            }
1909
1910
1
            json_path_constant[i / 2] = path_const;
1911
1
            if (const auto* nullable_column =
1912
1
                        check_and_get_column<ColumnNullable>(path_column.get())) {
1913
1
                json_path_null_maps[i / 2] = &nullable_column->get_null_map_data();
1914
1
                const auto& nested_column = nullable_column->get_nested_column();
1915
1
                json_path_columns[i / 2] = assert_cast<const ColumnString*>(&nested_column);
1916
1
            } else {
1917
0
                json_path_columns[i / 2] = assert_cast<const ColumnString*>(path_column.get());
1918
0
            }
1919
1920
1
            json_value_constant[i / 2] = value_const;
1921
1
            if (const auto* nullable_column =
1922
1
                        check_and_get_column<ColumnNullable>(value_column.get())) {
1923
1
                json_value_null_maps[i / 2] = &nullable_column->get_null_map_data();
1924
1
                const auto& nested_column = nullable_column->get_nested_column();
1925
1
                json_value_columns[i / 2] = assert_cast<const ColumnString*>(&nested_column);
1926
1
            } else {
1927
0
                json_value_columns[i / 2] = assert_cast<const ColumnString*>(value_column.get());
1928
0
            }
1929
1
        }
1930
1931
1
        DorisVector<const JsonbDocument*> json_documents(input_rows_count);
1932
1
        if (json_data_const) {
1933
0
            auto json_data_string = json_data_column->get_data_at(0);
1934
0
            const JsonbDocument* doc = nullptr;
1935
0
            RETURN_IF_ERROR(JsonbDocument::checkAndCreateDocument(json_data_string.data,
1936
0
                                                                  json_data_string.size, &doc));
1937
0
            if (!doc || !doc->getValue()) [[unlikely]] {
1938
0
                return create_all_null_result(return_data_type, block, result, input_rows_count);
1939
0
            }
1940
0
            for (size_t i = 0; i != input_rows_count; ++i) {
1941
0
                json_documents[i] = doc;
1942
0
            }
1943
1
        } else {
1944
4
            for (size_t i = 0; i != input_rows_count; ++i) {
1945
3
                if (json_data_null_map && (*json_data_null_map)[i]) {
1946
0
                    null_map[i] = 1;
1947
0
                    json_documents[i] = nullptr;
1948
0
                    continue;
1949
0
                }
1950
1951
3
                auto json_data_string = json_data_column->get_data_at(i);
1952
3
                const JsonbDocument* doc = nullptr;
1953
3
                RETURN_IF_ERROR(JsonbDocument::checkAndCreateDocument(json_data_string.data,
1954
3
                                                                      json_data_string.size, &doc));
1955
3
                if (!doc || !doc->getValue()) [[unlikely]] {
1956
0
                    null_map[i] = 1;
1957
0
                    continue;
1958
0
                }
1959
3
                json_documents[i] = doc;
1960
3
            }
1961
1
        }
1962
1963
1
        DorisVector<DorisVector<JsonbPath>> json_paths(keys_count);
1964
1
        DorisVector<DorisVector<const JsonbValue*>> json_values(keys_count);
1965
1966
1
        RETURN_IF_ERROR(parse_paths_and_values(json_paths, json_values, arguments, input_rows_count,
1967
1
                                               json_path_columns, json_path_constant,
1968
1
                                               json_path_null_maps, json_value_columns,
1969
1
                                               json_value_constant, json_value_null_maps));
1970
1971
1
        JsonbWriter writer;
1972
1
        struct DocumentBuffer {
1973
1
            DorisUniqueBufferPtr<char> ptr;
1974
1
            size_t size = 0;
1975
1
            size_t capacity = 0;
1976
1
        };
1977
1978
1
        DocumentBuffer tmp_buffer;
1979
1980
4
        for (size_t row_idx = 0; row_idx != input_rows_count; ++row_idx) {
1981
6
            for (size_t i = 1; i < arguments.size(); i += 2) {
1982
3
                const size_t index = i / 2;
1983
3
                auto& json_path = json_paths[index];
1984
3
                auto& json_value = json_values[index];
1985
1986
3
                const auto path_index = index_check_const(row_idx, json_path_constant[index]);
1987
3
                const auto value_index = index_check_const(row_idx, json_value_constant[index]);
1988
1989
3
                if (null_map[row_idx]) {
1990
0
                    continue;
1991
0
                }
1992
1993
3
                if (json_documents[row_idx] == nullptr) {
1994
0
                    null_map[row_idx] = 1;
1995
0
                    continue;
1996
0
                }
1997
1998
3
                if (json_path_null_maps[index] && (*json_path_null_maps[index])[path_index]) {
1999
0
                    null_map[row_idx] = 1;
2000
0
                    continue;
2001
0
                }
2002
2003
3
                auto find_result =
2004
3
                        json_documents[row_idx]->getValue()->findValue(json_path[path_index]);
2005
2006
3
                if (find_result.is_wildcard) {
2007
0
                    return Status::InvalidArgument(
2008
0
                            " In this situation, path expressions may not contain the * and ** "
2009
0
                            "tokens or an array range, argument index: {}, row index: {}",
2010
0
                            i, row_idx);
2011
0
                }
2012
2013
                if constexpr (modify_type == JsonbModifyType::Insert) {
2014
                    if (find_result.value) {
2015
                        continue;
2016
                    }
2017
3
                } else if constexpr (modify_type == JsonbModifyType::Replace) {
2018
3
                    if (!find_result.value) {
2019
3
                        continue;
2020
3
                    }
2021
3
                }
2022
2023
3
                std::vector<const JsonbValue*> parents;
2024
2025
3
                bool replace = false;
2026
3
                parents.emplace_back(json_documents[row_idx]->getValue());
2027
3
                const auto legs_count = json_path[path_index].get_leg_vector_size();
2028
3
                if (find_result.value) {
2029
                    // find target path, replace it with the new value.
2030
0
                    replace = true;
2031
0
                    if (!build_parents_by_path(json_documents[row_idx]->getValue(),
2032
0
                                               json_path[path_index], parents)) {
2033
0
                        continue;
2034
0
                    }
2035
3
                } else {
2036
                    // does not find target path, insert the new value.
2037
3
                    JsonbPath new_path;
2038
3
                    DCHECK_GT(legs_count, 0);
2039
5
                    for (size_t j = 0; j + 1 < legs_count; ++j) {
2040
2
                        auto* current_leg = json_path[path_index].get_leg_from_leg_vector(j);
2041
2
                        std::unique_ptr<leg_info> leg = std::make_unique<leg_info>(
2042
2
                                current_leg->leg_ptr, current_leg->leg_len,
2043
2
                                current_leg->array_index, current_leg->type);
2044
2
                        new_path.add_leg_to_leg_vector(std::move(leg));
2045
2
                    }
2046
2047
3
                    if (!build_parents_by_path(json_documents[row_idx]->getValue(), new_path,
2048
3
                                               parents)) {
2049
0
                        continue;
2050
0
                    }
2051
3
                }
2052
2053
3
                leg_info* last_leg =
2054
3
                        legs_count > 0
2055
3
                                ? json_path[path_index].get_leg_from_leg_vector(legs_count - 1)
2056
3
                                : nullptr;
2057
3
                RETURN_IF_ERROR(write_json_value(json_documents[row_idx]->getValue(), parents, 0,
2058
3
                                                 json_value[value_index], replace, last_leg,
2059
3
                                                 writer));
2060
2061
3
                auto* writer_output = writer.getOutput();
2062
3
                if (writer_output->getSize() > tmp_buffer.capacity) {
2063
1
                    tmp_buffer.capacity =
2064
1
                            ((size_t(writer_output->getSize()) + 1024 - 1) / 1024) * 1024;
2065
1
                    tmp_buffer.ptr = make_unique_buffer<char>(tmp_buffer.capacity);
2066
1
                    DCHECK_LE(writer_output->getSize(), tmp_buffer.capacity);
2067
1
                }
2068
2069
3
                memcpy(tmp_buffer.ptr.get(), writer_output->getBuffer(), writer_output->getSize());
2070
3
                tmp_buffer.size = writer_output->getSize();
2071
2072
3
                writer.reset();
2073
2074
3
                RETURN_IF_ERROR(JsonbDocument::checkAndCreateDocument(
2075
3
                        tmp_buffer.ptr.get(), tmp_buffer.size, &json_documents[row_idx]));
2076
3
            }
2077
2078
3
            if (!null_map[row_idx]) {
2079
3
                const auto* jsonb_document = json_documents[row_idx];
2080
3
                const auto size = jsonb_document->numPackedBytes();
2081
3
                res_chars.insert(reinterpret_cast<const char*>(jsonb_document),
2082
3
                                 reinterpret_cast<const char*>(jsonb_document) + size);
2083
3
            }
2084
2085
3
            res_offsets[row_idx] = static_cast<uint32_t>(res_chars.size());
2086
2087
3
            if (!null_map[row_idx]) {
2088
3
                auto* ptr = res_chars.data() + res_offsets[row_idx - 1];
2089
3
                auto size = res_offsets[row_idx] - res_offsets[row_idx - 1];
2090
3
                const JsonbDocument* doc = nullptr;
2091
3
                THROW_IF_ERROR(JsonbDocument::checkAndCreateDocument(
2092
3
                        reinterpret_cast<const char*>(ptr), size, &doc));
2093
3
            }
2094
3
        }
2095
2096
1
        block.get_by_position(result).column = std::move(result_column);
2097
1
        return Status::OK();
2098
1
    }
Unexecuted instantiation: _ZNK5doris19FunctionJsonbModifyILNS_15JsonbModifyTypeE2EE12execute_implEPNS_15FunctionContextERNS_5BlockERKSt6vectorIjSaIjEEjm
2099
2100
    bool build_parents_by_path(const JsonbValue* root, const JsonbPath& path,
2101
10
                               std::vector<const JsonbValue*>& parents) const {
2102
10
        const size_t index = parents.size() - 1;
2103
10
        if (index == path.get_leg_vector_size()) {
2104
6
            return true;
2105
6
        }
2106
2107
4
        JsonbPath current;
2108
4
        auto* current_leg = path.get_leg_from_leg_vector(index);
2109
4
        std::unique_ptr<leg_info> leg =
2110
4
                std::make_unique<leg_info>(current_leg->leg_ptr, current_leg->leg_len,
2111
4
                                           current_leg->array_index, current_leg->type);
2112
4
        current.add_leg_to_leg_vector(std::move(leg));
2113
2114
4
        auto find_result = root->findValue(current);
2115
4
        if (!find_result.value) {
2116
0
            return false;
2117
4
        } else if (find_result.value == root) {
2118
0
            return true;
2119
4
        } else {
2120
4
            parents.emplace_back(find_result.value);
2121
4
        }
2122
2123
4
        return build_parents_by_path(find_result.value, path, parents);
2124
4
    }
_ZNK5doris19FunctionJsonbModifyILNS_15JsonbModifyTypeE0EE21build_parents_by_pathEPKNS_10JsonbValueERKNS_9JsonbPathERSt6vectorIS5_SaIS5_EE
Line
Count
Source
2101
5
                               std::vector<const JsonbValue*>& parents) const {
2102
5
        const size_t index = parents.size() - 1;
2103
5
        if (index == path.get_leg_vector_size()) {
2104
3
            return true;
2105
3
        }
2106
2107
2
        JsonbPath current;
2108
2
        auto* current_leg = path.get_leg_from_leg_vector(index);
2109
2
        std::unique_ptr<leg_info> leg =
2110
2
                std::make_unique<leg_info>(current_leg->leg_ptr, current_leg->leg_len,
2111
2
                                           current_leg->array_index, current_leg->type);
2112
2
        current.add_leg_to_leg_vector(std::move(leg));
2113
2114
2
        auto find_result = root->findValue(current);
2115
2
        if (!find_result.value) {
2116
0
            return false;
2117
2
        } else if (find_result.value == root) {
2118
0
            return true;
2119
2
        } else {
2120
2
            parents.emplace_back(find_result.value);
2121
2
        }
2122
2123
2
        return build_parents_by_path(find_result.value, path, parents);
2124
2
    }
_ZNK5doris19FunctionJsonbModifyILNS_15JsonbModifyTypeE1EE21build_parents_by_pathEPKNS_10JsonbValueERKNS_9JsonbPathERSt6vectorIS5_SaIS5_EE
Line
Count
Source
2101
5
                               std::vector<const JsonbValue*>& parents) const {
2102
5
        const size_t index = parents.size() - 1;
2103
5
        if (index == path.get_leg_vector_size()) {
2104
3
            return true;
2105
3
        }
2106
2107
2
        JsonbPath current;
2108
2
        auto* current_leg = path.get_leg_from_leg_vector(index);
2109
2
        std::unique_ptr<leg_info> leg =
2110
2
                std::make_unique<leg_info>(current_leg->leg_ptr, current_leg->leg_len,
2111
2
                                           current_leg->array_index, current_leg->type);
2112
2
        current.add_leg_to_leg_vector(std::move(leg));
2113
2114
2
        auto find_result = root->findValue(current);
2115
2
        if (!find_result.value) {
2116
0
            return false;
2117
2
        } else if (find_result.value == root) {
2118
0
            return true;
2119
2
        } else {
2120
2
            parents.emplace_back(find_result.value);
2121
2
        }
2122
2123
2
        return build_parents_by_path(find_result.value, path, parents);
2124
2
    }
Unexecuted instantiation: _ZNK5doris19FunctionJsonbModifyILNS_15JsonbModifyTypeE2EE21build_parents_by_pathEPKNS_10JsonbValueERKNS_9JsonbPathERSt6vectorIS5_SaIS5_EE
2125
2126
    Status write_json_value(const JsonbValue* root, const std::vector<const JsonbValue*>& parents,
2127
                            const size_t parent_index, const JsonbValue* value, const bool replace,
2128
10
                            const leg_info* last_leg, JsonbWriter& writer) const {
2129
10
        if (parent_index >= parents.size()) {
2130
0
            return Status::InvalidArgument(
2131
0
                    "JsonbModify: parent_index {} is out of bounds for parents size {}",
2132
0
                    parent_index, parents.size());
2133
0
        }
2134
2135
10
        if (parents[parent_index] != root) {
2136
0
            return Status::InvalidArgument(
2137
0
                    "JsonbModify: parent value does not match root value, parent_index: {}, "
2138
0
                    "parents size: {}",
2139
0
                    parent_index, parents.size());
2140
0
        }
2141
2142
10
        if (parent_index == parents.size() - 1 && replace) {
2143
            // We are at the last parent, write the value directly
2144
0
            if (value == nullptr) {
2145
0
                writer.writeNull();
2146
0
            } else {
2147
0
                writer.writeValue(value);
2148
0
            }
2149
0
            return Status::OK();
2150
0
        }
2151
2152
10
        bool value_written = false;
2153
10
        bool is_last_parent = (parent_index == parents.size() - 1);
2154
10
        const auto* next_parent = is_last_parent ? nullptr : parents[parent_index + 1];
2155
10
        if (root->isArray()) {
2156
2
            writer.writeStartArray();
2157
2
            const auto* array_val = root->unpack<ArrayVal>();
2158
4
            for (int i = 0; i != array_val->numElem(); ++i) {
2159
2
                auto* it = array_val->get(i);
2160
2161
2
                if (is_last_parent && last_leg->array_index == i) {
2162
0
                    value_written = true;
2163
0
                    writer.writeValue(value);
2164
2
                } else if (it == next_parent) {
2165
0
                    value_written = true;
2166
0
                    RETURN_IF_ERROR(write_json_value(it, parents, parent_index + 1, value, replace,
2167
0
                                                     last_leg, writer));
2168
2
                } else {
2169
2
                    writer.writeValue(it);
2170
2
                }
2171
2
            }
2172
2
            if (is_last_parent && !value_written) {
2173
2
                value_written = true;
2174
2
                writer.writeValue(value);
2175
2
            }
2176
2177
2
            writer.writeEndArray();
2178
2179
8
        } else {
2180
            /**
2181
                Because even for a non-array object, `$[0]` can still point to that object:
2182
                ```
2183
                select json_extract('{"key": "value"}', '$[0]');
2184
                +------------------------------------------+
2185
                | json_extract('{"key": "value"}', '$[0]') |
2186
                +------------------------------------------+
2187
                | {"key": "value"}                         |
2188
                +------------------------------------------+
2189
                ```
2190
                So when inserting an element into `$[1]`, even if '$' does not represent an array,
2191
                it should be converted to an array before insertion:
2192
                ```
2193
                select json_insert('123','$[1]', null);
2194
                +---------------------------------+
2195
                | json_insert('123','$[1]', null) |
2196
                +---------------------------------+
2197
                | [123, null]                     |
2198
                +---------------------------------+
2199
                ```
2200
             */
2201
8
            if (is_last_parent && last_leg && last_leg->type == ARRAY_CODE) {
2202
0
                writer.writeStartArray();
2203
0
                writer.writeValue(root);
2204
0
                writer.writeValue(value);
2205
0
                writer.writeEndArray();
2206
0
                return Status::OK();
2207
8
            } else if (root->isObject()) {
2208
8
                writer.writeStartObject();
2209
8
                const auto* object_val = root->unpack<ObjectVal>();
2210
8
                for (const auto& it : *object_val) {
2211
4
                    writer.writeKey(it.getKeyStr(), it.klen());
2212
4
                    if (it.value() == next_parent) {
2213
4
                        value_written = true;
2214
4
                        RETURN_IF_ERROR(write_json_value(it.value(), parents, parent_index + 1,
2215
4
                                                         value, replace, last_leg, writer));
2216
4
                    } else {
2217
0
                        writer.writeValue(it.value());
2218
0
                    }
2219
4
                }
2220
2221
8
                if (is_last_parent && !value_written) {
2222
4
                    value_written = true;
2223
4
                    writer.writeStartObject();
2224
4
                    writer.writeKey(last_leg->leg_ptr, static_cast<uint8_t>(last_leg->leg_len));
2225
4
                    writer.writeValue(value);
2226
4
                    writer.writeEndObject();
2227
4
                }
2228
8
                writer.writeEndObject();
2229
2230
8
            } else {
2231
0
                return Status::InvalidArgument("Cannot insert value into this type");
2232
0
            }
2233
8
        }
2234
2235
10
        if (!value_written) {
2236
0
            return Status::InvalidArgument(
2237
0
                    "JsonbModify: value not written, parent_index: {}, parents size: {}",
2238
0
                    parent_index, parents.size());
2239
0
        }
2240
2241
10
        return Status::OK();
2242
10
    }
_ZNK5doris19FunctionJsonbModifyILNS_15JsonbModifyTypeE0EE16write_json_valueEPKNS_10JsonbValueERKSt6vectorIS5_SaIS5_EEmS5_bPKNS_8leg_infoERNS_12JsonbWriterTINS_14JsonbOutStreamEEE
Line
Count
Source
2128
5
                            const leg_info* last_leg, JsonbWriter& writer) const {
2129
5
        if (parent_index >= parents.size()) {
2130
0
            return Status::InvalidArgument(
2131
0
                    "JsonbModify: parent_index {} is out of bounds for parents size {}",
2132
0
                    parent_index, parents.size());
2133
0
        }
2134
2135
5
        if (parents[parent_index] != root) {
2136
0
            return Status::InvalidArgument(
2137
0
                    "JsonbModify: parent value does not match root value, parent_index: {}, "
2138
0
                    "parents size: {}",
2139
0
                    parent_index, parents.size());
2140
0
        }
2141
2142
5
        if (parent_index == parents.size() - 1 && replace) {
2143
            // We are at the last parent, write the value directly
2144
0
            if (value == nullptr) {
2145
0
                writer.writeNull();
2146
0
            } else {
2147
0
                writer.writeValue(value);
2148
0
            }
2149
0
            return Status::OK();
2150
0
        }
2151
2152
5
        bool value_written = false;
2153
5
        bool is_last_parent = (parent_index == parents.size() - 1);
2154
5
        const auto* next_parent = is_last_parent ? nullptr : parents[parent_index + 1];
2155
5
        if (root->isArray()) {
2156
1
            writer.writeStartArray();
2157
1
            const auto* array_val = root->unpack<ArrayVal>();
2158
2
            for (int i = 0; i != array_val->numElem(); ++i) {
2159
1
                auto* it = array_val->get(i);
2160
2161
1
                if (is_last_parent && last_leg->array_index == i) {
2162
0
                    value_written = true;
2163
0
                    writer.writeValue(value);
2164
1
                } else if (it == next_parent) {
2165
0
                    value_written = true;
2166
0
                    RETURN_IF_ERROR(write_json_value(it, parents, parent_index + 1, value, replace,
2167
0
                                                     last_leg, writer));
2168
1
                } else {
2169
1
                    writer.writeValue(it);
2170
1
                }
2171
1
            }
2172
1
            if (is_last_parent && !value_written) {
2173
1
                value_written = true;
2174
1
                writer.writeValue(value);
2175
1
            }
2176
2177
1
            writer.writeEndArray();
2178
2179
4
        } else {
2180
            /**
2181
                Because even for a non-array object, `$[0]` can still point to that object:
2182
                ```
2183
                select json_extract('{"key": "value"}', '$[0]');
2184
                +------------------------------------------+
2185
                | json_extract('{"key": "value"}', '$[0]') |
2186
                +------------------------------------------+
2187
                | {"key": "value"}                         |
2188
                +------------------------------------------+
2189
                ```
2190
                So when inserting an element into `$[1]`, even if '$' does not represent an array,
2191
                it should be converted to an array before insertion:
2192
                ```
2193
                select json_insert('123','$[1]', null);
2194
                +---------------------------------+
2195
                | json_insert('123','$[1]', null) |
2196
                +---------------------------------+
2197
                | [123, null]                     |
2198
                +---------------------------------+
2199
                ```
2200
             */
2201
4
            if (is_last_parent && last_leg && last_leg->type == ARRAY_CODE) {
2202
0
                writer.writeStartArray();
2203
0
                writer.writeValue(root);
2204
0
                writer.writeValue(value);
2205
0
                writer.writeEndArray();
2206
0
                return Status::OK();
2207
4
            } else if (root->isObject()) {
2208
4
                writer.writeStartObject();
2209
4
                const auto* object_val = root->unpack<ObjectVal>();
2210
4
                for (const auto& it : *object_val) {
2211
2
                    writer.writeKey(it.getKeyStr(), it.klen());
2212
2
                    if (it.value() == next_parent) {
2213
2
                        value_written = true;
2214
2
                        RETURN_IF_ERROR(write_json_value(it.value(), parents, parent_index + 1,
2215
2
                                                         value, replace, last_leg, writer));
2216
2
                    } else {
2217
0
                        writer.writeValue(it.value());
2218
0
                    }
2219
2
                }
2220
2221
4
                if (is_last_parent && !value_written) {
2222
2
                    value_written = true;
2223
2
                    writer.writeStartObject();
2224
2
                    writer.writeKey(last_leg->leg_ptr, static_cast<uint8_t>(last_leg->leg_len));
2225
2
                    writer.writeValue(value);
2226
2
                    writer.writeEndObject();
2227
2
                }
2228
4
                writer.writeEndObject();
2229
2230
4
            } else {
2231
0
                return Status::InvalidArgument("Cannot insert value into this type");
2232
0
            }
2233
4
        }
2234
2235
5
        if (!value_written) {
2236
0
            return Status::InvalidArgument(
2237
0
                    "JsonbModify: value not written, parent_index: {}, parents size: {}",
2238
0
                    parent_index, parents.size());
2239
0
        }
2240
2241
5
        return Status::OK();
2242
5
    }
_ZNK5doris19FunctionJsonbModifyILNS_15JsonbModifyTypeE1EE16write_json_valueEPKNS_10JsonbValueERKSt6vectorIS5_SaIS5_EEmS5_bPKNS_8leg_infoERNS_12JsonbWriterTINS_14JsonbOutStreamEEE
Line
Count
Source
2128
5
                            const leg_info* last_leg, JsonbWriter& writer) const {
2129
5
        if (parent_index >= parents.size()) {
2130
0
            return Status::InvalidArgument(
2131
0
                    "JsonbModify: parent_index {} is out of bounds for parents size {}",
2132
0
                    parent_index, parents.size());
2133
0
        }
2134
2135
5
        if (parents[parent_index] != root) {
2136
0
            return Status::InvalidArgument(
2137
0
                    "JsonbModify: parent value does not match root value, parent_index: {}, "
2138
0
                    "parents size: {}",
2139
0
                    parent_index, parents.size());
2140
0
        }
2141
2142
5
        if (parent_index == parents.size() - 1 && replace) {
2143
            // We are at the last parent, write the value directly
2144
0
            if (value == nullptr) {
2145
0
                writer.writeNull();
2146
0
            } else {
2147
0
                writer.writeValue(value);
2148
0
            }
2149
0
            return Status::OK();
2150
0
        }
2151
2152
5
        bool value_written = false;
2153
5
        bool is_last_parent = (parent_index == parents.size() - 1);
2154
5
        const auto* next_parent = is_last_parent ? nullptr : parents[parent_index + 1];
2155
5
        if (root->isArray()) {
2156
1
            writer.writeStartArray();
2157
1
            const auto* array_val = root->unpack<ArrayVal>();
2158
2
            for (int i = 0; i != array_val->numElem(); ++i) {
2159
1
                auto* it = array_val->get(i);
2160
2161
1
                if (is_last_parent && last_leg->array_index == i) {
2162
0
                    value_written = true;
2163
0
                    writer.writeValue(value);
2164
1
                } else if (it == next_parent) {
2165
0
                    value_written = true;
2166
0
                    RETURN_IF_ERROR(write_json_value(it, parents, parent_index + 1, value, replace,
2167
0
                                                     last_leg, writer));
2168
1
                } else {
2169
1
                    writer.writeValue(it);
2170
1
                }
2171
1
            }
2172
1
            if (is_last_parent && !value_written) {
2173
1
                value_written = true;
2174
1
                writer.writeValue(value);
2175
1
            }
2176
2177
1
            writer.writeEndArray();
2178
2179
4
        } else {
2180
            /**
2181
                Because even for a non-array object, `$[0]` can still point to that object:
2182
                ```
2183
                select json_extract('{"key": "value"}', '$[0]');
2184
                +------------------------------------------+
2185
                | json_extract('{"key": "value"}', '$[0]') |
2186
                +------------------------------------------+
2187
                | {"key": "value"}                         |
2188
                +------------------------------------------+
2189
                ```
2190
                So when inserting an element into `$[1]`, even if '$' does not represent an array,
2191
                it should be converted to an array before insertion:
2192
                ```
2193
                select json_insert('123','$[1]', null);
2194
                +---------------------------------+
2195
                | json_insert('123','$[1]', null) |
2196
                +---------------------------------+
2197
                | [123, null]                     |
2198
                +---------------------------------+
2199
                ```
2200
             */
2201
4
            if (is_last_parent && last_leg && last_leg->type == ARRAY_CODE) {
2202
0
                writer.writeStartArray();
2203
0
                writer.writeValue(root);
2204
0
                writer.writeValue(value);
2205
0
                writer.writeEndArray();
2206
0
                return Status::OK();
2207
4
            } else if (root->isObject()) {
2208
4
                writer.writeStartObject();
2209
4
                const auto* object_val = root->unpack<ObjectVal>();
2210
4
                for (const auto& it : *object_val) {
2211
2
                    writer.writeKey(it.getKeyStr(), it.klen());
2212
2
                    if (it.value() == next_parent) {
2213
2
                        value_written = true;
2214
2
                        RETURN_IF_ERROR(write_json_value(it.value(), parents, parent_index + 1,
2215
2
                                                         value, replace, last_leg, writer));
2216
2
                    } else {
2217
0
                        writer.writeValue(it.value());
2218
0
                    }
2219
2
                }
2220
2221
4
                if (is_last_parent && !value_written) {
2222
2
                    value_written = true;
2223
2
                    writer.writeStartObject();
2224
2
                    writer.writeKey(last_leg->leg_ptr, static_cast<uint8_t>(last_leg->leg_len));
2225
2
                    writer.writeValue(value);
2226
2
                    writer.writeEndObject();
2227
2
                }
2228
4
                writer.writeEndObject();
2229
2230
4
            } else {
2231
0
                return Status::InvalidArgument("Cannot insert value into this type");
2232
0
            }
2233
4
        }
2234
2235
5
        if (!value_written) {
2236
0
            return Status::InvalidArgument(
2237
0
                    "JsonbModify: value not written, parent_index: {}, parents size: {}",
2238
0
                    parent_index, parents.size());
2239
0
        }
2240
2241
5
        return Status::OK();
2242
5
    }
Unexecuted instantiation: _ZNK5doris19FunctionJsonbModifyILNS_15JsonbModifyTypeE2EE16write_json_valueEPKNS_10JsonbValueERKSt6vectorIS5_SaIS5_EEmS5_bPKNS_8leg_infoERNS_12JsonbWriterTINS_14JsonbOutStreamEEE
2243
2244
    Status parse_paths_and_values(DorisVector<DorisVector<JsonbPath>>& json_paths,
2245
                                  DorisVector<DorisVector<const JsonbValue*>>& json_values,
2246
                                  const ColumnNumbers& arguments, const size_t input_rows_count,
2247
                                  const std::vector<const ColumnString*>& json_path_columns,
2248
                                  const std::vector<bool>& json_path_constant,
2249
                                  const std::vector<const NullMap*>& json_path_null_maps,
2250
                                  const std::vector<const ColumnString*>& json_value_columns,
2251
                                  const std::vector<bool>& json_value_constant,
2252
2
                                  const std::vector<const NullMap*>& json_value_null_maps) const {
2253
4
        for (size_t i = 1; i < arguments.size(); i += 2) {
2254
2
            const size_t index = i / 2;
2255
2
            const auto* json_path_column = json_path_columns[index];
2256
2
            const auto* value_column = json_value_columns[index];
2257
2258
2
            json_paths[index].resize(json_path_constant[index] ? 1 : input_rows_count);
2259
2
            json_values[index].resize(json_value_constant[index] ? 1 : input_rows_count, nullptr);
2260
2261
8
            for (size_t row_idx = 0; row_idx != json_paths[index].size(); ++row_idx) {
2262
6
                if (json_path_null_maps[index] && (*json_path_null_maps[index])[row_idx]) {
2263
0
                    continue;
2264
0
                }
2265
2266
6
                auto path_string = json_path_column->get_data_at(row_idx);
2267
6
                if (!json_paths[index][row_idx].seek(path_string.data, path_string.size)) {
2268
0
                    return Status::InvalidArgument(
2269
0
                            "Json path error: Invalid Json Path for value: {}, "
2270
0
                            "argument "
2271
0
                            "index: {}, row index: {}",
2272
0
                            std::string_view(path_string.data, path_string.size), i, row_idx);
2273
0
                }
2274
2275
6
                if (json_paths[index][row_idx].is_wildcard()) {
2276
0
                    return Status::InvalidArgument(
2277
0
                            "In this situation, path expressions may not contain the * and ** "
2278
0
                            "tokens, argument index: {}, row index: {}",
2279
0
                            i, row_idx);
2280
0
                }
2281
6
            }
2282
2283
8
            for (size_t row_idx = 0; row_idx != json_values[index].size(); ++row_idx) {
2284
6
                if (json_value_null_maps[index] && (*json_value_null_maps[index])[row_idx]) {
2285
0
                    continue;
2286
0
                }
2287
2288
6
                auto value_string = value_column->get_data_at(row_idx);
2289
6
                const JsonbDocument* doc = nullptr;
2290
6
                RETURN_IF_ERROR(JsonbDocument::checkAndCreateDocument(value_string.data,
2291
6
                                                                      value_string.size, &doc));
2292
6
                if (doc) {
2293
6
                    json_values[index][row_idx] = doc->getValue();
2294
6
                }
2295
6
            }
2296
2
        }
2297
2298
2
        return Status::OK();
2299
2
    }
_ZNK5doris19FunctionJsonbModifyILNS_15JsonbModifyTypeE0EE22parse_paths_and_valuesERSt6vectorIS3_INS_9JsonbPathENS_18CustomStdAllocatorIS4_NS_9AllocatorILb0ELb0ELb0ENS_22DefaultMemoryAllocatorELb1EEEEEENS5_ISA_S8_EEERS3_IS3_IPKNS_10JsonbValueENS5_ISG_S8_EEENS5_ISI_S8_EEERKS3_IjSaIjEEmRKS3_IPKNS_9ColumnStrIjEESaIST_EERKS3_IbSaIbEERKS3_IPKNS_8PODArrayIhLm4096ES8_Lm16ELm15EEESaIS15_EESX_S11_S19_
Line
Count
Source
2252
1
                                  const std::vector<const NullMap*>& json_value_null_maps) const {
2253
2
        for (size_t i = 1; i < arguments.size(); i += 2) {
2254
1
            const size_t index = i / 2;
2255
1
            const auto* json_path_column = json_path_columns[index];
2256
1
            const auto* value_column = json_value_columns[index];
2257
2258
1
            json_paths[index].resize(json_path_constant[index] ? 1 : input_rows_count);
2259
1
            json_values[index].resize(json_value_constant[index] ? 1 : input_rows_count, nullptr);
2260
2261
4
            for (size_t row_idx = 0; row_idx != json_paths[index].size(); ++row_idx) {
2262
3
                if (json_path_null_maps[index] && (*json_path_null_maps[index])[row_idx]) {
2263
0
                    continue;
2264
0
                }
2265
2266
3
                auto path_string = json_path_column->get_data_at(row_idx);
2267
3
                if (!json_paths[index][row_idx].seek(path_string.data, path_string.size)) {
2268
0
                    return Status::InvalidArgument(
2269
0
                            "Json path error: Invalid Json Path for value: {}, "
2270
0
                            "argument "
2271
0
                            "index: {}, row index: {}",
2272
0
                            std::string_view(path_string.data, path_string.size), i, row_idx);
2273
0
                }
2274
2275
3
                if (json_paths[index][row_idx].is_wildcard()) {
2276
0
                    return Status::InvalidArgument(
2277
0
                            "In this situation, path expressions may not contain the * and ** "
2278
0
                            "tokens, argument index: {}, row index: {}",
2279
0
                            i, row_idx);
2280
0
                }
2281
3
            }
2282
2283
4
            for (size_t row_idx = 0; row_idx != json_values[index].size(); ++row_idx) {
2284
3
                if (json_value_null_maps[index] && (*json_value_null_maps[index])[row_idx]) {
2285
0
                    continue;
2286
0
                }
2287
2288
3
                auto value_string = value_column->get_data_at(row_idx);
2289
3
                const JsonbDocument* doc = nullptr;
2290
3
                RETURN_IF_ERROR(JsonbDocument::checkAndCreateDocument(value_string.data,
2291
3
                                                                      value_string.size, &doc));
2292
3
                if (doc) {
2293
3
                    json_values[index][row_idx] = doc->getValue();
2294
3
                }
2295
3
            }
2296
1
        }
2297
2298
1
        return Status::OK();
2299
1
    }
_ZNK5doris19FunctionJsonbModifyILNS_15JsonbModifyTypeE1EE22parse_paths_and_valuesERSt6vectorIS3_INS_9JsonbPathENS_18CustomStdAllocatorIS4_NS_9AllocatorILb0ELb0ELb0ENS_22DefaultMemoryAllocatorELb1EEEEEENS5_ISA_S8_EEERS3_IS3_IPKNS_10JsonbValueENS5_ISG_S8_EEENS5_ISI_S8_EEERKS3_IjSaIjEEmRKS3_IPKNS_9ColumnStrIjEESaIST_EERKS3_IbSaIbEERKS3_IPKNS_8PODArrayIhLm4096ES8_Lm16ELm15EEESaIS15_EESX_S11_S19_
Line
Count
Source
2252
1
                                  const std::vector<const NullMap*>& json_value_null_maps) const {
2253
2
        for (size_t i = 1; i < arguments.size(); i += 2) {
2254
1
            const size_t index = i / 2;
2255
1
            const auto* json_path_column = json_path_columns[index];
2256
1
            const auto* value_column = json_value_columns[index];
2257
2258
1
            json_paths[index].resize(json_path_constant[index] ? 1 : input_rows_count);
2259
1
            json_values[index].resize(json_value_constant[index] ? 1 : input_rows_count, nullptr);
2260
2261
4
            for (size_t row_idx = 0; row_idx != json_paths[index].size(); ++row_idx) {
2262
3
                if (json_path_null_maps[index] && (*json_path_null_maps[index])[row_idx]) {
2263
0
                    continue;
2264
0
                }
2265
2266
3
                auto path_string = json_path_column->get_data_at(row_idx);
2267
3
                if (!json_paths[index][row_idx].seek(path_string.data, path_string.size)) {
2268
0
                    return Status::InvalidArgument(
2269
0
                            "Json path error: Invalid Json Path for value: {}, "
2270
0
                            "argument "
2271
0
                            "index: {}, row index: {}",
2272
0
                            std::string_view(path_string.data, path_string.size), i, row_idx);
2273
0
                }
2274
2275
3
                if (json_paths[index][row_idx].is_wildcard()) {
2276
0
                    return Status::InvalidArgument(
2277
0
                            "In this situation, path expressions may not contain the * and ** "
2278
0
                            "tokens, argument index: {}, row index: {}",
2279
0
                            i, row_idx);
2280
0
                }
2281
3
            }
2282
2283
4
            for (size_t row_idx = 0; row_idx != json_values[index].size(); ++row_idx) {
2284
3
                if (json_value_null_maps[index] && (*json_value_null_maps[index])[row_idx]) {
2285
0
                    continue;
2286
0
                }
2287
2288
3
                auto value_string = value_column->get_data_at(row_idx);
2289
3
                const JsonbDocument* doc = nullptr;
2290
3
                RETURN_IF_ERROR(JsonbDocument::checkAndCreateDocument(value_string.data,
2291
3
                                                                      value_string.size, &doc));
2292
3
                if (doc) {
2293
3
                    json_values[index][row_idx] = doc->getValue();
2294
3
                }
2295
3
            }
2296
1
        }
2297
2298
1
        return Status::OK();
2299
1
    }
Unexecuted instantiation: _ZNK5doris19FunctionJsonbModifyILNS_15JsonbModifyTypeE2EE22parse_paths_and_valuesERSt6vectorIS3_INS_9JsonbPathENS_18CustomStdAllocatorIS4_NS_9AllocatorILb0ELb0ELb0ENS_22DefaultMemoryAllocatorELb1EEEEEENS5_ISA_S8_EEERS3_IS3_IPKNS_10JsonbValueENS5_ISG_S8_EEENS5_ISI_S8_EEERKS3_IjSaIjEEmRKS3_IPKNS_9ColumnStrIjEESaIST_EERKS3_IbSaIbEERKS3_IPKNS_8PODArrayIhLm4096ES8_Lm16ELm15EEESaIS15_EESX_S11_S19_
2300
};
2301
2302
struct JsonbContainsAndPathImpl {
2303
3
    static DataTypes get_variadic_argument_types() {
2304
3
        return {std::make_shared<DataTypeJsonb>(), std::make_shared<DataTypeJsonb>(),
2305
3
                std::make_shared<DataTypeString>()};
2306
3
    }
2307
2308
    static Status execute_impl(FunctionContext* context, Block& block,
2309
                               const ColumnNumbers& arguments, uint32_t result,
2310
2
                               size_t input_rows_count) {
2311
2
        return JsonbContainsUtil::jsonb_contains_execute(context, block, arguments, result,
2312
2
                                                         input_rows_count);
2313
2
    }
2314
};
2315
2316
class FunctionJsonSearch : public IFunction {
2317
private:
2318
    using OneFun = std::function<Status(size_t, bool*)>;
2319
0
    static Status always_one(size_t i, bool* res) {
2320
0
        *res = true;
2321
0
        return Status::OK();
2322
0
    }
2323
0
    static Status always_all(size_t i, bool* res) {
2324
0
        *res = false;
2325
0
        return Status::OK();
2326
0
    }
2327
2328
    using CheckNullFun = std::function<bool(size_t)>;
2329
0
    static bool always_not_null(size_t) { return false; }
2330
2331
    using GetJsonStringRefFun = std::function<StringRef(size_t)>;
2332
2333
0
    Status matched(const std::string_view& str, LikeState* state, unsigned char* res) const {
2334
0
        StringRef pattern; // not used
2335
0
        StringRef value_val(str.data(), str.size());
2336
0
        return (state->scalar_function)(&state->search_state, value_val, pattern, res);
2337
0
    }
2338
2339
    /**
2340
     * Recursive search for matching string, if found, the result will be added to a vector
2341
     * @param element json element
2342
     * @param one_match
2343
     * @param search_str
2344
     * @param cur_path
2345
     * @param matches The path that has already been matched
2346
     * @return true if matched else false
2347
     */
2348
    bool find_matches(const JsonbValue* element, const bool& one_match, LikeState* state,
2349
0
                      JsonbPath* cur_path, std::unordered_set<std::string>* matches) const {
2350
0
        if (element->isString()) {
2351
0
            const auto* json_string = element->unpack<JsonbStringVal>();
2352
0
            const std::string_view element_str(json_string->getBlob(), json_string->length());
2353
0
            unsigned char res;
2354
0
            RETURN_IF_ERROR(matched(element_str, state, &res));
2355
0
            if (res) {
2356
0
                std::string str;
2357
0
                auto valid = cur_path->to_string(&str);
2358
0
                if (!valid) {
2359
0
                    return false;
2360
0
                }
2361
0
                return matches->insert(str).second;
2362
0
            } else {
2363
0
                return false;
2364
0
            }
2365
0
        } else if (element->isObject()) {
2366
0
            const auto* object = element->unpack<ObjectVal>();
2367
0
            bool find = false;
2368
0
            for (const auto& item : *object) {
2369
0
                Slice key(item.getKeyStr(), item.klen());
2370
0
                const auto* child_element = item.value();
2371
                // construct an object member path leg.
2372
0
                auto leg = std::make_unique<leg_info>(key.data, key.size, 0, MEMBER_CODE);
2373
0
                cur_path->add_leg_to_leg_vector(std::move(leg));
2374
0
                find |= find_matches(child_element, one_match, state, cur_path, matches);
2375
0
                cur_path->pop_leg_from_leg_vector();
2376
0
                if (one_match && find) {
2377
0
                    return true;
2378
0
                }
2379
0
            }
2380
0
            return find;
2381
0
        } else if (element->isArray()) {
2382
0
            const auto* array = element->unpack<ArrayVal>();
2383
0
            bool find = false;
2384
0
            for (int i = 0; i < array->numElem(); ++i) {
2385
0
                auto leg = std::make_unique<leg_info>(nullptr, 0, i, ARRAY_CODE);
2386
0
                cur_path->add_leg_to_leg_vector(std::move(leg));
2387
0
                const auto* child_element = array->get(i);
2388
                // construct an array cell path leg.
2389
0
                find |= find_matches(child_element, one_match, state, cur_path, matches);
2390
0
                cur_path->pop_leg_from_leg_vector();
2391
0
                if (one_match && find) {
2392
0
                    return true;
2393
0
                }
2394
0
            }
2395
0
            return find;
2396
0
        } else {
2397
0
            return false;
2398
0
        }
2399
0
    }
2400
2401
    void make_result_str(JsonbWriter& writer, std::unordered_set<std::string>& matches,
2402
0
                         ColumnString* result_col) const {
2403
0
        if (matches.size() == 1) {
2404
0
            for (const auto& str_ref : matches) {
2405
0
                writer.writeStartString();
2406
0
                writer.writeString(str_ref);
2407
0
                writer.writeEndString();
2408
0
            }
2409
0
        } else {
2410
0
            writer.writeStartArray();
2411
0
            for (const auto& str_ref : matches) {
2412
0
                writer.writeStartString();
2413
0
                writer.writeString(str_ref);
2414
0
                writer.writeEndString();
2415
0
            }
2416
0
            writer.writeEndArray();
2417
0
        }
2418
2419
0
        result_col->insert_data(writer.getOutput()->getBuffer(),
2420
0
                                (size_t)writer.getOutput()->getSize());
2421
0
    }
2422
2423
    template <bool search_is_const>
2424
    Status execute_vector(Block& block, size_t input_rows_count, CheckNullFun json_null_check,
2425
                          GetJsonStringRefFun col_json_string, CheckNullFun one_null_check,
2426
                          OneFun one_check, CheckNullFun search_null_check,
2427
                          const ColumnString* col_search_string, FunctionContext* context,
2428
0
                          size_t result) const {
2429
0
        auto result_col = ColumnString::create();
2430
0
        auto null_map = ColumnUInt8::create(input_rows_count, 0);
2431
2432
0
        std::shared_ptr<LikeState> state_ptr;
2433
0
        LikeState* state = nullptr;
2434
0
        if (search_is_const) {
2435
0
            state = reinterpret_cast<LikeState*>(
2436
0
                    context->get_function_state(FunctionContext::THREAD_LOCAL));
2437
0
        }
2438
2439
0
        bool is_one = false;
2440
2441
0
        JsonbWriter writer;
2442
0
        for (size_t i = 0; i < input_rows_count; ++i) {
2443
            // an error occurs if the json_doc argument is not a valid json document.
2444
0
            if (json_null_check(i)) {
2445
0
                null_map->get_data()[i] = 1;
2446
0
                result_col->insert_data("", 0);
2447
0
                continue;
2448
0
            }
2449
0
            const auto& json_doc_str = col_json_string(i);
2450
0
            const JsonbDocument* json_doc = nullptr;
2451
0
            auto st = JsonbDocument::checkAndCreateDocument(json_doc_str.data, json_doc_str.size,
2452
0
                                                            &json_doc);
2453
0
            if (!st.ok()) {
2454
0
                return Status::InvalidArgument(
2455
0
                        "the json_doc argument at row {} is not a valid json document: {}", i,
2456
0
                        st.to_string());
2457
0
            }
2458
2459
0
            if (!one_null_check(i)) {
2460
0
                RETURN_IF_ERROR(one_check(i, &is_one));
2461
0
            }
2462
2463
0
            if (one_null_check(i) || search_null_check(i)) {
2464
0
                null_map->get_data()[i] = 1;
2465
0
                result_col->insert_data("", 0);
2466
0
                continue;
2467
0
            }
2468
2469
            // an error occurs if any path argument is not a valid path expression.
2470
0
            std::string root_path_str = "$";
2471
0
            JsonbPath root_path;
2472
0
            root_path.seek(root_path_str.c_str(), root_path_str.size());
2473
0
            std::vector<JsonbPath*> paths;
2474
0
            paths.push_back(&root_path);
2475
2476
0
            if (!search_is_const) {
2477
0
                state_ptr = std::make_shared<LikeState>();
2478
0
                state_ptr->is_like_pattern = true;
2479
0
                const auto& search_str = col_search_string->get_data_at(i);
2480
0
                RETURN_IF_ERROR(FunctionLike::construct_like_const_state(context, search_str,
2481
0
                                                                         state_ptr, false));
2482
0
                state = state_ptr.get();
2483
0
            }
2484
2485
            // maintain a hashset to deduplicate matches.
2486
0
            std::unordered_set<std::string> matches;
2487
0
            for (const auto& item : paths) {
2488
0
                auto* cur_path = item;
2489
0
                auto find = find_matches(json_doc->getValue(), is_one, state, cur_path, &matches);
2490
0
                if (is_one && find) {
2491
0
                    break;
2492
0
                }
2493
0
            }
2494
0
            if (matches.empty()) {
2495
                // returns NULL if the search_str is not found in the document.
2496
0
                null_map->get_data()[i] = 1;
2497
0
                result_col->insert_data("", 0);
2498
0
                continue;
2499
0
            }
2500
2501
0
            writer.reset();
2502
0
            make_result_str(writer, matches, result_col.get());
2503
0
        }
2504
0
        auto result_col_nullable =
2505
0
                ColumnNullable::create(std::move(result_col), std::move(null_map));
2506
0
        block.replace_by_position(result, std::move(result_col_nullable));
2507
0
        return Status::OK();
2508
0
    }
Unexecuted instantiation: _ZNK5doris18FunctionJsonSearch14execute_vectorILb1EEENS_6StatusERNS_5BlockEmSt8functionIFbmEES5_IFNS_9StringRefEmEES7_S5_IFS2_mPbEES7_PKNS_9ColumnStrIjEEPNS_15FunctionContextEm
Unexecuted instantiation: _ZNK5doris18FunctionJsonSearch14execute_vectorILb0EEENS_6StatusERNS_5BlockEmSt8functionIFbmEES5_IFNS_9StringRefEmEES7_S5_IFS2_mPbEES7_PKNS_9ColumnStrIjEEPNS_15FunctionContextEm
2509
2510
    static constexpr auto one = "one";
2511
    static constexpr auto all = "all";
2512
2513
public:
2514
    static constexpr auto name = "json_search";
2515
2
    static FunctionPtr create() { return std::make_shared<FunctionJsonSearch>(); }
2516
2517
1
    String get_name() const override { return name; }
2518
1
    bool is_variadic() const override { return false; }
2519
0
    size_t get_number_of_arguments() const override { return 3; }
2520
2521
0
    DataTypePtr get_return_type_impl(const DataTypes& arguments) const override {
2522
0
        return make_nullable(std::make_shared<DataTypeJsonb>());
2523
0
    }
2524
2525
0
    bool use_default_implementation_for_nulls() const override { return false; }
2526
2527
0
    Status open(FunctionContext* context, FunctionContext::FunctionStateScope scope) override {
2528
0
        if (scope != FunctionContext::THREAD_LOCAL) {
2529
0
            return Status::OK();
2530
0
        }
2531
0
        if (context->is_col_constant(2)) {
2532
0
            std::shared_ptr<LikeState> state = std::make_shared<LikeState>();
2533
0
            state->is_like_pattern = true;
2534
0
            const auto pattern_col = context->get_constant_col(2)->column_ptr;
2535
0
            const auto& pattern = pattern_col->get_data_at(0);
2536
0
            RETURN_IF_ERROR(
2537
0
                    FunctionLike::construct_like_const_state(context, pattern, state, false));
2538
0
            context->set_function_state(scope, state);
2539
0
        }
2540
0
        return Status::OK();
2541
0
    }
2542
2543
    Status execute_impl(FunctionContext* context, Block& block, const ColumnNumbers& arguments,
2544
0
                        uint32_t result, size_t input_rows_count) const override {
2545
        // the json_doc, one_or_all, and search_str must be given.
2546
        // and we require the positions are static.
2547
0
        if (arguments.size() < 3) {
2548
0
            return Status::InvalidArgument("too few arguments for function {}", name);
2549
0
        }
2550
0
        if (arguments.size() > 3) {
2551
0
            return Status::NotSupported("escape and path params are not support now");
2552
0
        }
2553
2554
0
        CheckNullFun json_null_check = always_not_null;
2555
0
        GetJsonStringRefFun get_json_fun;
2556
        // prepare jsonb data column
2557
0
        auto&& [col_json, json_is_const] =
2558
0
                unpack_if_const(block.get_by_position(arguments[0]).column);
2559
0
        const auto* col_json_string = check_and_get_column<ColumnString>(col_json.get());
2560
0
        if (const auto* nullable = check_and_get_column<ColumnNullable>(col_json.get())) {
2561
0
            col_json_string =
2562
0
                    check_and_get_column<ColumnString>(nullable->get_nested_column_ptr().get());
2563
0
        }
2564
2565
0
        if (!col_json_string) {
2566
0
            return Status::RuntimeError("Illegal arg json {} should be ColumnString",
2567
0
                                        col_json->get_name());
2568
0
        }
2569
2570
0
        auto create_all_null_result = [&]() {
2571
0
            auto res_str = ColumnString::create();
2572
0
            res_str->insert_default();
2573
0
            auto res = ColumnNullable::create(std::move(res_str), ColumnUInt8::create(1, 1));
2574
0
            if (input_rows_count > 1) {
2575
0
                block.get_by_position(result).column =
2576
0
                        ColumnConst::create(std::move(res), input_rows_count);
2577
0
            } else {
2578
0
                block.get_by_position(result).column = std::move(res);
2579
0
            }
2580
0
            return Status::OK();
2581
0
        };
2582
2583
0
        if (json_is_const) {
2584
0
            if (col_json->is_null_at(0)) {
2585
0
                return create_all_null_result();
2586
0
            } else {
2587
0
                const auto& json_str = col_json_string->get_data_at(0);
2588
0
                get_json_fun = [json_str](size_t i) { return json_str; };
2589
0
            }
2590
0
        } else {
2591
0
            json_null_check = [col_json](size_t i) { return col_json->is_null_at(i); };
2592
0
            get_json_fun = [col_json_string](size_t i) { return col_json_string->get_data_at(i); };
2593
0
        }
2594
2595
        // one_or_all
2596
0
        CheckNullFun one_null_check = always_not_null;
2597
0
        OneFun one_check = always_one;
2598
0
        auto&& [col_one, one_is_const] =
2599
0
                unpack_if_const(block.get_by_position(arguments[1]).column);
2600
0
        one_is_const |= input_rows_count == 1;
2601
0
        const auto* col_one_string = check_and_get_column<ColumnString>(col_one.get());
2602
0
        if (const auto* nullable = check_and_get_column<ColumnNullable>(col_one.get())) {
2603
0
            col_one_string = check_and_get_column<ColumnString>(*nullable->get_nested_column_ptr());
2604
0
        }
2605
0
        if (!col_one_string) {
2606
0
            return Status::RuntimeError("Illegal arg one {} should be ColumnString",
2607
0
                                        col_one->get_name());
2608
0
        }
2609
0
        if (one_is_const) {
2610
0
            if (col_one->is_null_at(0)) {
2611
0
                return create_all_null_result();
2612
0
            } else {
2613
0
                const auto& one_or_all = col_one_string->get_data_at(0);
2614
0
                std::string one_or_all_str = one_or_all.to_string();
2615
0
                if (strcasecmp(one_or_all_str.c_str(), all) == 0) {
2616
0
                    one_check = always_all;
2617
0
                } else if (strcasecmp(one_or_all_str.c_str(), one) == 0) {
2618
                    // nothing
2619
0
                } else {
2620
                    // an error occurs if the one_or_all argument is not 'one' nor 'all'.
2621
0
                    return Status::InvalidArgument(
2622
0
                            "the one_or_all argument {} is not 'one' not 'all'", one_or_all_str);
2623
0
                }
2624
0
            }
2625
0
        } else {
2626
0
            one_null_check = [col_one](size_t i) { return col_one->is_null_at(i); };
2627
0
            one_check = [col_one_string](size_t i, bool* is_one) {
2628
0
                const auto& one_or_all = col_one_string->get_data_at(i);
2629
0
                std::string one_or_all_str = one_or_all.to_string();
2630
0
                if (strcasecmp(one_or_all_str.c_str(), all) == 0) {
2631
0
                    *is_one = false;
2632
0
                } else if (strcasecmp(one_or_all_str.c_str(), one) == 0) {
2633
0
                    *is_one = true;
2634
0
                } else {
2635
                    // an error occurs if the one_or_all argument is not 'one' nor 'all'.
2636
0
                    return Status::InvalidArgument(
2637
0
                            "the one_or_all argument {} is not 'one' not 'all'", one_or_all_str);
2638
0
                }
2639
0
                return Status::OK();
2640
0
            };
2641
0
        }
2642
2643
        // search_str
2644
0
        auto&& [col_search, search_is_const] =
2645
0
                unpack_if_const(block.get_by_position(arguments[2]).column);
2646
2647
0
        const auto* col_search_string = check_and_get_column<ColumnString>(col_search.get());
2648
0
        if (const auto* nullable = check_and_get_column<ColumnNullable>(col_search.get())) {
2649
0
            col_search_string =
2650
0
                    check_and_get_column<ColumnString>(*nullable->get_nested_column_ptr());
2651
0
        }
2652
0
        if (!col_search_string) {
2653
0
            return Status::RuntimeError("Illegal arg pattern {} should be ColumnString",
2654
0
                                        col_search->get_name());
2655
0
        }
2656
0
        if (search_is_const) {
2657
0
            CheckNullFun search_null_check = always_not_null;
2658
0
            if (col_search->is_null_at(0)) {
2659
0
                return create_all_null_result();
2660
0
            }
2661
0
            RETURN_IF_ERROR(execute_vector<true>(
2662
0
                    block, input_rows_count, json_null_check, get_json_fun, one_null_check,
2663
0
                    one_check, search_null_check, col_search_string, context, result));
2664
0
        } else {
2665
0
            CheckNullFun search_null_check = [col_search](size_t i) {
2666
0
                return col_search->is_null_at(i);
2667
0
            };
2668
0
            RETURN_IF_ERROR(execute_vector<false>(
2669
0
                    block, input_rows_count, json_null_check, get_json_fun, one_null_check,
2670
0
                    one_check, search_null_check, col_search_string, context, result));
2671
0
        }
2672
0
        return Status::OK();
2673
0
    }
2674
};
2675
2676
struct DocumentBuffer {
2677
    std::unique_ptr<char[]> ptr;
2678
    size_t size = 0;
2679
    size_t capacity = 0;
2680
};
2681
2682
class FunctionJsonbRemove : public IFunction {
2683
public:
2684
    static constexpr auto name = "jsonb_remove";
2685
    static constexpr auto alias = "json_remove";
2686
2687
2
    static FunctionPtr create() { return std::make_shared<FunctionJsonbRemove>(); }
2688
2689
0
    String get_name() const override { return name; }
2690
2691
0
    size_t get_number_of_arguments() const override { return 0; }
2692
1
    bool is_variadic() const override { return true; }
2693
2694
0
    bool use_default_implementation_for_nulls() const override { return false; }
2695
2696
0
    DataTypePtr get_return_type_impl(const DataTypes& arguments) const override {
2697
0
        return make_nullable(std::make_shared<DataTypeJsonb>());
2698
0
    }
2699
2700
    Status execute_impl(FunctionContext* context, Block& block, const ColumnNumbers& arguments,
2701
0
                        uint32_t result, size_t input_rows_count) const override {
2702
        // Check if arguments count is valid (json_doc + at least one path)
2703
0
        if (arguments.size() < 2) {
2704
0
            return Status::InvalidArgument("json_remove requires at least 2 arguments");
2705
0
        }
2706
2707
0
        auto return_data_type = make_nullable(std::make_shared<DataTypeJsonb>());
2708
0
        auto result_column = return_data_type->create_column();
2709
0
        auto& nullable_column = assert_cast<ColumnNullable&>(*result_column);
2710
0
        auto& res_chars =
2711
0
                assert_cast<ColumnString&>(nullable_column.get_nested_column()).get_chars();
2712
0
        auto& res_offsets =
2713
0
                assert_cast<ColumnString&>(nullable_column.get_nested_column()).get_offsets();
2714
0
        auto& null_map = nullable_column.get_null_map_data();
2715
2716
0
        res_chars.reserve(input_rows_count * 64);
2717
0
        res_offsets.resize(input_rows_count);
2718
0
        null_map.resize_fill(input_rows_count, 0);
2719
2720
        // Get JSON document column
2721
0
        auto [json_column, json_const] =
2722
0
                unpack_if_const(block.get_by_position(arguments[0]).column);
2723
0
        const auto* json_nullable = check_and_get_column<ColumnNullable>(json_column.get());
2724
0
        const ColumnString* json_data_column = nullptr;
2725
0
        const NullMap* json_null_map = nullptr;
2726
2727
0
        if (json_nullable) {
2728
0
            json_null_map = &json_nullable->get_null_map_data();
2729
0
            json_data_column =
2730
0
                    check_and_get_column<ColumnString>(&json_nullable->get_nested_column());
2731
0
        } else {
2732
0
            json_data_column = check_and_get_column<ColumnString>(json_column.get());
2733
0
        }
2734
2735
0
        if (!json_data_column) {
2736
0
            return Status::InvalidArgument("First argument must be a JSON document");
2737
0
        }
2738
2739
        // Parse paths
2740
0
        std::vector<const ColumnString*> path_columns;
2741
0
        std::vector<const NullMap*> path_null_maps;
2742
0
        std::vector<bool> path_constants;
2743
2744
0
        for (size_t i = 1; i < arguments.size(); ++i) {
2745
0
            auto [path_column, path_const] =
2746
0
                    unpack_if_const(block.get_by_position(arguments[i]).column);
2747
0
            const auto* path_nullable = check_and_get_column<ColumnNullable>(path_column.get());
2748
2749
0
            if (path_nullable) {
2750
0
                path_null_maps.push_back(&path_nullable->get_null_map_data());
2751
0
                path_columns.push_back(
2752
0
                        check_and_get_column<ColumnString>(&path_nullable->get_nested_column()));
2753
0
            } else {
2754
0
                path_null_maps.push_back(nullptr);
2755
0
                path_columns.push_back(check_and_get_column<ColumnString>(path_column.get()));
2756
0
            }
2757
2758
0
            if (!path_columns.back()) {
2759
0
                return Status::InvalidArgument(
2760
0
                        fmt::format("Argument {} must be a string path", i + 1));
2761
0
            }
2762
2763
0
            path_constants.push_back(path_const);
2764
0
        }
2765
2766
        // Reusable JsonbWriter for performance
2767
0
        JsonbWriter writer;
2768
2769
0
        for (size_t row_idx = 0; row_idx < input_rows_count; ++row_idx) {
2770
0
            size_t json_idx = index_check_const(row_idx, json_const);
2771
2772
            // Check if JSON document is null
2773
0
            if (json_null_map && (*json_null_map)[json_idx]) {
2774
0
                null_map[row_idx] = 1;
2775
0
                res_offsets[row_idx] = static_cast<uint32_t>(res_chars.size());
2776
0
                continue;
2777
0
            }
2778
2779
            // Parse JSON document
2780
0
            const auto& json_data = json_data_column->get_data_at(json_idx);
2781
0
            const JsonbDocument* json_doc = nullptr;
2782
0
            Status parse_status = JsonbDocument::checkAndCreateDocument(json_data.data,
2783
0
                                                                        json_data.size, &json_doc);
2784
2785
0
            if (!parse_status.ok() || !json_doc) {
2786
0
                null_map[row_idx] = 1;
2787
0
                res_offsets[row_idx] = static_cast<uint32_t>(res_chars.size());
2788
0
                continue;
2789
0
            }
2790
2791
            // Check if any path is null
2792
0
            bool has_null_path = false;
2793
0
            for (size_t path_idx = 0; path_idx < path_columns.size(); ++path_idx) {
2794
0
                size_t idx = index_check_const(row_idx, path_constants[path_idx]);
2795
0
                if (path_null_maps[path_idx] && (*path_null_maps[path_idx])[idx]) {
2796
0
                    has_null_path = true;
2797
0
                    break;
2798
0
                }
2799
0
            }
2800
2801
0
            if (has_null_path) {
2802
0
                null_map[row_idx] = 1;
2803
0
                res_offsets[row_idx] = static_cast<uint32_t>(res_chars.size());
2804
0
                continue;
2805
0
            }
2806
2807
0
            std::vector<JsonbPath> paths;
2808
2809
0
            for (size_t path_idx = 0; path_idx < path_columns.size(); ++path_idx) {
2810
0
                size_t idx = index_check_const(row_idx, path_constants[path_idx]);
2811
0
                const auto& path_data = path_columns[path_idx]->get_data_at(idx);
2812
2813
0
                JsonbPath path;
2814
0
                if (!path.seek(path_data.data, path_data.size)) {
2815
0
                    return Status::InvalidArgument(
2816
0
                            "Json path error: Invalid Json Path for value: {} at row: {}",
2817
0
                            std::string_view(path_data.data, path_data.size), row_idx);
2818
0
                }
2819
2820
0
                if (path.is_wildcard() || path.is_supper_wildcard()) {
2821
0
                    return Status::InvalidArgument(
2822
0
                            "In this situation, path expressions may not contain the * and ** "
2823
0
                            "tokens or an array range, argument index: {}, row index: {}",
2824
0
                            path_idx + 1, row_idx);
2825
0
                }
2826
2827
0
                paths.push_back(std::move(path));
2828
0
            }
2829
2830
0
            const JsonbValue* current_value = json_doc->getValue();
2831
2832
0
            DocumentBuffer tmp_buffer;
2833
2834
0
            for (size_t path_idx = 0; path_idx < paths.size(); ++path_idx) {
2835
0
                writer.reset();
2836
2837
0
                auto find_result = current_value->findValue(paths[path_idx]);
2838
2839
0
                if (find_result.is_wildcard) {
2840
0
                    continue;
2841
0
                }
2842
2843
0
                if (find_result.value) {
2844
0
                    RETURN_IF_ERROR(clone_without_path(current_value, paths[path_idx], writer));
2845
2846
0
                    auto* writer_output = writer.getOutput();
2847
0
                    if (writer_output->getSize() > tmp_buffer.capacity) {
2848
0
                        tmp_buffer.capacity =
2849
0
                                ((size_t(writer_output->getSize()) + 1024 - 1) / 1024) * 1024;
2850
0
                        tmp_buffer.ptr = std::make_unique<char[]>(tmp_buffer.capacity);
2851
0
                        DCHECK_LE(writer_output->getSize(), tmp_buffer.capacity);
2852
0
                    }
2853
2854
0
                    memcpy(tmp_buffer.ptr.get(), writer_output->getBuffer(),
2855
0
                           writer_output->getSize());
2856
0
                    tmp_buffer.size = writer_output->getSize();
2857
2858
0
                    const JsonbDocument* new_doc = nullptr;
2859
0
                    RETURN_IF_ERROR(JsonbDocument::checkAndCreateDocument(
2860
0
                            tmp_buffer.ptr.get(), tmp_buffer.size, &new_doc));
2861
2862
0
                    current_value = new_doc->getValue();
2863
0
                }
2864
0
            }
2865
2866
0
            const JsonbDocument* modified_doc = nullptr;
2867
0
            if (current_value != json_doc->getValue()) {
2868
0
                RETURN_IF_ERROR(JsonbDocument::checkAndCreateDocument(
2869
0
                        tmp_buffer.ptr.get(), tmp_buffer.size, &modified_doc));
2870
0
            } else {
2871
0
                modified_doc = json_doc;
2872
0
            }
2873
2874
            // Write the final result
2875
0
            const auto size = modified_doc->numPackedBytes();
2876
0
            res_chars.insert(reinterpret_cast<const char*>(modified_doc),
2877
0
                             reinterpret_cast<const char*>(modified_doc) + size);
2878
0
            res_offsets[row_idx] = static_cast<uint32_t>(res_chars.size());
2879
0
        }
2880
2881
0
        block.get_by_position(result).column = std::move(result_column);
2882
0
        return Status::OK();
2883
0
    }
2884
2885
private:
2886
    Status clone_without_path(const JsonbValue* root, const JsonbPath& path,
2887
0
                              JsonbWriter& writer) const {
2888
        // Start writing at the root level
2889
0
        if (root->isObject()) {
2890
0
            writer.writeStartObject();
2891
0
            RETURN_IF_ERROR(clone_object_without_path(root, path, 0, writer));
2892
0
            writer.writeEndObject();
2893
0
        } else if (root->isArray()) {
2894
0
            writer.writeStartArray();
2895
0
            RETURN_IF_ERROR(clone_array_without_path(root, path, 0, writer));
2896
0
            writer.writeEndArray();
2897
0
        } else {
2898
            // Primitive value - can't remove anything from it
2899
0
            writer.writeValue(root);
2900
0
        }
2901
0
        return Status::OK();
2902
0
    }
2903
2904
    Status clone_object_without_path(const JsonbValue* obj_value, const JsonbPath& path,
2905
0
                                     size_t depth, JsonbWriter& writer) const {
2906
0
        const auto* obj = obj_value->unpack<ObjectVal>();
2907
2908
0
        for (const auto& kv : *obj) {
2909
0
            std::string key(kv.getKeyStr(), kv.klen());
2910
2911
0
            if (depth < path.get_leg_vector_size()) {
2912
0
                const auto* leg = path.get_leg_from_leg_vector(depth);
2913
0
                if (leg->type == MEMBER_CODE) {
2914
0
                    std::string target_key(leg->leg_ptr, leg->leg_len);
2915
2916
0
                    if (key == target_key) {
2917
0
                        if (depth == path.get_leg_vector_size() - 1) {
2918
0
                            continue;
2919
0
                        } else {
2920
0
                            writer.writeKey(kv.getKeyStr(), kv.klen());
2921
0
                            if (kv.value()->isObject()) {
2922
0
                                writer.writeStartObject();
2923
0
                                RETURN_IF_ERROR(clone_object_without_path(kv.value(), path,
2924
0
                                                                          depth + 1, writer));
2925
0
                                writer.writeEndObject();
2926
0
                            } else if (kv.value()->isArray()) {
2927
0
                                writer.writeStartArray();
2928
0
                                RETURN_IF_ERROR(clone_array_without_path(kv.value(), path,
2929
0
                                                                         depth + 1, writer));
2930
0
                                writer.writeEndArray();
2931
0
                            } else {
2932
0
                                writer.writeValue(kv.value());
2933
0
                            }
2934
0
                        }
2935
0
                    } else {
2936
0
                        writer.writeKey(kv.getKeyStr(), kv.klen());
2937
0
                        writer.writeValue(kv.value());
2938
0
                    }
2939
0
                } else {
2940
0
                    writer.writeKey(kv.getKeyStr(), kv.klen());
2941
0
                    writer.writeValue(kv.value());
2942
0
                }
2943
0
            } else {
2944
0
                writer.writeKey(kv.getKeyStr(), kv.klen());
2945
0
                writer.writeValue(kv.value());
2946
0
            }
2947
0
        }
2948
2949
0
        return Status::OK();
2950
0
    }
2951
2952
    Status clone_array_without_path(const JsonbValue* arr_value, const JsonbPath& path,
2953
0
                                    size_t depth, JsonbWriter& writer) const {
2954
0
        const auto* arr = arr_value->unpack<ArrayVal>();
2955
2956
0
        int index = 0;
2957
0
        for (const auto& element : *arr) {
2958
0
            if (depth < path.get_leg_vector_size()) {
2959
0
                const auto* leg = path.get_leg_from_leg_vector(depth);
2960
0
                if (leg->type == ARRAY_CODE) {
2961
0
                    int target_index = leg->array_index;
2962
2963
0
                    if (index == target_index) {
2964
0
                        if (depth == path.get_leg_vector_size() - 1) {
2965
                            // This is the target element to remove - skip it
2966
0
                        } else {
2967
0
                            if (element.isObject()) {
2968
0
                                writer.writeStartObject();
2969
0
                                RETURN_IF_ERROR(clone_object_without_path(&element, path, depth + 1,
2970
0
                                                                          writer));
2971
0
                                writer.writeEndObject();
2972
0
                            } else if (element.isArray()) {
2973
0
                                writer.writeStartArray();
2974
0
                                RETURN_IF_ERROR(clone_array_without_path(&element, path, depth + 1,
2975
0
                                                                         writer));
2976
0
                                writer.writeEndArray();
2977
0
                            } else {
2978
0
                                writer.writeValue(&element);
2979
0
                            }
2980
0
                        }
2981
0
                    } else {
2982
0
                        writer.writeValue(&element);
2983
0
                    }
2984
0
                } else {
2985
0
                    writer.writeValue(&element);
2986
0
                }
2987
0
            } else {
2988
0
                writer.writeValue(&element);
2989
0
            }
2990
0
            index++;
2991
0
        }
2992
2993
0
        return Status::OK();
2994
0
    }
2995
};
2996
2997
class FunctionStripNullValue : public IFunction {
2998
public:
2999
    static constexpr auto name = "strip_null_value";
3000
2
    static FunctionPtr create() { return std::make_shared<FunctionStripNullValue>(); }
3001
3002
1
    String get_name() const override { return name; }
3003
1
    bool is_variadic() const override { return false; }
3004
0
    size_t get_number_of_arguments() const override { return 1; }
3005
3006
0
    bool use_default_implementation_for_nulls() const override { return false; }
3007
3008
0
    DataTypePtr get_return_type_impl(const DataTypes& arguments) const override {
3009
0
        return make_nullable(std::make_shared<DataTypeJsonb>());
3010
0
    }
3011
3012
    Status execute_impl(FunctionContext* context, Block& block, const ColumnNumbers& arguments,
3013
0
                        uint32_t result, size_t input_rows_count) const override {
3014
0
        const auto arg_column =
3015
0
                block.get_by_position(arguments[0]).column->convert_to_full_column_if_const();
3016
0
        const ColumnString* json_column = nullptr;
3017
0
        const NullMap* json_null_map = nullptr;
3018
0
        if (const auto* nullable_col = check_and_get_column<ColumnNullable>(arg_column.get())) {
3019
0
            json_column = assert_cast<const ColumnString*>(&nullable_col->get_nested_column());
3020
0
            json_null_map = &nullable_col->get_null_map_data();
3021
0
        } else {
3022
0
            json_column = assert_cast<const ColumnString*>(arg_column.get());
3023
0
        }
3024
3025
0
        auto return_data_type = make_nullable(std::make_shared<DataTypeJsonb>());
3026
0
        auto result_column = return_data_type->create_column();
3027
3028
0
        auto& result_nullmap = assert_cast<ColumnNullable&>(*result_column).get_null_map_data();
3029
0
        auto& result_data_col = assert_cast<ColumnString&>(
3030
0
                assert_cast<ColumnNullable&>(*result_column).get_nested_column());
3031
3032
0
        result_nullmap.resize_fill(input_rows_count, 0);
3033
0
        for (size_t i = 0; i != input_rows_count; ++i) {
3034
0
            if (json_null_map && (*json_null_map)[i]) {
3035
0
                result_nullmap[i] = 1;
3036
0
                result_data_col.insert_default();
3037
0
                continue;
3038
0
            }
3039
0
            const JsonbDocument* json_doc = nullptr;
3040
0
            const auto& json_str = json_column->get_data_at(i);
3041
0
            RETURN_IF_ERROR(
3042
0
                    JsonbDocument::checkAndCreateDocument(json_str.data, json_str.size, &json_doc));
3043
0
            if (json_doc) [[likely]] {
3044
0
                if (json_doc->getValue()->isNull()) {
3045
0
                    result_nullmap[i] = 1;
3046
0
                    result_data_col.insert_default();
3047
0
                } else {
3048
0
                    result_nullmap[i] = 0;
3049
0
                    result_data_col.insert_data(json_str.data, json_str.size);
3050
0
                }
3051
0
            } else {
3052
0
                result_nullmap[i] = 1;
3053
0
                result_data_col.insert_default();
3054
0
            }
3055
0
        }
3056
3057
0
        block.get_by_position(result).column = std::move(result_column);
3058
0
        return Status::OK();
3059
0
    }
3060
};
3061
3062
1
void register_function_jsonb(SimpleFunctionFactory& factory) {
3063
1
    factory.register_function<FunctionJsonbParse>(FunctionJsonbParse::name);
3064
1
    factory.register_alias(FunctionJsonbParse::name, FunctionJsonbParse::alias);
3065
1
    factory.register_function<FunctionJsonbParseErrorNull>("json_parse_error_to_null");
3066
1
    factory.register_alias("json_parse_error_to_null", "jsonb_parse_error_to_null");
3067
1
    factory.register_function<FunctionJsonbParseErrorValue>("json_parse_error_to_value");
3068
1
    factory.register_alias("json_parse_error_to_value", "jsonb_parse_error_to_value");
3069
3070
1
    factory.register_function<FunctionJsonbExists>();
3071
1
    factory.register_alias(FunctionJsonbExists::name, FunctionJsonbExists::alias);
3072
1
    factory.register_function<FunctionJsonbType>();
3073
1
    factory.register_alias(FunctionJsonbType::name, FunctionJsonbType::alias);
3074
3075
1
    factory.register_function<FunctionJsonbKeys>();
3076
1
    factory.register_alias(FunctionJsonbKeys::name, FunctionJsonbKeys::alias);
3077
3078
1
    factory.register_function<FunctionJsonbExtractIsnull>();
3079
1
    factory.register_alias(FunctionJsonbExtractIsnull::name, FunctionJsonbExtractIsnull::alias);
3080
3081
1
    factory.register_function<FunctionJsonbExtractJsonb>();
3082
1
    factory.register_alias(FunctionJsonbExtractJsonb::name, FunctionJsonbExtractJsonb::alias);
3083
1
    factory.register_function<FunctionJsonbExtractJsonbNoQuotes>();
3084
1
    factory.register_alias(FunctionJsonbExtractJsonbNoQuotes::name,
3085
1
                           FunctionJsonbExtractJsonbNoQuotes::alias);
3086
3087
1
    factory.register_function<FunctionJsonbLength<JsonbLengthAndPathImpl>>();
3088
1
    factory.register_function<FunctionJsonbContains<JsonbContainsAndPathImpl>>();
3089
3090
1
    factory.register_function<FunctionJsonSearch>();
3091
3092
1
    factory.register_function<FunctionJsonbArray<false>>();
3093
1
    factory.register_alias(FunctionJsonbArray<false>::name, FunctionJsonbArray<false>::alias);
3094
3095
1
    factory.register_function<FunctionJsonbArray<true>>("json_array_ignore_null");
3096
1
    factory.register_alias("json_array_ignore_null", "jsonb_array_ignore_null");
3097
3098
1
    factory.register_function<FunctionJsonbObject>();
3099
1
    factory.register_alias(FunctionJsonbObject::name, FunctionJsonbObject::alias);
3100
3101
1
    factory.register_function<FunctionJsonbModify<JsonbModifyType::Insert>>();
3102
1
    factory.register_alias(FunctionJsonbModify<JsonbModifyType::Insert>::name,
3103
1
                           FunctionJsonbModify<JsonbModifyType::Insert>::alias);
3104
1
    factory.register_function<FunctionJsonbModify<JsonbModifyType::Set>>();
3105
1
    factory.register_alias(FunctionJsonbModify<JsonbModifyType::Set>::name,
3106
1
                           FunctionJsonbModify<JsonbModifyType::Set>::alias);
3107
1
    factory.register_function<FunctionJsonbModify<JsonbModifyType::Replace>>();
3108
1
    factory.register_alias(FunctionJsonbModify<JsonbModifyType::Replace>::name,
3109
1
                           FunctionJsonbModify<JsonbModifyType::Replace>::alias);
3110
3111
1
    factory.register_function<FunctionJsonbRemove>();
3112
1
    factory.register_alias(FunctionJsonbRemove::name, FunctionJsonbRemove::alias);
3113
3114
1
    factory.register_function<FunctionStripNullValue>();
3115
1
}
3116
3117
} // namespace doris