Coverage Report

Created: 2025-05-20 15:56

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