Coverage Report

Created: 2025-07-28 16:00

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