Coverage Report

Created: 2025-06-16 14:03

/root/doris/be/src/vec/exprs/vexpr.cpp
Line
Count
Source (jump to first uncovered line)
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 "vec/exprs/vexpr.h"
19
20
#include <fmt/format.h>
21
#include <gen_cpp/Exprs_types.h>
22
#include <gen_cpp/FrontendService_types.h>
23
#include <thrift/protocol/TDebugProtocol.h>
24
25
#include <algorithm>
26
#include <boost/algorithm/string/split.hpp>
27
#include <boost/iterator/iterator_facade.hpp>
28
#include <cstdint>
29
#include <memory>
30
#include <stack>
31
#include <utility>
32
33
#include "common/config.h"
34
#include "common/exception.h"
35
#include "common/status.h"
36
#include "pipeline/pipeline_task.h"
37
#include "runtime/define_primitive_type.h"
38
#include "vec/columns/column_vector.h"
39
#include "vec/data_types/data_type_array.h"
40
#include "vec/data_types/data_type_factory.hpp"
41
#include "vec/data_types/data_type_nullable.h"
42
#include "vec/data_types/data_type_number.h"
43
#include "vec/exprs/varray_literal.h"
44
#include "vec/exprs/vcase_expr.h"
45
#include "vec/exprs/vcast_expr.h"
46
#include "vec/exprs/vcolumn_ref.h"
47
#include "vec/exprs/vcompound_pred.h"
48
#include "vec/exprs/vectorized_fn_call.h"
49
#include "vec/exprs/vexpr_context.h"
50
#include "vec/exprs/vin_predicate.h"
51
#include "vec/exprs/vinfo_func.h"
52
#include "vec/exprs/vlambda_function_call_expr.h"
53
#include "vec/exprs/vlambda_function_expr.h"
54
#include "vec/exprs/vliteral.h"
55
#include "vec/exprs/vmap_literal.h"
56
#include "vec/exprs/vmatch_predicate.h"
57
#include "vec/exprs/vslot_ref.h"
58
#include "vec/exprs/vstruct_literal.h"
59
#include "vec/exprs/vtuple_is_null_predicate.h"
60
#include "vec/utils/util.hpp"
61
62
namespace doris {
63
#include "common/compile_check_begin.h"
64
65
class RowDescriptor;
66
class RuntimeState;
67
68
// NOLINTBEGIN(readability-function-cognitive-complexity)
69
// NOLINTBEGIN(readability-function-size)
70
TExprNode create_texpr_node_from(const void* data, const PrimitiveType& type, int precision,
71
5
                                 int scale) {
72
5
    TExprNode node;
73
74
5
    switch (type) {
75
0
    case TYPE_BOOLEAN: {
76
0
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_BOOLEAN>(data, &node));
77
0
        break;
78
0
    }
79
0
    case TYPE_TINYINT: {
80
0
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_TINYINT>(data, &node));
81
0
        break;
82
0
    }
83
0
    case TYPE_SMALLINT: {
84
0
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_SMALLINT>(data, &node));
85
0
        break;
86
0
    }
87
5
    case TYPE_INT: {
88
5
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_INT>(data, &node));
89
5
        break;
90
5
    }
91
5
    case TYPE_BIGINT: {
92
0
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_BIGINT>(data, &node));
93
0
        break;
94
0
    }
95
0
    case TYPE_LARGEINT: {
96
0
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_LARGEINT>(data, &node));
97
0
        break;
98
0
    }
99
0
    case TYPE_FLOAT: {
100
0
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_FLOAT>(data, &node));
101
0
        break;
102
0
    }
103
0
    case TYPE_DOUBLE: {
104
0
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_DOUBLE>(data, &node));
105
0
        break;
106
0
    }
107
0
    case TYPE_DATEV2: {
108
0
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_DATEV2>(data, &node));
109
0
        break;
110
0
    }
111
0
    case TYPE_DATETIMEV2: {
112
0
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_DATETIMEV2>(data, &node, precision, scale));
113
0
        break;
114
0
    }
115
0
    case TYPE_DATE: {
116
0
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_DATE>(data, &node));
117
0
        break;
118
0
    }
119
0
    case TYPE_DATETIME: {
120
0
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_DATETIME>(data, &node));
121
0
        break;
122
0
    }
123
0
    case TYPE_DECIMALV2: {
124
0
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_DECIMALV2>(data, &node, precision, scale));
125
0
        break;
126
0
    }
