Coverage Report

Created: 2026-03-19 14:47

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
476k
                           size_t input_rows_count) {
47
476k
    ColumnPtr result_null_map_column;
48
    /// If result is already nullable.
49
476k
    ColumnPtr src_not_nullable = src;
50
476k
    MutableColumnPtr mutable_result_null_map_column;
51
52
476k
    if (auto nullable = check_and_get_column_ptr<ColumnNullable>(src)) {
53
158k
        src_not_nullable = nullable->get_nested_column_ptr();
54
158k
        result_null_map_column = nullable->get_null_map_column_ptr();
55
158k
    }
56
57
643k
    for (const auto& arg : args) {
58
643k
        const ColumnWithTypeAndName& elem = block.get_by_position(arg);
59
643k
        if (!elem.type->is_nullable() || is_column_const(*elem.column)) {
60
180k
            continue;
61
180k
        }
62
63
462k
        if (auto nullable = cast_to_column<ColumnNullable>(elem.column); nullable->has_null()) {
64
56.0k
            const ColumnPtr& null_map_column = nullable->get_null_map_column_ptr();
65
56.0k
            if (!result_null_map_column) { // NOLINT(bugprone-use-after-move)
66
29.0k
                result_null_map_column = null_map_column->clone_resized(input_rows_count);
67
29.0k
                continue;
68
29.0k
            }
69
70
27.0k
            if (!mutable_result_null_map_column) {
71
25.7k
                mutable_result_null_map_column =
72
25.7k
                        std::move(result_null_map_column)->assume_mutable();
73
25.7k
            }
74
75
27.0k
            NullMap& result_null_map =
76
27.0k
                    assert_cast<ColumnUInt8&>(*mutable_result_null_map_column).get_data();
77
27.0k
            const NullMap& src_null_map =
78
27.0k
                    assert_cast<const ColumnUInt8&>(*null_map_column).get_data();
79
80
27.0k
            VectorizedUtils::update_null_map(result_null_map, src_null_map);
81
27.0k
        }
82
462k
    }
83
84
476k
    if (!result_null_map_column) {
85
288k
        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
288k
        return ColumnNullable::create(src, ColumnUInt8::create(input_rows_count, 0));
92
288k
    }
93
94
188k
    return ColumnNullable::create(src_not_nullable, result_null_map_column);
95
476k
}
96
97
356k
bool have_null_column(const Block& block, const ColumnNumbers& args) {
98
604k
    return std::ranges::any_of(args, [&block](const auto& elem) {
99
604k
        return block.get_by_position(elem).type->is_nullable();
100
604k
    });
101
356k
}
102
103
487k
bool have_null_column(const ColumnsWithTypeAndName& args) {
104
829k
    return std::ranges::any_of(args, [](const auto& elem) { return elem.type->is_nullable(); });
105
487k
}
106
107
inline Status PreparedFunctionImpl::_execute_skipped_constant_deal(FunctionContext* context,
108
                                                                   Block& block,
109
                                                                   const ColumnNumbers& args,
110
                                                                   uint32_t result,
111
834k
                                                                   size_t input_rows_count) const {
112
834k
    bool executed = false;
113
834k
    RETURN_IF_ERROR(default_implementation_for_nulls(context, block, args, result, input_rows_count,
114
834k
                                                     &executed));
115
834k
    if (executed) {
116
140k
        return Status::OK();
117
140k
    }
118
694k
    return execute_impl(context, block, args, result, input_rows_count);
119
834k
}
120
121
Status PreparedFunctionImpl::default_implementation_for_constant_arguments(
122
        FunctionContext* context, Block& block, const ColumnNumbers& args, uint32_t result,
123
835k
        size_t input_rows_count, bool* executed) const {
124
835k
    *executed = false;
125
835k
    ColumnNumbers args_expect_const = get_arguments_that_are_always_constant();
126
127
    // Check that these arguments are really constant.
128
835k
    for (auto arg_num : args_expect_const) {
129
381k
        if (arg_num < args.size() &&
130
381k
            !is_column_const(*block.get_by_position(args[arg_num]).column)) {
131
5
            return Status::InvalidArgument("Argument at index {} for function {} must be constant",
132
5
                                           arg_num, get_name());
133
5
        }
134
381k
    }
135
136
835k
    if (args.empty() || !use_default_implementation_for_constants() ||
137
835k
        !VectorizedUtils::all_arguments_are_constant(block, args)) {
138
747k
        return Status::OK();
139
747k
    }
140
141
    // now all columns are const.
142
87.8k
    Block temporary_block;
143
144
87.8k
    int arguments_size = (int)args.size();
145
201k
    for (size_t arg_num = 0; arg_num < arguments_size; ++arg_num) {
146
113k
        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
113k
        if (args_expect_const.end() !=
151
113k
            std::find(args_expect_const.begin(), args_expect_const.end(), arg_num)) {
152
329
            temporary_block.insert({column.column, column.type, column.name});
153
113k
        } else {
154
113k
            temporary_block.insert(
155
113k
                    {assert_cast<const ColumnConst*>(column.column.get())->get_data_column_ptr(),
156
113k
                     column.type, column.name});
157
113k
        }
158
113k
    }
159
160
87.8k
    temporary_block.insert(block.get_by_position(result));
161
162
87.8k
    ColumnNumbers temporary_argument_numbers(arguments_size);
163
201k
    for (int i = 0; i < arguments_size; ++i) {
164
113k
        temporary_argument_numbers[i] = i;
165
113k
    }
166
167
87.8k
    RETURN_IF_ERROR(_execute_skipped_constant_deal(context, temporary_block,
168
87.8k
                                                   temporary_argument_numbers, arguments_size,
169
87.8k
                                                   temporary_block.rows()));
170
171
86.7k
    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
86.7k
    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
86.7k
    } else {
177
86.7k
        result_column = temporary_block.get_by_position(arguments_size).column;
178
86.7k
    }
