Coverage Report

Created: 2026-03-23 08:27

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/exprs/function/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 "exprs/function/function.h"
22
23
#include <algorithm>
24
#include <memory>
25
#include <numeric>
26
27
#include "common/status.h"
28
#include "core/assert_cast.h"
29
#include "core/column/column.h"
30
#include "core/column/column_const.h"
31
#include "core/column/column_nullable.h"
32
#include "core/column/column_vector.h"
33
#include "core/data_type/data_type_array.h"
34
#include "core/data_type/data_type_nothing.h"
35
#include "core/data_type/data_type_nullable.h"
36
#include "core/data_type/define_primitive_type.h"
37
#include "core/data_type/primitive_type.h"
38
#include "core/field.h"
39
#include "exec/common/util.hpp"
40
#include "exprs/aggregate/aggregate_function.h"
41
#include "exprs/function/function_helpers.h"
42
43
namespace doris {
44
#include "common/compile_check_begin.h"
45
ColumnPtr wrap_in_nullable(const ColumnPtr& src, const Block& block, const ColumnNumbers& args,
46
647k
                           size_t input_rows_count) {
47
647k
    ColumnPtr result_null_map_column;
48
    /// If result is already nullable.
49
647k
    ColumnPtr src_not_nullable = src;
50
647k
    MutableColumnPtr mutable_result_null_map_column;
51
52
647k
    if (auto nullable = check_and_get_column_ptr<ColumnNullable>(src)) {
53
174k
        src_not_nullable = nullable->get_nested_column_ptr();
54
174k
        result_null_map_column = nullable->get_null_map_column_ptr();
55
174k
    }
56
57
945k
    for (const auto& arg : args) {
58
945k
        const ColumnWithTypeAndName& elem = block.get_by_position(arg);
59
945k
        if (!elem.type->is_nullable() || is_column_const(*elem.column)) {
60
304k
            continue;
61
304k
        }
62
63
640k
        if (auto nullable = cast_to_column<ColumnNullable>(elem.column); nullable->has_null()) {
64
63.9k
            const ColumnPtr& null_map_column = nullable->get_null_map_column_ptr();
65
63.9k
            if (!result_null_map_column) { // NOLINT(bugprone-use-after-move)
66
36.5k
                result_null_map_column = null_map_column->clone_resized(input_rows_count);
67
36.5k
                continue;
68
36.5k
            }
69
70
27.3k
            if (!mutable_result_null_map_column) {
71
26.1k
                mutable_result_null_map_column =
72
26.1k
                        std::move(result_null_map_column)->assume_mutable();
73
26.1k
            }
74
75
27.3k
            NullMap& result_null_map =
76
27.3k
                    assert_cast<ColumnUInt8&>(*mutable_result_null_map_column).get_data();
77
27.3k
            const NullMap& src_null_map =
78
27.3k
                    assert_cast<const ColumnUInt8&>(*null_map_column).get_data();
79
80
27.3k
            VectorizedUtils::update_null_map(result_null_map, src_null_map);
81
27.3k
        }
82
640k
    }
83
84
647k
    if (!result_null_map_column) {
85
435k
        if (is_column_const(*src)) {
86
73
            return ColumnConst::create(
87
73
                    make_nullable(assert_cast<const ColumnConst&>(*src).get_data_column_ptr(),
88
73
                                  false),
89
73
                    input_rows_count);
90
73
        }
91
435k
        return ColumnNullable::create(src, ColumnUInt8::create(input_rows_count, 0));
92
435k
    }
93
94
211k
    return ColumnNullable::create(src_not_nullable, result_null_map_column);
95
647k
}
96
97
641k
bool have_null_column(const Block& block, const ColumnNumbers& args) {
98
1.03M
    return std::ranges::any_of(args, [&block](const auto& elem) {
99
1.03M
        return block.get_by_position(elem).type->is_nullable();
100
1.03M
    });
101
641k
}
102
103
681k
bool have_null_column(const ColumnsWithTypeAndName& args) {
104
1.19M
    return std::ranges::any_of(args, [](const auto& elem) { return elem.type->is_nullable(); });
105
681k
}
106
107
inline Status PreparedFunctionImpl::_execute_skipped_constant_deal(FunctionContext* context,
108
                                                                   Block& block,
109
                                                                   const ColumnNumbers& args,
110
                                                                   uint32_t result,
111
1.19M
                                                                   size_t input_rows_count) const {
112
1.19M
    bool executed = false;
113
1.19M
    RETURN_IF_ERROR(default_implementation_for_nulls(context, block, args, result, input_rows_count,
114
1.19M
                                                     &executed));
115
1.19M
    if (executed) {
116
280k
        return Status::OK();
117
280k
    }
118
915k
    return execute_impl(context, block, args, result, input_rows_count);
119
1.19M
}
120
121
Status PreparedFunctionImpl::default_implementation_for_constant_arguments(
122
        FunctionContext* context, Block& block, const ColumnNumbers& args, uint32_t result,
123
1.19M
        size_t input_rows_count, bool* executed) const {
124
1.19M
    *executed = false;
125
1.19M
    ColumnNumbers args_expect_const = get_arguments_that_are_always_constant();
126
127
    // Check that these arguments are really constant.
128
1.19M
    for (auto arg_num : args_expect_const) {
129
421k
        if (arg_num < args.size() &&
130
421k
            !is_column_const(*block.get_by_position(args[arg_num]).column)) {
131
9
            return Status::InvalidArgument("Argument at index {} for function {} must be constant",
132
9
                                           arg_num, get_name());
133
9
        }
134
421k
    }
135
136
1.19M
    if (args.empty() || !use_default_implementation_for_constants() ||
137
1.19M
        !VectorizedUtils::all_arguments_are_constant(block, args)) {
138
1.09M
        return Status::OK();
139
1.09M
    }
140
141
    // now all columns are const.
142
98.3k
    Block temporary_block;
143
144
98.3k
    int arguments_size = (int)args.size();
145
233k
    for (size_t arg_num = 0; arg_num < arguments_size; ++arg_num) {
146
135k
        const ColumnWithTypeAndName& column = block.get_by_position(args[arg_num]);
147
        // Columns in const_list --> column_const,    others --> nested_column
148
        // that's because some functions supposes some specific columns always constant.
149
        // If we unpack it, there will be unnecessary cost of virtual judge.
150
135k
        if (args_expect_const.end() !=
151
135k
            std::find(args_expect_const.begin(), args_expect_const.end(), arg_num)) {
152
549
            temporary_block.insert({column.column, column.type, column.name});
153
134k
        } else {
154
134k
            temporary_block.insert(
155
134k
                    {assert_cast<const ColumnConst*>(column.column.get())->get_data_column_ptr(),
156
134k
                     column.type, column.name});
157
134k
        }
158
135k
    }
159
160
98.3k
    temporary_block.insert(block.get_by_position(result));
161
162
98.3k
    ColumnNumbers temporary_argument_numbers(arguments_size);
163
233k
    for (int i = 0; i < arguments_size; ++i) {
164
135k
        temporary_argument_numbers[i] = i;
165
135k
    }
166
167
98.3k
    RETURN_IF_ERROR(_execute_skipped_constant_deal(context, temporary_block,
168
98.3k
                                                   temporary_argument_numbers, arguments_size,
169
98.3k
                                                   temporary_block.rows()));
170
171
97.3k
    ColumnPtr result_column;
172
    /// extremely rare case, when we have function with completely const arguments
173
    /// but some of them produced by non is_deterministic function
174
97.3k
    if (temporary_block.get_by_position(arguments_size).column->size() > 1) {
175
0
        result_column = temporary_block.get_by_position(arguments_size).column->clone_resized(1);
176
97.3k
    } else {
177
97.3k
        result_column = temporary_block.get_by_position(arguments_size).column;
178
97.3k
    }
179
    // We shuold handle the case where the result column is also a ColumnConst.
180
97.3k
    block.get_by_position(result).column = ColumnConst::create(result_column, input_rows_count);
181
97.3k
    *executed = true;
182
97.3k
    return Status::OK();
183
98.3k
}
184
185
Status PreparedFunctionImpl::default_implementation_for_nulls(
186
        FunctionContext* context, Block& block, const ColumnNumbers& args, uint32_t result,
187
1.19M
        size_t input_rows_count, bool* executed) const {
188
1.19M
    *executed = false;
189
1.19M
    if (args.empty() || !use_default_implementation_for_nulls()) {
190
540k
        return Status::OK();
191
540k
    }
192
193
1.33M
    if (std::ranges::any_of(args, [&block](const auto& elem) {
194
1.33M
            return block.get_by_position(elem).column->only_null();
195
1.33M
        })) {
196
13.9k
        block.get_by_position(result).column =
197
13.9k
                block.get_by_position(result).type->create_column_const(input_rows_count, Field());
198
13.9k
        *executed = true;
199
13.9k
        return Status::OK();
200
13.9k
    }
201
202
641k
    if (have_null_column(block, args)) {
203
266k
        bool need_to_default = need_replace_null_data_to_default();
204
        // extract nested column from nulls
205
266k
        ColumnNumbers new_args;
206
266k
        Block new_block;
207
208
820k
        for (int i = 0; i < args.size(); ++i) {
209
553k
            uint32_t arg = args[i];
210
553k
            new_args.push_back(i);
211
553k
            new_block.insert(block.get_by_position(arg).unnest_nullable(need_to_default));
212
553k
        }
213
266k
        new_block.insert(block.get_by_position(result));
214
266k
        int new_result = new_block.columns() - 1;
215
216
266k
        RETURN_IF_ERROR(default_execute(context, new_block, new_args, new_result, block.rows()));
217
        // After run with nested, wrap them in null. Before this, block.get_by_position(result).type
218
        // is not compatible with get_by_position(result).column
219
220
266k
        block.get_by_position(result).column = wrap_in_nullable(
221
266k
                new_block.get_by_position(new_result).column, block, args, input_rows_count);
222
223
266k
        *executed = true;
224
266k
        return Status::OK();
225
266k
    }
226
375k
    return Status::OK();
227
641k
}
228
229
Status PreparedFunctionImpl::default_execute(FunctionContext* context, Block& block,
230
                                             const ColumnNumbers& args, uint32_t result,
231
1.19M
                                             size_t input_rows_count) const {
232
1.19M
    bool executed = false;
233
234
1.19M
    RETURN_IF_ERROR(default_implementation_for_constant_arguments(context, block, args, result,
235
1.19M
                                                                  input_rows_count, &executed));
236
1.19M
    if (executed) {
237
97.2k
        return Status::OK();
238
97.2k
    }
239
240
1.09M
    return _execute_skipped_constant_deal(context, block, args, result, input_rows_count);
241
1.19M
}
242
243
Status PreparedFunctionImpl::execute(FunctionContext* context, Block& block,
244
                                     const ColumnNumbers& args, uint32_t result,
245
929k
                                     size_t input_rows_count) const {
246
929k
    return default_execute(context, block, args, result, input_rows_count);
247
929k
}
248
249
771k
void FunctionBuilderImpl::check_number_of_arguments(size_t number_of_arguments) const {
250
771k
    if (is_variadic()) {
251
83.3k
        return;
252
83.3k
    }
253
254
688k
    size_t expected_number_of_arguments = get_number_of_arguments();
255
256
688k
    DCHECK_EQ(number_of_arguments, expected_number_of_arguments) << fmt::format(
257
0
            "Number of arguments for function {} doesn't match: passed {} , should be {}",
258
0
            get_name(), number_of_arguments, expected_number_of_arguments);
259
688k
    if (number_of_arguments != expected_number_of_arguments) {
260
0
        throw Exception(
261
0
                ErrorCode::INVALID_ARGUMENT,
262
0
                "Number of arguments for function {} doesn't match: passed {} , should be {}",
263
0
                get_name(), number_of_arguments, expected_number_of_arguments);
264
0
    }
265
688k
}
266
267
775k
DataTypePtr FunctionBuilderImpl::get_return_type(const ColumnsWithTypeAndName& arguments) const {
268
775k
    check_number_of_arguments(arguments.size());
269
270
775k
    if (!arguments.empty() && use_default_implementation_for_nulls()) {
271
681k
        if (have_null_column(arguments)) {
272
163k
            ColumnNumbers numbers(arguments.size());
273
163k
            std::iota(numbers.begin(), numbers.end(), 0);
274
163k
            auto [nested_block, _] =
275
163k
                    create_block_with_nested_columns(Block(arguments), numbers, false);
276
163k
            auto return_type = get_return_type_impl(
277
163k
                    ColumnsWithTypeAndName(nested_block.begin(), nested_block.end()));
278
163k
            if (!return_type) {
279
0
                return nullptr;
280
0
            }
281
163k
            return make_nullable(return_type);
282
163k
        }
283
681k
    }
284
285
611k
    return get_return_type_impl(arguments);
286
775k
}
287
288
bool FunctionBuilderImpl::is_date_or_datetime_or_decimal(
289
2.93k
        const DataTypePtr& return_type, const DataTypePtr& func_return_type) const {
290
2.93k
    return (is_date_or_datetime(return_type->get_primitive_type()) &&
291
2.93k
            is_date_or_datetime(func_return_type->get_primitive_type())) ||
292
2.93k
           (is_date_v2_or_datetime_v2(return_type->get_primitive_type()) &&
293
2.93k
            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
2.93k
           (is_date_v2_or_datetime_v2(return_type->get_primitive_type()) &&
298
2.01k
            is_date_or_datetime(func_return_type->get_primitive_type())) ||
299
2.93k
           (is_date_or_datetime(return_type->get_primitive_type()) &&
300
1.98k
            is_date_v2_or_datetime_v2(func_return_type->get_primitive_type())) ||
301
2.93k
           (is_decimal(return_type->get_primitive_type()) &&
302
1.98k
            is_decimal(func_return_type->get_primitive_type())) ||
303
2.93k
           (is_time_type(return_type->get_primitive_type()) &&
304
498
            is_time_type(func_return_type->get_primitive_type()));
305
2.93k
}
306
307
575
bool contains_date_or_datetime_or_decimal(const DataTypePtr& type) {
308
575
    auto type_ptr = type->is_nullable() ? ((DataTypeNullable*)type.get())->get_nested_type() : type;
309
310
575
    switch (type_ptr->get_primitive_type()) {
311
16
    case TYPE_ARRAY: {
312
16
        const auto* array_type = assert_cast<const DataTypeArray*>(type_ptr.get());
313
16
        return contains_date_or_datetime_or_decimal(array_type->get_nested_type());
314
0
    }
315
0
    case TYPE_MAP: {
316
0
        const auto* map_type = assert_cast<const DataTypeMap*>(type_ptr.get());
317
0
        return contains_date_or_datetime_or_decimal(map_type->get_key_type()) ||
318
0
               contains_date_or_datetime_or_decimal(map_type->get_value_type());
319
0
    }
320
33
    case TYPE_STRUCT: {
321
33
        const auto* struct_type = assert_cast<const DataTypeStruct*>(type_ptr.get());
322
33
        const auto& elements = struct_type->get_elements();
323
71
        return std::ranges::any_of(elements, [](const DataTypePtr& element) {
324
71
            return contains_date_or_datetime_or_decimal(element);
325
71
        });
326
0
    }
327
526
    default:
328
        // For scalar types, check if it's date/datetime/decimal
329
526
        return is_date_or_datetime(type_ptr->get_primitive_type()) ||
330
526
               is_date_v2_or_datetime_v2(type_ptr->get_primitive_type()) ||
331
526
               is_decimal(type_ptr->get_primitive_type()) ||
332
526
               is_time_type(type_ptr->get_primitive_type());
333
575
    }
334
575
}
335
336
// make sure array/map/struct and nested  array/map/struct can be check
337
bool FunctionBuilderImpl::is_nested_type_date_or_datetime_or_decimal(
338
490
        const DataTypePtr& return_type, const DataTypePtr& func_return_type) const {
339
490
    auto return_type_ptr = return_type->is_nullable()
340
490
                                   ? ((DataTypeNullable*)return_type.get())->get_nested_type()
341
490
                                   : return_type;
342
490
    auto func_return_type_ptr =
343
490
            func_return_type->is_nullable()
344
490
                    ? ((DataTypeNullable*)func_return_type.get())->get_nested_type()
345
490
                    : func_return_type;
346
    // make sure that map/struct/array also need to check
347
490
    if (return_type_ptr->get_primitive_type() != func_return_type_ptr->get_primitive_type()) {
348
2
        return false;
349
2
    }
350
351
    // Check if this type contains date/datetime/decimal types
352
488
    if (!contains_date_or_datetime_or_decimal(return_type_ptr)) {
353
        // If no date/datetime/decimal types, just pass through
354
454
        return true;
355
454
    }
356
357
    // If contains date/datetime/decimal types, recursively check each element
358
34
    switch (return_type_ptr->get_primitive_type()) {
359
16
    case TYPE_ARRAY: {
360
16
        auto nested_return_type = remove_nullable(
361
16
                (assert_cast<const DataTypeArray*>(return_type_ptr.get()))->get_nested_type());
362
16
        auto nested_func_type = remove_nullable(
363
16
                (assert_cast<const DataTypeArray*>(func_return_type_ptr.get()))->get_nested_type());
364
16
        return is_nested_type_date_or_datetime_or_decimal(nested_return_type, nested_func_type);
365
0
    }
366
0
    case TYPE_MAP: {
367
0
        const auto* return_map = assert_cast<const DataTypeMap*>(return_type_ptr.get());
368
0
        const auto* func_map = assert_cast<const DataTypeMap*>(func_return_type_ptr.get());
369
370
0
        auto key_return = remove_nullable(return_map->get_key_type());
371
0
        auto key_func = remove_nullable(func_map->get_key_type());
372
0
        auto value_return = remove_nullable(return_map->get_value_type());
373
0
        auto value_func = remove_nullable(func_map->get_value_type());
374
375
0
        return is_nested_type_date_or_datetime_or_decimal(key_return, key_func) &&
376
0
               is_nested_type_date_or_datetime_or_decimal(value_return, value_func);
377
0
    }
378
1
    case TYPE_STRUCT: {
379
1
        const auto* return_struct = assert_cast<const DataTypeStruct*>(return_type_ptr.get());
380
1
        const auto* func_struct = assert_cast<const DataTypeStruct*>(func_return_type_ptr.get());
381
382
1
        auto return_elements = return_struct->get_elements();
383
1
        auto func_elements = func_struct->get_elements();
384
385
1
        if (return_elements.size() != func_elements.size()) {
386
0
            return false;
387
0
        }
388
389
5
        for (size_t i = 0; i < return_elements.size(); i++) {
390
4
            auto elem_return = remove_nullable(return_elements[i]);
391
4
            auto elem_func = remove_nullable(func_elements[i]);
392
393
4
            if (!is_nested_type_date_or_datetime_or_decimal(elem_return, elem_func)) {
394
0
                return false;
395
0
            }
396
4
        }
397
1
        return true;
398
1
    }
399
17
    default:
400
17
        return is_date_or_datetime_or_decimal(return_type_ptr, func_return_type_ptr);
401
34
    }
402
34
}
403
404
#include "common/compile_check_end.h"
405
} // namespace doris