Coverage Report

Created: 2026-05-18 23:36

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