127
0
    case TYPE_DECIMAL32: {
128
0
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_DECIMAL32>(data, &node, precision, scale));
129
0
        break;
130
0
    }
131
0
    case TYPE_DECIMAL64: {
132
0
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_DECIMAL64>(data, &node, precision, scale));
133
0
        break;
134
0
    }
135
0
    case TYPE_DECIMAL128I: {
136
0
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_DECIMAL128I>(data, &node, precision, scale));
137
0
        break;
138
0
    }
139
0
    case TYPE_DECIMAL256: {
140
0
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_DECIMAL256>(data, &node, precision, scale));
141
0
        break;
142
0
    }
143
0
    case TYPE_CHAR: {
144
0
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_CHAR>(data, &node));
145
0
        break;
146
0
    }
147
0
    case TYPE_VARCHAR: {
148
0
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_VARCHAR>(data, &node));
149
0
        break;
150
0
    }
151
0
    case TYPE_STRING: {
152
0
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_STRING>(data, &node));
153
0
        break;
154
0
    }
155
0
    case TYPE_IPV4: {
156
0
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_IPV4>(data, &node));
157
0
        break;
158
0
    }
159
0
    case TYPE_IPV6: {
160
0
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_IPV6>(data, &node));
161
0
        break;
162
0
    }
163
0
    case TYPE_TIMEV2: {
164
0
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_TIMEV2>(data, &node));
165
0
        break;
166
0
    }
167
0
    default:
168
0
        throw Exception(ErrorCode::INTERNAL_ERROR, "runtime filter meet invalid type {}",
169
0
                        int(type));
170
5
    }
171
5
    return node;