179
    // We shuold handle the case where the result column is also a ColumnConst.
180
86.7k
    block.get_by_position(result).column = ColumnConst::create(result_column, input_rows_count);
181
86.7k
    *executed = true;
182
86.7k
    return Status::OK();
183
87.8k
}
184
185
Status PreparedFunctionImpl::default_implementation_for_nulls(
186
        FunctionContext* context, Block& block, const ColumnNumbers& args, uint32_t result,
187
835k
        size_t input_rows_count, bool* executed) const {
188
835k
    *executed = false;
189
835k
    if (args.empty() || !use_default_implementation_for_nulls()) {
190
466k
        return Status::OK();
191
466k
    }
192
193
771k
    if (std::ranges::any_of(args, [&block](const auto& elem) {
194
771k
            return block.get_by_position(elem).column->only_null();
195
771k
        })) {
196
11.9k
        block.get_by_position(result).column =
197
11.9k
                block.get_by_position(result).type->create_column_const(input_rows_count, Field());
198
11.9k
        *executed = true;
199
11.9k
        return Status::OK();
200
11.9k
    }
201
202
356k
    if (have_null_column(block, args)) {
203
128k
        bool need_to_default = need_replace_null_data_to_default();
204
        // extract nested column from nulls
205
128k
        ColumnNumbers new_args;
206
128k
        Block new_block;
207
208
411k
        for (int i = 0; i < args.size(); ++i) {
209
283k
            uint32_t arg = args[i];
210
283k
            new_args.push_back(i);
211
283k
            new_block.insert(block.get_by_position(arg).unnest_nullable(need_to_default));
212
283k
        }
213
128k
        new_block.insert(block.get_by_position(result));
214
128k
        int new_result = new_block.columns() - 1;
215
216
128k
        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
128k
        block.get_by_position(result).column = wrap_in_nullable(
221
128k
                new_block.get_by_position(new_result).column, block, args, input_rows_count);
222
223
128k
        *executed = true;
224
128k
        return Status::OK();
225
128k
    }
226
227k
    return Status::OK();
227
356k
}
228
229
Status PreparedFunctionImpl::default_execute(FunctionContext* context, Block& block,
230
                                             const ColumnNumbers& args, uint32_t result,
231
834k
                                             size_t input_rows_count) const {
232
834k
    bool executed = false;
233
234
834k
    RETURN_IF_ERROR(default_implementation_for_constant_arguments(context, block, args, result,
235
834k
                                                                  input_rows_count, &executed));
236
833k
    if (executed) {
237
86.9k
        return Status::OK();
238
86.9k
    }
239
240
746k
    return _execute_skipped_constant_deal(context, block, args, result, input_rows_count);
241
833k
}
242
243
Status PreparedFunctionImpl::execute(FunctionContext* context, Block& block,
244
                                     const ColumnNumbers& args, uint32_t result,
245
706k
                                     size_t input_rows_count) const {
246
706k
    return default_execute(context, block, args, result, input_rows_count);
247
706k
}
248
249
565k
void FunctionBuilderImpl::check_number_of_arguments(size_t number_of_arguments) const {
250
565k
    if (is_variadic()) {
251
73.4k
        return;
252
73.4k
    }
253
254
491k
    size_t expected_number_of_arguments = get_number_of_arguments();
255
256
491k
    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
491k
    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
491k
}
266
267
566k
DataTypePtr FunctionBuilderImpl::get_return_type(const ColumnsWithTypeAndName& arguments) const {
268
566k
    check_number_of_arguments(arguments.size());
269
270
566k
    if (!arguments.empty() && use_default_implementation_for_nulls()) {
271
486k
        if (have_null_column(arguments)) {
272
142k
            ColumnNumbers numbers(arguments.size());
273
142k
            std::iota(numbers.begin(), numbers.end(), 0);
274
142k
            auto [nested_block, _] =
275
142k
                    create_block_with_nested_columns(Block(arguments), numbers, false);
276
142k
            auto return_type = get_return_type_impl(
277
142k
                    ColumnsWithTypeAndName(nested_block.begin(), nested_block.end()));
278
142k
            if (!return_type) {
279
0
                return nullptr;
280
0
            }
281
142k
            return make_nullable(return_type);
282
142k
        }
283
486k
    }
284
285
423k
    return get_return_type_impl(arguments);
286
566k
}
287
288
bool FunctionBuilderImpl::is_date_or_datetime_or_decimal(
289
2.53k
        const DataTypePtr& return_type, const DataTypePtr& func_return_type) const {
290
2.53k
    return (is_date_or_datetime(return_type->get_primitive_type()) &&
291
2.53k
            is_date_or_datetime(func_return_type->get_primitive_type())) ||
292
2.53k
           (is_date_v2_or_datetime_v2(return_type->get_primitive_type()) &&
293
2.53k
            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.53k
           (is_date_v2_or_datetime_v2(return_type->get_primitive_type()) &&
298
1.61k
            is_date_or_datetime(func_return_type->get_primitive_type())) ||
299
2.53k
           (is_date_or_datetime(return_type->get_primitive_type()) &&
300
1.58k
            is_date_v2_or_datetime_v2(func_return_type->get_primitive_type())) ||
301
2.53k
           (is_decimal(return_type->get_primitive_type()) &&
302
1.58k
            is_decimal(func_return_type->get_primitive_type())) ||
303
2.53k
           (is_time_type(return_type->get_primitive_type()) &&
304
498
            is_time_type(func_return_type->get_primitive_type()));
305
2.53k
}
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