Coverage Report

Created: 2025-09-29 18:47

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/root/doris/be/src/vec/functions/function.cpp
Line
Count
Source
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
// This file is copied from
18
// https://github.com/ClickHouse/ClickHouse/blob/master/src/Functions/IFunction.cpp
19
// and modified by Doris
20
21
#include "vec/functions/function.h"
22
23
#include <algorithm>
24
#include <memory>
25
#include <numeric>
26
27
#include "common/status.h"
28
#include "runtime/primitive_type.h"
29
#include "vec/aggregate_functions/aggregate_function.h"
30
#include "vec/columns/column.h"
31
#include "vec/columns/column_const.h"
32
#include "vec/columns/column_nullable.h"
33
#include "vec/columns/column_vector.h"
34
#include "vec/common/assert_cast.h"
35
#include "vec/core/field.h"
36
#include "vec/data_types/data_type_array.h"
37
#include "vec/data_types/data_type_nothing.h"
38
#include "vec/data_types/data_type_nullable.h"
39
#include "vec/functions/function_helpers.h"
40
#include "vec/utils/util.hpp"
41
42
namespace doris::vectorized {
43
#include "common/compile_check_begin.h"
44
ColumnPtr wrap_in_nullable(const ColumnPtr& src, const Block& block, const ColumnNumbers& args,
45
68.9k
                           uint32_t result, size_t input_rows_count) {
46
68.9k
    ColumnPtr result_null_map_column;
47
    /// If result is already nullable.
48
68.9k
    ColumnPtr src_not_nullable = src;
49
68.9k
    MutableColumnPtr mutable_result_null_map_column;
50
51
68.9k
    if (const auto* nullable = check_and_get_column<ColumnNullable>(*src)) {
52
8.43k
        src_not_nullable = nullable->get_nested_column_ptr();
53
8.43k
        result_null_map_column = nullable->get_null_map_column_ptr();
54
8.43k
    }
55
56
93.3k
    for (const auto& arg : args) {
57
93.3k
        const ColumnWithTypeAndName& elem = block.get_by_position(arg);
58
93.3k
        if (!elem.type->is_nullable() || is_column_const(*elem.column)) {
59
19.7k
            continue;
60
19.7k
        }
61
62
73.5k
        if (const auto* nullable = assert_cast<const ColumnNullable*>(elem.column.get());
63
73.5k
            nullable->has_null()) {
64
1.05k
            const ColumnPtr& null_map_column = nullable->get_null_map_column_ptr();
65
1.05k
            if (!result_null_map_column) { // NOLINT(bugprone-use-after-move)
66
960
                result_null_map_column = null_map_column->clone_resized(input_rows_count);
67
960
                continue;
68
960
            }
69
70
94
            if (!mutable_result_null_map_column) {
71
70
                mutable_result_null_map_column =
72
70
                        std::move(result_null_map_column)->assume_mutable();
73
70
            }
74
75
94
            NullMap& result_null_map =
76
94
                    assert_cast<ColumnUInt8&>(*mutable_result_null_map_column).get_data();
77
94
            const NullMap& src_null_map =
78
94
                    assert_cast<const ColumnUInt8&>(*null_map_column).get_data();
79
80
94
            VectorizedUtils::update_null_map(result_null_map, src_null_map);
81
94
        }
82
73.5k
    }
83
84
68.9k
    if (!result_null_map_column) {
85
59.5k
        if (is_column_const(*src)) {
86
0
            return ColumnConst::create(
87
0
                    make_nullable(assert_cast<const ColumnConst&>(*src).get_data_column_ptr(),
88
0
                                  false),
89
0
                    input_rows_count);
90
0
        }
91
59.5k
        return ColumnNullable::create(src, ColumnUInt8::create(input_rows_count, 0));
92
59.5k
    }
93
94
9.39k
    return ColumnNullable::create(src_not_nullable, result_null_map_column);
95
68.9k
}
96
97
16.0k
bool have_null_column(const Block& block, const ColumnNumbers& args) {
98
29.0k
    return std::ranges::any_of(args, [&block](const auto& elem) {
99
29.0k
        return block.get_by_position(elem).type->is_nullable();
100
29.0k
    });
101
16.0k
}
102
103
11.5k
bool have_null_column(const ColumnsWithTypeAndName& args) {
104
11.5k
    return std::ranges::any_of(args, [](const auto& elem) { return elem.type->is_nullable(); });
105
11.5k
}
106
107
inline Status PreparedFunctionImpl::_execute_skipped_constant_deal(
108
        FunctionContext* context, Block& block, const ColumnNumbers& args, uint32_t result,
109
105k
        size_t input_rows_count, bool dry_run) const {
110
105k
    bool executed = false;
111
105k
    RETURN_IF_ERROR(default_implementation_for_nulls(context, block, args, result, input_rows_count,
112
105k
                                                     dry_run, &executed));
113
105k
    if (executed) {
114
11.3k
        return Status::OK();
115
11.3k
    }
116
117
94.6k
    if (dry_run) {
118
0
        return execute_impl_dry_run(context, block, args, result, input_rows_count);
119
94.6k
    } else {
120
94.6k
        return execute_impl(context, block, args, result, input_rows_count);
121
94.6k
    }
122
94.6k
}
123
124
Status PreparedFunctionImpl::default_implementation_for_constant_arguments(
125
        FunctionContext* context, Block& block, const ColumnNumbers& args, uint32_t result,
126
105k
        size_t input_rows_count, bool dry_run, bool* executed) const {
127
105k
    *executed = false;
128
105k
    ColumnNumbers args_expect_const = get_arguments_that_are_always_constant();
129
130
    // Check that these arguments are really constant.
131
105k
    for (auto arg_num : args_expect_const) {
132
85.5k
        if (arg_num < args.size() &&
133
85.5k
            !is_column_const(*block.get_by_position(args[arg_num]).column)) {
134
0
            return Status::InvalidArgument("Argument at index {} for function {} must be constant",
135
0
                                           arg_num, get_name());
136
0
        }
137
85.5k
    }
138
139
105k
    if (args.empty() || !use_default_implementation_for_constants() ||
140
105k
        !VectorizedUtils::all_arguments_are_constant(block, args)) {
141
103k
        return Status::OK();
142
103k
    }
143
144
    // now all columns are const.
145
2.44k
    Block temporary_block;
146
147
2.44k
    int arguments_size = (int)args.size();
148
8.16k
    for (size_t arg_num = 0; arg_num < arguments_size; ++arg_num) {
149
5.71k
        const ColumnWithTypeAndName& column = block.get_by_position(args[arg_num]);
150
        // Columns in const_list --> column_const,    others --> nested_column
151
        // that's because some functions supposes some specific columns always constant.
152
        // If we unpack it, there will be unnecessary cost of virtual judge.
153
5.71k
        if (args_expect_const.end() !=
154
5.71k
            std::find(args_expect_const.begin(), args_expect_const.end(), arg_num)) {
155
0
            temporary_block.insert({column.column, column.type, column.name});
156
5.71k
        } else {
157
5.71k
            temporary_block.insert(
158
5.71k
                    {assert_cast<const ColumnConst*>(column.column.get())->get_data_column_ptr(),
159
5.71k
                     column.type, column.name});
160
5.71k
        }
161
5.71k
    }
162
163
2.44k
    temporary_block.insert(block.get_by_position(result));
164
165
2.44k
    ColumnNumbers temporary_argument_numbers(arguments_size);
166
8.16k
    for (int i = 0; i < arguments_size; ++i) {
167
5.71k
        temporary_argument_numbers[i] = i;
168
5.71k
    }
169
170
2.44k
    RETURN_IF_ERROR(_execute_skipped_constant_deal(context, temporary_block,
171
2.44k
                                                   temporary_argument_numbers, arguments_size,
172
2.44k
                                                   temporary_block.rows(), dry_run));
173
174
2.44k
    ColumnPtr result_column;
175
    /// extremely rare case, when we have function with completely const arguments
176
    /// but some of them produced by non is_deterministic function
177
2.44k
    if (temporary_block.get_by_position(arguments_size).column->size() > 1) {
178
0
        result_column = temporary_block.get_by_position(arguments_size).column->clone_resized(1);
179
2.44k
    } else {
180
2.44k
        result_column = temporary_block.get_by_position(arguments_size).column;
181
2.44k
    }
182
    // We shuold handle the case where the result column is also a ColumnConst.
183
2.44k
    block.get_by_position(result).column = ColumnConst::create(result_column, input_rows_count);
184
2.44k
    *executed = true;
185
2.44k
    return Status::OK();
186
2.44k
}
187
188
Status PreparedFunctionImpl::default_implementation_for_nulls(
189
        FunctionContext* context, Block& block, const ColumnNumbers& args, uint32_t result,
190
105k
        size_t input_rows_count, bool dry_run, bool* executed) const {
191
105k
    *executed = false;
192
105k
    if (args.empty() || !use_default_implementation_for_nulls()) {
193
86.5k
        return Status::OK();
194
86.5k
    }
195
196
48.1k
    if (std::ranges::any_of(args, [&block](const auto& elem) {
197
48.1k
            return block.get_by_position(elem).column->only_null();
198
48.1k
        })) {
199
3.40k
        block.get_by_position(result).column =
200
3.40k
                block.get_by_position(result).type->create_column_const(input_rows_count, Field());
201
3.40k
        *executed = true;
202
3.40k
        return Status::OK();
203
3.40k
    }
204
205
16.0k
    if (have_null_column(block, args)) {
206
7.92k
        bool need_to_default = need_replace_null_data_to_default();
207
        // extract nested column from nulls
208
7.92k
        ColumnNumbers new_args;
209
20.9k
        for (auto arg : args) {
210
20.9k
            new_args.push_back(block.columns());
211
20.9k
            block.insert(block.get_by_position(arg).unnest_nullable(need_to_default));
212
20.9k
            DCHECK(!block.get_by_position(new_args.back()).column->is_nullable());
213
20.9k
        }
214
7.92k
        RETURN_IF_ERROR(execute_without_low_cardinality_columns(context, block, new_args, result,
215
7.92k
                                                                block.rows(), dry_run));
216
        // After run with nested, wrap them in null. Before this, block.get_by_position(result).type
217
        // is not compatible with get_by_position(result).column
218
7.92k
        block.get_by_position(result).column = wrap_in_nullable(
219
7.92k
                block.get_by_position(result).column, block, args, result, input_rows_count);
220
221
28.8k
        while (!new_args.empty()) {
222
20.9k
            block.erase(new_args.back());
223
20.9k
            new_args.pop_back();
224
20.9k
        }
225
7.92k
        *executed = true;
226
7.92k
        return Status::OK();
227
7.92k
    }
228
8.08k
    return Status::OK();
229
16.0k
}
230
231
Status PreparedFunctionImpl::execute_without_low_cardinality_columns(
232
        FunctionContext* context, Block& block, const ColumnNumbers& args, uint32_t result,
233
105k
        size_t input_rows_count, bool dry_run) const {
234
105k
    bool executed = false;
235
236
105k
    RETURN_IF_ERROR(default_implementation_for_constant_arguments(
237
105k
            context, block, args, result, input_rows_count, dry_run, &executed));
238
105k
    if (executed) {
239
2.44k
        return Status::OK();
240
2.44k
    }
241
242
103k
    return _execute_skipped_constant_deal(context, block, args, result, input_rows_count, dry_run);
243
105k
}
244
245
Status PreparedFunctionImpl::execute(FunctionContext* context, Block& block,
246
                                     const ColumnNumbers& args, uint32_t result,
247
98.0k
                                     size_t input_rows_count, bool dry_run) const {
248
98.0k
    return execute_without_low_cardinality_columns(context, block, args, result, input_rows_count,
249
98.0k
                                                   dry_run);
250
98.0k
}
251
252
12.6k
void FunctionBuilderImpl::check_number_of_arguments(size_t number_of_arguments) const {
253
12.6k
    if (is_variadic()) {
254
3.94k
        return;
255
3.94k
    }
256
257
8.70k
    size_t expected_number_of_arguments = get_number_of_arguments();
258
259
8.70k
    DCHECK_EQ(number_of_arguments, expected_number_of_arguments) << fmt::format(
260
0
            "Number of arguments for function {} doesn't match: passed {} , should be {}",
261
0
            get_name(), number_of_arguments, expected_number_of_arguments);
262
8.70k
    if (number_of_arguments != expected_number_of_arguments) {
263
0
        throw Exception(
264
0
                ErrorCode::INVALID_ARGUMENT,
265
0
                "Number of arguments for function {} doesn't match: passed {} , should be {}",
266
0
                get_name(), number_of_arguments, expected_number_of_arguments);
267
0
    }
268
8.70k
}
269
270
12.6k
DataTypePtr FunctionBuilderImpl::get_return_type(const ColumnsWithTypeAndName& arguments) const {
271
12.6k
    check_number_of_arguments(arguments.size());
272
273
12.6k
    if (!arguments.empty() && use_default_implementation_for_nulls()) {
274
11.5k
        if (have_null_column(arguments)) {
275
11.3k
            ColumnNumbers numbers(arguments.size());
276
11.3k
            std::iota(numbers.begin(), numbers.end(), 0);
277
11.3k
            auto [nested_block, _] =
278
11.3k
                    create_block_with_nested_columns(Block(arguments), numbers, false);
279
11.3k
            auto return_type = get_return_type_impl(
280
11.3k
                    ColumnsWithTypeAndName(nested_block.begin(), nested_block.end()));
281
11.3k
            return make_nullable(return_type);
282
11.3k
        }
283
11.5k
    }
284
285
1.29k
    return get_return_type_impl(arguments);
286
12.6k
}
287
288
bool FunctionBuilderImpl::is_date_or_datetime_or_decimal(
289
8
        const DataTypePtr& return_type, const DataTypePtr& func_return_type) const {
290
8
    return (is_date_or_datetime(return_type->get_primitive_type()) &&
291
8
            is_date_or_datetime(func_return_type->get_primitive_type())) ||
292
8
           (is_date_v2_or_datetime_v2(return_type->get_primitive_type()) &&
293
8
            is_date_v2_or_datetime_v2(func_return_type->get_primitive_type())) ||
294
           // For some date functions such as str_to_date(string, string), return_type will
295
           // be datetimev2 if users enable datev2 but get_return_type(arguments) will still
296
           // return datetime. We need keep backward compatibility here.
297
8
           (is_date_v2_or_datetime_v2(return_type->get_primitive_type()) &&
298
4
            is_date_or_datetime(func_return_type->get_primitive_type())) ||
299
8
           (is_date_or_datetime(return_type->get_primitive_type()) &&
300
4
            is_date_v2_or_datetime_v2(func_return_type->get_primitive_type())) ||
301
8
           (is_decimal(return_type->get_primitive_type()) &&
302
4
            is_decimal(func_return_type->get_primitive_type())) ||
303
8
           (is_time_type(return_type->get_primitive_type()) &&
304
2
            is_time_type(func_return_type->get_primitive_type()));
305
8
}
306
307
bool FunctionBuilderImpl::is_array_nested_type_date_or_datetime_or_decimal(
308
2
        const DataTypePtr& return_type, const DataTypePtr& func_return_type) const {
309
2
    auto return_type_ptr = return_type->is_nullable()
310
2
                                   ? ((DataTypeNullable*)return_type.get())->get_nested_type()
311
2
                                   : return_type;
312
2
    auto func_return_type_ptr =
313
2
            func_return_type->is_nullable()
314
2
                    ? ((DataTypeNullable*)func_return_type.get())->get_nested_type()
315
2
                    : func_return_type;
316
2
    if (!(return_type_ptr->get_primitive_type() == TYPE_ARRAY &&
317
2
          func_return_type_ptr->get_primitive_type() == TYPE_ARRAY)) {
318
2
        return false;
319
2
    }
320
0
    auto nested_nullable_return_type_ptr =
321
0
            (assert_cast<const DataTypeArray*>(return_type_ptr.get()))->get_nested_type();
322
0
    auto nested_nullable_func_return_type =
323
0
            (assert_cast<const DataTypeArray*>(func_return_type_ptr.get()))->get_nested_type();
324
    // There must be nullable inside array type.
325
0
    if (nested_nullable_return_type_ptr->is_nullable() &&
326
0
        nested_nullable_func_return_type->is_nullable()) {
327
0
        auto nested_return_type_ptr =
328
0
                ((DataTypeNullable*)(nested_nullable_return_type_ptr.get()))->get_nested_type();
329
0
        auto nested_func_return_type_ptr =
330
0
                ((DataTypeNullable*)(nested_nullable_func_return_type.get()))->get_nested_type();
331
0
        return is_date_or_datetime_or_decimal(nested_return_type_ptr, nested_func_return_type_ptr);
332
0
    }
333
0
    return false;
334
0
}
335
#include "common/compile_check_end.h"
336
} // namespace doris::vectorized