172
5
}
173
// NOLINTEND(readability-function-size)
174
// NOLINTEND(readability-function-cognitive-complexity)
175
} // namespace doris
176
177
namespace doris::vectorized {
178
179
0
bool VExpr::is_acting_on_a_slot(const VExpr& expr) {
180
0
    const auto& children = expr.children();
181
182
0
    auto is_a_slot = std::any_of(children.begin(), children.end(),
183
0
                                 [](const auto& child) { return is_acting_on_a_slot(*child); });
184
185
0
    return is_a_slot ? true : (expr.node_type() == TExprNodeType::SLOT_REF);
186
0
}
187
188
VExpr::VExpr(const TExprNode& node)
189
        : _node_type(node.node_type),
190
433k
          _opcode(node.__isset.opcode ? node.opcode : TExprOpcode::INVALID_OPCODE) {
191
433k
    if (node.__isset.fn) {
192
55
        _fn = node.fn;
193
55
    }
194
195
433k
    bool is_nullable = true;
196
433k
    if (node.__isset.is_nullable) {
197
429k
        is_nullable = node.is_nullable;
198
429k
    }
199
    // If we define null literal ,should make nullable data type to get correct field instead of undefined ptr
200
433k
    if (node.node_type == TExprNodeType::NULL_LITERAL) {
201
1
        CHECK(is_nullable);
202
1
    }
203
433k
    _data_type = get_data_type_with_default_argument(
204
433k
            DataTypeFactory::instance().create_data_type(node.type, is_nullable));
205
433k
}
206
207
0
VExpr::VExpr(const VExpr& vexpr) = default;
208
209
VExpr::VExpr(DataTypePtr type, bool is_slotref)
210
        : _opcode(TExprOpcode::INVALID_OPCODE),
211
0
          _data_type(get_data_type_with_default_argument(type)) {
212
0
    if (is_slotref) {
213
0
        _node_type = TExprNodeType::SLOT_REF;
214
0
    }
215
0
}
216
217
279k
Status VExpr::prepare(RuntimeState* state, const RowDescriptor& row_desc, VExprContext* context) {
218
279k
    ++context->_depth_num;
219
279k
    if (context->_depth_num > config::max_depth_of_expr_tree) {
220
0
        return Status::Error<ErrorCode::EXCEEDED_LIMIT>(
221
0
                "The depth of the expression tree is too big, make it less than {}",
222
0
                config::max_depth_of_expr_tree);
223
0
    }
224
225
279k
    for (auto& i : _children) {
226
134
        RETURN_IF_ERROR(i->prepare(state, row_desc, context));
227
134
    }
228
279k
    --context->_depth_num;
229
279k
    _enable_inverted_index_query = state->query_options().enable_inverted_index_query;
230
279k
    return Status::OK();
231
279k
}
232
233
Status VExpr::open(RuntimeState* state, VExprContext* context,
234
555k
                   FunctionContext::FunctionStateScope scope) {
235
555k
    for (auto& i : _children) {
236
2
        RETURN_IF_ERROR(i->open(state, context, scope));
237
2
    }
238
555k
    if (scope == FunctionContext::FRAGMENT_LOCAL) {
239
279k
        RETURN_IF_ERROR(VExpr::get_const_col(context, nullptr));
240
279k
    }
241
555k
    return Status::OK();
242
555k
}
243
244
556k
void VExpr::close(VExprContext* context, FunctionContext::FunctionStateScope scope) {
245
556k
    for (auto& i : _children) {
246
76
        i->close(context, scope);
247
76
    }
248
556k
}
249
250
// NOLINTBEGIN(readability-function-size)
251
433k
Status VExpr::create_expr(const TExprNode& expr_node, VExprSPtr& expr) {
252
433k
    try {
253
433k
        switch (expr_node.node_type) {
254
0
        case TExprNodeType::BOOL_LITERAL:
255
33
        case TExprNodeType::INT_LITERAL:
256
33
        case TExprNodeType::LARGE_INT_LITERAL:
257
34
        case TExprNodeType::IPV4_LITERAL:
258
34
        case TExprNodeType::IPV6_LITERAL:
259
35
        case TExprNodeType::FLOAT_LITERAL:
260
36
        case TExprNodeType::DECIMAL_LITERAL:
261
39
        case TExprNodeType::DATE_LITERAL:
262
39
        case TExprNodeType::TIMEV2_LITERAL:
263
45
        case TExprNodeType::STRING_LITERAL:
264
45
        case TExprNodeType::JSON_LITERAL:
265
46
        case TExprNodeType::NULL_LITERAL: {
266
46
            expr = VLiteral::create_shared(expr_node);
267
46
            break;
268
45
        }
269
0
        case TExprNodeType::ARRAY_LITERAL: {
270
0
            expr = VArrayLiteral::create_shared(expr_node);
271
0
            break;
272
45
        }
273
0
        case TExprNodeType::MAP_LITERAL: {
274
0
            expr = VMapLiteral::create_shared(expr_node);
275
0
            break;
276
45
        }
277
0
        case TExprNodeType::STRUCT_LITERAL: {
278
0
            expr = VStructLiteral::create_shared(expr_node);
279
0
            break;
280
45
        }
281
433k
        case TExprNodeType::SLOT_REF: {
282
433k
            expr = VSlotRef::create_shared(expr_node);
283
433k
            break;
284
45
        }
285
0
        case TExprNodeType::COLUMN_REF: {
286
0
            expr = VColumnRef::create_shared(expr_node);
287
0
            break;
288
45
        }
289
17
        case TExprNodeType::COMPOUND_PRED: {
290
17
            expr = VCompoundPred::create_shared(expr_node);
291
17
            break;
292
45
        }
293
0
        case TExprNodeType::LAMBDA_FUNCTION_EXPR: {
294
0
            expr = VLambdaFunctionExpr::create_shared(expr_node);
295
0
            break;
296
45
        }
297
0
        case TExprNodeType::LAMBDA_FUNCTION_CALL_EXPR: {
298
0
            expr = VLambdaFunctionCallExpr::create_shared(expr_node);
299
0
            break;
300
45
        }
301
1
        case TExprNodeType::ARITHMETIC_EXPR:
302
40
        case TExprNodeType::BINARY_PRED:
303
41
        case TExprNodeType::NULL_AWARE_BINARY_PRED:
304
49
        case TExprNodeType::FUNCTION_CALL:
305
49
        case TExprNodeType::COMPUTE_FUNCTION_CALL: {
306
49
            expr = VectorizedFnCall::create_shared(expr_node);
307
49
            break;
308
49
        }
309
0
        case TExprNodeType::MATCH_PRED: {
310
0
            expr = VMatchPredicate::create_shared(expr_node);
311
0
            break;
312
49
        }
313
2
        case TExprNodeType::CAST_EXPR: {
314
2
            expr = VCastExpr::create_shared(expr_node);
315
2
            break;
316
49
        }
317
5
        case TExprNodeType::IN_PRED: {
318
5
            expr = VInPredicate::create_shared(expr_node);
319
5
            break;
320
49
        }
321
0
        case TExprNodeType::CASE_EXPR: {
322
0
            if (!expr_node.__isset.case_expr) {
323
0
                return Status::InternalError("Case expression not set in thrift node");
324
0
            }
325
0
            expr = VCaseExpr::create_shared(expr_node);
326
0
            break;
327
0
        }
328
0
        case TExprNodeType::INFO_FUNC: {
329
0
            expr = VInfoFunc::create_shared(expr_node);
330
0
            break;
331
0
        }
332
0
        case TExprNodeType::TUPLE_IS_NULL_PRED: {
333
0
            expr = VTupleIsNullPredicate::create_shared(expr_node);
334
0
            break;
335
0
        }
336
0
        default:
337
0
            return Status::InternalError("Unknown expr node type: {}", expr_node.node_type);
338
433k
        }
339
433k
    } catch (const Exception& e) {
340
0
        if (e.code() == ErrorCode::INTERNAL_ERROR) {
341
0
            return Status::InternalError("Create Expr failed because {}\nTExprNode={}", e.what(),
342
0
                                         apache::thrift::ThriftDebugString(expr_node));
343
0
        }
344
0
        return Status::Error<false>(e.code(), "Create Expr failed because {}", e.what());
345
0
        LOG(WARNING) << "create expr failed, TExprNode={}, reason={}"
346
0
                     << apache::thrift::ThriftDebugString(expr_node) << e.what();
347
0
    }
348
433k
    if (!expr->data_type()) {
349
0
        return Status::InvalidArgument("Unknown expr type: {}", expr_node.node_type);
350
0
    }
351
433k
    return Status::OK();
352
433k
}
353
// NOLINTEND(readability-function-size)
354
355
Status VExpr::create_tree_from_thrift(const std::vector<TExprNode>& nodes, int* node_idx,
356
433k
                                      VExprSPtr& root_expr, VExprContextSPtr& ctx) {
357
    // propagate error case
358
433k
    if (*node_idx >= nodes.size()) {
359
0
        return Status::InternalError("Failed to reconstruct expression tree from thrift.");
360
0
    }
361
362
    // create root expr
363
433k
    int root_children = nodes[*node_idx].num_children;
364
433k
    VExprSPtr root;
365
433k
    RETURN_IF_ERROR(create_expr(nodes[*node_idx], root));
366
433k
    DCHECK(root != nullptr);
367
433k
    root_expr = root;
368
433k
    ctx = std::make_shared<VExprContext>(root);
369
    // short path for leaf node
370
433k
    if (root_children <= 0) {
371
433k
        return Status::OK();
372
433k
    }
373
374
    // non-recursive traversal
375
27
    using VExprSPtrCountPair = std::pair<VExprSPtr, int>;
376
27
    std::stack<std::shared_ptr<VExprSPtrCountPair>> s;
377
27
    s.emplace(std::make_shared<VExprSPtrCountPair>(root, root_children));
378
156
    while (!s.empty()) {
379
        // copy the shared ptr resource to avoid dangling reference
380
129
        auto parent = s.top();
381
        // Decrement or pop
382
129
        if (parent->second > 1) {
383
65
            parent->second -= 1;
384
65
        } else {
385
64
            s.pop();
386
64
        }
387
388
129
        DCHECK(parent->first != nullptr);
389
129
        if (++*node_idx >= nodes.size()) {
390
0
            return Status::InternalError("Failed to reconstruct expression tree from thrift.");
391
0
        }
392
393
129
        VExprSPtr expr;
394
129
        RETURN_IF_ERROR(create_expr(nodes[*node_idx], expr));
395
129
        DCHECK(expr != nullptr);
396
129
        parent->first->add_child(expr);
397
        // push to stack if has children
398
129
        int num_children = nodes[*node_idx].num_children;
399
129
        if (num_children > 0) {
400
37
            s.emplace(std::make_shared<VExprSPtrCountPair>(expr, num_children));
401
37
        }
402
129
    }
403
27
    return Status::OK();
404
27
}
405
406
433k
Status VExpr::create_expr_tree(const TExpr& texpr, VExprContextSPtr& ctx) {
407
433k
    if (texpr.nodes.empty()) {
408
7
        ctx = nullptr;
409
7
        return Status::OK();
410
7
    }
411
433k
    int node_idx = 0;
412
433k
    VExprSPtr e;
413
433k
    Status status = create_tree_from_thrift(texpr.nodes, &node_idx, e, ctx);
414
433k
    if (status.ok() && node_idx + 1 != texpr.nodes.size()) {
415
0
        status = Status::InternalError(
416
0
                "Expression tree only partially reconstructed. Not all thrift nodes were "
417
0
                "used.");
418
0
    }
419
433k
    if (!status.ok()) {
420
0
        LOG(ERROR) << "Could not construct expr tree.\n"
421
0
                   << status << "\n"
422
0
                   << apache::thrift::ThriftDebugString(texpr);
423
0
    }
424
433k
    return status;
425
433k
}
426
427
30.1k
Status VExpr::create_expr_trees(const std::vector<TExpr>& texprs, VExprContextSPtrs& ctxs) {
428
30.1k
    ctxs.clear();
429
75.6k
    for (const auto& texpr : texprs) {
430
75.6k
        VExprContextSPtr ctx;
431
75.6k
        RETURN_IF_ERROR(create_expr_tree(texpr, ctx));
432
75.6k
        ctxs.push_back(ctx);
433
75.6k
    }
434
30.1k
    return Status::OK();
435
30.1k
}
436
437
Status VExpr::check_expr_output_type(const VExprContextSPtrs& ctxs,
438
26.0k
                                     const RowDescriptor& output_row_desc) {
439
26.0k
    if (ctxs.empty()) {
440
2
        return Status::OK();
441
2
    }
442
26.0k
    auto name_and_types = VectorizedUtils::create_name_and_data_types(output_row_desc);
443
26.0k
    if (ctxs.size() != name_and_types.size()) {
444
0
        return Status::InternalError(
445
0
                "output type size not match expr size {} , expected output size {} ", ctxs.size(),
446
0
                name_and_types.size());
447
0
    }
448
71.5k
    auto check_type_can_be_converted = [](DataTypePtr& from, DataTypePtr& to) -> bool {
449
71.5k
        if (to->equals(*from)) {
450
71.5k
            return true;
451
71.5k
        }
452
0
        if (to->is_nullable() && !from->is_nullable()) {
453
0
            return remove_nullable(to)->equals(*from);
454
0
        }
455
0
        return false;
456
0
    };
457
97.5k
    for (int i = 0; i < ctxs.size(); i++) {
458
71.5k
        auto real_expr_type = get_data_type_with_default_argument(ctxs[i]->root()->data_type());
459
71.5k
        auto&& [name, expected_type] = name_and_types[i];
460
71.5k
        if (!check_type_can_be_converted(real_expr_type, expected_type)) {
461
0
            return Status::InternalError(
462
0
                    "output type not match expr type  , col name {} , expected type {} , real type "
463
0
                    "{}",
464
0
                    name, expected_type->get_name(), real_expr_type->get_name());
465
0
        }
466
71.5k
    }
467
26.0k
    return Status::OK();
468
26.0k
}
469
470
Status VExpr::prepare(const VExprContextSPtrs& ctxs, RuntimeState* state,
471
160k
                      const RowDescriptor& row_desc) {
472
279k
    for (auto ctx : ctxs) {
473
279k
        RETURN_IF_ERROR(ctx->prepare(state, row_desc));
474
279k
    }
475
160k
    return Status::OK();
476
160k
}
477
478
160k
Status VExpr::open(const VExprContextSPtrs& ctxs, RuntimeState* state) {
479
279k
    for (const auto& ctx : ctxs) {
480
279k
        RETURN_IF_ERROR(ctx->open(state));
481
279k
    }
482
160k
    return Status::OK();
483
160k
}
484
485
Status VExpr::clone_if_not_exists(const VExprContextSPtrs& ctxs, RuntimeState* state,
486
0
                                  VExprContextSPtrs& new_ctxs) {
487
0
    if (!new_ctxs.empty()) {
488
        // 'ctxs' was already cloned into '*new_ctxs', nothing to do.
489
0
        DCHECK_EQ(new_ctxs.size(), ctxs.size());
490
0
        for (auto& new_ctx : new_ctxs) {
491
0
            DCHECK(new_ctx->_is_clone);
492
0
        }
493
0
        return Status::OK();
494
0
    }
495
0
    new_ctxs.resize(ctxs.size());
496
0
    for (int i = 0; i < ctxs.size(); ++i) {
497
0
        RETURN_IF_ERROR(ctxs[i]->clone(state, new_ctxs[i]));
498
0
    }
499
0
    return Status::OK();
500
0
}
501
502
1
std::string VExpr::debug_string() const {
503
    // TODO: implement partial debug string for member vars
504
1
    std::stringstream out;
505
1
    out << " type=" << _data_type->get_name();
506
507
1
    if (!_children.empty()) {
508
0
        out << " children=" << debug_string(_children);
509
0
    }
510
511
1
    return out.str();
512
1
}
513
514
0
std::string VExpr::debug_string(const VExprSPtrs& exprs) {
515
0
    std::stringstream out;
516
0
    out << "[";
517
518
0
    for (int i = 0; i < exprs.size(); ++i) {
519
0
        out << (i == 0 ? "" : " ") << exprs[i]->debug_string();
520
0
    }
521
522
0
    out << "]";
523
0
    return out.str();
524
0
}
525
526
0
std::string VExpr::debug_string(const VExprContextSPtrs& ctxs) {
527
0
    VExprSPtrs exprs;
528
0
    for (const auto& ctx : ctxs) {
529
0
        exprs.push_back(ctx->root());
530
0
    }
531
0
    return debug_string(exprs);
532
0
}
533
534
61
bool VExpr::is_constant() const {
535
61
    return std::all_of(_children.begin(), _children.end(),
536
61
                       [](const VExprSPtr& expr) { return expr->is_constant(); });
537
61
}
538
539
Status VExpr::get_const_col(VExprContext* context,
540
279k
                            std::shared_ptr<ColumnPtrWrapper>* column_wrapper) {
541
279k
    if (!is_constant()) {
542
279k
        return Status::OK();
543
279k
    }
544
545
17
    if (_constant_col != nullptr) {
546
8
        DCHECK(column_wrapper != nullptr);
547
8
        *column_wrapper = _constant_col;
548
8
        return Status::OK();
549
8
    }
550
551
9
    int result = -1;
552
9
    Block block;
553
    // If block is empty, some functions will produce no result. So we insert a column with
554
    // single value here.
555
9
    block.insert({ColumnUInt8::create(1), std::make_shared<DataTypeUInt8>(), ""});
556
557
9
    _getting_const_col = true;
558
9
    RETURN_IF_ERROR(execute(context, &block, &result));
559
9
    _getting_const_col = false;
560
561
9
    DCHECK(result != -1);
562
9
    const auto& column = block.get_by_position(result).column;
563
9
    _constant_col = std::make_shared<ColumnPtrWrapper>(column);
564
9
    if (column_wrapper != nullptr) {
565
0
        *column_wrapper = _constant_col;
566
0
    }
567
568
9
    return Status::OK();
569
9
}
570
571
67
void VExpr::register_function_context(RuntimeState* state, VExprContext* context) {
572
67
    std::vector<DataTypePtr> arg_types;
573
132
    for (auto& i : _children) {
574
132
        arg_types.push_back(i->data_type());
575
132
    }
576
577
67
    _fn_context_index = context->register_function_context(state, _data_type, arg_types);
578
67
}
579
580
Status VExpr::init_function_context(RuntimeState* state, VExprContext* context,
581
                                    FunctionContext::FunctionStateScope scope,
582
26
                                    const FunctionBasePtr& function) const {
583
26
    FunctionContext* fn_ctx = context->fn_context(_fn_context_index);
584
26
    if (scope == FunctionContext::FRAGMENT_LOCAL) {
585
14
        std::vector<std::shared_ptr<ColumnPtrWrapper>> constant_cols;
586
26
        for (auto c : _children) {
587
26
            std::shared_ptr<ColumnPtrWrapper> const_col;
588
26
            RETURN_IF_ERROR(c->get_const_col(context, &const_col));
589
26
            constant_cols.push_back(const_col);
590
26
        }
591
14
        fn_ctx->set_constant_cols(constant_cols);
592
14
    }
593
594
26
    if (scope == FunctionContext::FRAGMENT_LOCAL) {
595
14
        RETURN_IF_ERROR(function->open(fn_ctx, FunctionContext::FRAGMENT_LOCAL));
596
14
    }
597
26
    RETURN_IF_ERROR(function->open(fn_ctx, FunctionContext::THREAD_LOCAL));
598
26
    return Status::OK();
599
26
}
600
601
void VExpr::close_function_context(VExprContext* context, FunctionContext::FunctionStateScope scope,
602
45
                                   const FunctionBasePtr& function) const {
603
45
    if (_fn_context_index != -1) {
604
32
        FunctionContext* fn_ctx = context->fn_context(_fn_context_index);
605
        // `close_function_context` is called in VExprContext's destructor so do not throw exceptions here.
606
32
        static_cast<void>(function->close(fn_ctx, FunctionContext::THREAD_LOCAL));
607
32
        if (scope == FunctionContext::FRAGMENT_LOCAL) {
608
20
            static_cast<void>(function->close(fn_ctx, FunctionContext::FRAGMENT_LOCAL));
609
20
        }
610
32
    }
611
45
}
612
613
8
Status VExpr::check_constant(const Block& block, ColumnNumbers arguments) const {
614
8
    if (is_constant() && !VectorizedUtils::all_arguments_are_constant(block, arguments)) {
615
0
        return Status::InternalError("const check failed, expr={}", debug_string());
616
0
    }
617
8
    return Status::OK();
618
8
}
619
620
Status VExpr::get_result_from_const(vectorized::Block* block, const std::string& expr_name,
621
0
                                    int* result_column_id) {
622
0
    *result_column_id = block->columns();
623
0
    auto column = ColumnConst::create(_constant_col->column_ptr, block->rows());
624
0
    block->insert({std::move(column), _data_type, expr_name});
625
0
    return Status::OK();
626
0
}
627
628
Status VExpr::_evaluate_inverted_index(VExprContext* context, const FunctionBasePtr& function,
629
1
                                       uint32_t segment_num_rows) {
630
    // Pre-allocate vectors based on an estimated or known size
631
1
    std::vector<segment_v2::InvertedIndexIterator*> iterators;
632
1
    std::vector<vectorized::IndexFieldNameAndTypePair> data_type_with_names;
633
1
    std::vector<int> column_ids;
634
1
    vectorized::ColumnsWithTypeAndName arguments;
635
1
    VExprSPtrs children_exprs;
636
637
    // Reserve space to avoid multiple reallocations
638
1
    const size_t estimated_size = get_num_children();
639
1
    iterators.reserve(estimated_size);
640
1
    data_type_with_names.reserve(estimated_size);
641
1
    column_ids.reserve(estimated_size);
642
1
    children_exprs.reserve(estimated_size);
643
644
1
    auto index_context = context->get_inverted_index_context();
645
646
    // if child is cast expr, we need to ensure target data type is the same with storage data type.
647
    // or they are all string type
648
    // and if data type is array, we need to get the nested data type to ensure that.
649
2
    for (const auto& child : children()) {
650
2
        if (child->node_type() == TExprNodeType::CAST_EXPR) {
651
1
            auto* cast_expr = assert_cast<VCastExpr*>(child.get());
652
1
            DCHECK_EQ(cast_expr->get_num_children(), 1);
653
1
            if (cast_expr->get_child(0)->is_slot_ref()) {
654
0
                auto* column_slot_ref = assert_cast<VSlotRef*>(cast_expr->get_child(0).get());
655
0
                auto column_id = column_slot_ref->column_id();
656
0
                const auto* storage_name_type =
657
0
                        context->get_inverted_index_context()
658
0
                                ->get_storage_name_and_type_by_column_id(column_id);
659
0
                auto storage_type = remove_nullable(storage_name_type->second);
660
0
                auto target_type = remove_nullable(cast_expr->get_target_type());
661
0
                auto origin_primitive_type = storage_type->get_primitive_type();
662
0
                auto target_primitive_type = target_type->get_primitive_type();
663
0
                if (is_complex_type(storage_type->get_primitive_type())) {
664
0
                    if (storage_type->get_primitive_type() == TYPE_ARRAY &&
665
0
                        target_type->get_primitive_type() == TYPE_ARRAY) {
666
0
                        auto nested_storage_type =
667
0
                                (assert_cast<const DataTypeArray*>(storage_type.get()))
668
0
                                        ->get_nested_type();
669
0
                        origin_primitive_type = nested_storage_type->get_primitive_type();
670
0
                        auto nested_target_type =
671
0
                                (assert_cast<const DataTypeArray*>(target_type.get()))
672
0
                                        ->get_nested_type();
673
0
                        target_primitive_type = nested_target_type->get_primitive_type();
674
0
                    } else {
675
0
                        continue;
676
0
                    }
677
0
                }
678
0
                if (origin_primitive_type != TYPE_VARIANT &&
679
0
                    (storage_type->equals(*target_type) ||
680
0
                     (is_string_type(target_primitive_type) &&
681
0
                      is_string_type(origin_primitive_type)))) {
682
0
                    children_exprs.emplace_back(expr_without_cast(child));
683
0
                }
684
1
            } else {
685
1
                return Status::OK(); // for example: cast("abc") as ipv4 case
686
1
            }
687
1
        } else {
688
1
            children_exprs.emplace_back(child);
689
1
        }
690
2
    }
691
692
0
    if (children_exprs.empty()) {
693
0
        return Status::OK(); // Early exit if no children to process
694
0
    }
695
696
0
    for (const auto& child : children_exprs) {
697
0
        if (child->is_slot_ref()) {
698
0
            auto* column_slot_ref = assert_cast<VSlotRef*>(child.get());
699
0
            auto column_id = column_slot_ref->column_id();
700
0
            auto* iter =
701
0
                    context->get_inverted_index_context()->get_inverted_index_iterator_by_column_id(
702
0
                            column_id);
703
            //column does not have inverted index
704
0
            if (iter == nullptr) {
705
0
                continue;
706
0
            }
707
0
            const auto* storage_name_type =
708
0
                    context->get_inverted_index_context()->get_storage_name_and_type_by_column_id(
709
0
                            column_id);
710
0
            if (storage_name_type == nullptr) {
711
0
                auto err_msg = fmt::format(
712
0
                        "storage_name_type cannot be found for column {} while in {} "
713
0
                        "evaluate_inverted_index",
714
0
                        column_id, expr_name());
715
0
                LOG(ERROR) << err_msg;
716
0
                return Status::InternalError(err_msg);
717
0
            }
718
0
            iterators.emplace_back(iter);
719
0
            data_type_with_names.emplace_back(*storage_name_type);
720
0
            column_ids.emplace_back(column_id);
721
0
        } else if (child->is_literal()) {
722
0
            auto* column_literal = assert_cast<VLiteral*>(child.get());
723
0
            arguments.emplace_back(column_literal->get_column_ptr(),
724
0
                                   column_literal->get_data_type(), column_literal->expr_name());
725
0
        } else {
726
0
            return Status::OK(); // others cases
727
0
        }
728
0
    }
729
730
    // is null or is not null has no arguments
731
0
    if (iterators.empty() || (arguments.empty() && !(function->get_name() == "is_not_null_pred" ||
732
0
                                                     function->get_name() == "is_null_pred"))) {
733
0
        return Status::OK(); // Nothing to evaluate or no literals to compare against
734
0
    }
735
736
0
    auto result_bitmap = segment_v2::InvertedIndexResultBitmap();
737
0
    auto res = function->evaluate_inverted_index(arguments, data_type_with_names, iterators,
738
0
                                                 segment_num_rows, result_bitmap);
739
0
    if (!res.ok()) {
740
0
        return res;
741
0
    }
742
0
    if (!result_bitmap.is_empty()) {
743
0
        index_context->set_inverted_index_result_for_expr(this, result_bitmap);
744
0
        for (int column_id : column_ids) {
745
0
            index_context->set_true_for_inverted_index_status(this, column_id);
746
0
        }
747
0
    }
748
0
    return Status::OK();
749
0
}
750
751
0
size_t VExpr::estimate_memory(const size_t rows) {
752
0
    if (is_const_and_have_executed()) {
753
0
        return 0;
754
0
    }
755
756
0
    size_t estimate_size = 0;
757
0
    for (auto& child : _children) {
758
0
        estimate_size += child->estimate_memory(rows);
759
0
    }
760
761
0
    if (_data_type->have_maximum_size_of_value()) {
762
0
        estimate_size += rows * _data_type->get_size_of_value_in_memory();
763
0
    } else {
764
0
        estimate_size += rows * 64; /// TODO: need a more reasonable value
765
0
    }
766
0
    return estimate_size;
767
0
}
768
769
bool VExpr::fast_execute(doris::vectorized::VExprContext* context, doris::vectorized::Block* block,
770
8
                         int* result_column_id) {
771
8
    if (context->get_inverted_index_context() &&
772
8
        context->get_inverted_index_context()->get_inverted_index_result_column().contains(this)) {
773
0
        uint32_t num_columns_without_result = block->columns();
774
        // prepare a column to save result
775
0
        auto result_column =
776
0
                context->get_inverted_index_context()->get_inverted_index_result_column()[this];
777
0
        if (_data_type->is_nullable()) {
778
0
            block->insert(
779
0
                    {ColumnNullable::create(result_column, ColumnUInt8::create(block->rows(), 0)),
780
0
                     _data_type, expr_name()});
781
0
        } else {
782
0
            block->insert({result_column, _data_type, expr_name()});
783
0
        }
784
0
        *result_column_id = num_columns_without_result;
785
0
        return true;
786
0
    }
787
8
    return false;
788
8
}
789
790
0
bool VExpr::equals(const VExpr& other) {
791
0
    return false;
792
0
}
793
794
#include "common/compile_check_end.h"
795
} // namespace doris::vectorized