Coverage Report

Created: 2025-04-28 20:29

/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
31
#include "common/config.h"
32
#include "common/exception.h"
33
#include "common/status.h"
34
#include "pipeline/pipeline_task.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
26
          _type(TypeDescriptor::from_thrift(node.type)) {
185
26
    if (node.__isset.fn) {
186
2
        _fn = node.fn;
187
2
    }
188
189
26
    bool is_nullable = true;
190
26
    if (node.__isset.is_nullable) {
191
0
        is_nullable = node.is_nullable;
192
0
    }
193
    // If we define null literal ,should make nullable data type to get correct field instead of undefined ptr
194
26
    if (node.node_type == TExprNodeType::NULL_LITERAL) {
195
0
        CHECK(is_nullable);
196
0
    }
197
26
    _data_type = DataTypeFactory::instance().create_data_type(_type, is_nullable);
198
26
}
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
12
Status VExpr::prepare(RuntimeState* state, const RowDescriptor& row_desc, VExprContext* context) {
212
12
    ++context->_depth_num;
213
12
    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
12
    for (auto& i : _children) {
220
2
        RETURN_IF_ERROR(i->prepare(state, row_desc, context));
221
2
    }
222
12
    --context->_depth_num;
223
12
    return Status::OK();
224
12
}
225
226
Status VExpr::open(RuntimeState* state, VExprContext* context,
227
2
                   FunctionContext::FunctionStateScope scope) {
228
2
    for (auto& i : _children) {
229
0
        RETURN_IF_ERROR(i->open(state, context, scope));
230
0
    }
231
2
    if (scope == FunctionContext::FRAGMENT_LOCAL) {
232
2
        RETURN_IF_ERROR(VExpr::get_const_col(context, nullptr));
233
2
    }
234
2
    return Status::OK();
235
2
}
236
237
4
void VExpr::close(VExprContext* context, FunctionContext::FunctionStateScope scope) {
238
4
    for (auto& i : _children) {
239
2
        i->close(context, scope);
240
2
    }
241
4
}
242
243
// NOLINTBEGIN(readability-function-size)
244
12
Status VExpr::create_expr(const TExprNode& expr_node, VExprSPtr& expr) {
245
12
    try {
246
12
        switch (expr_node.node_type) {
247
0
        case TExprNodeType::BOOL_LITERAL:
248
0
        case TExprNodeType::INT_LITERAL:
249
0
        case TExprNodeType::LARGE_INT_LITERAL:
250
0
        case TExprNodeType::IPV4_LITERAL:
251
0
        case TExprNodeType::IPV6_LITERAL:
252
0
        case TExprNodeType::FLOAT_LITERAL:
253
0
        case TExprNodeType::DECIMAL_LITERAL:
254
0
        case TExprNodeType::DATE_LITERAL:
255
0
        case TExprNodeType::STRING_LITERAL:
256
0
        case TExprNodeType::JSON_LITERAL:
257
0
        case TExprNodeType::NULL_LITERAL: {
258
0
            expr = VLiteral::create_shared(expr_node);
259
0
            break;
260
0
        }
261
0
        case TExprNodeType::ARRAY_LITERAL: {
262
0
            expr = VArrayLiteral::create_shared(expr_node);
263
0
            break;
264
0
        }
265
0
        case TExprNodeType::MAP_LITERAL: {
266
0
            expr = VMapLiteral::create_shared(expr_node);
267
0
            break;
268
0
        }
269
0
        case TExprNodeType::STRUCT_LITERAL: {
270
0
            expr = VStructLiteral::create_shared(expr_node);
271
0
            break;
272
0
        }
273
10
        case TExprNodeType::SLOT_REF: {
274
10
            expr = VSlotRef::create_shared(expr_node);
275
10
            break;
276
0
        }
277
0
        case TExprNodeType::COLUMN_REF: {
278
0
            expr = VColumnRef::create_shared(expr_node);
279
0
            break;
280
0
        }
281
0
        case TExprNodeType::COMPOUND_PRED: {
282
0
            expr = VCompoundPred::create_shared(expr_node);
283
0
            break;
284
0
        }
285
0
        case TExprNodeType::LAMBDA_FUNCTION_EXPR: {
286
0
            expr = VLambdaFunctionExpr::create_shared(expr_node);
287
0
            break;
288
0
        }
289
0
        case TExprNodeType::LAMBDA_FUNCTION_CALL_EXPR: {
290
0
            expr = VLambdaFunctionCallExpr::create_shared(expr_node);
291
0
            break;
292
0
        }
293
0
        case TExprNodeType::ARITHMETIC_EXPR:
294
0
        case TExprNodeType::BINARY_PRED:
295
0
        case TExprNodeType::NULL_AWARE_BINARY_PRED:
296
2
        case TExprNodeType::FUNCTION_CALL:
297
2
        case TExprNodeType::COMPUTE_FUNCTION_CALL: {
298
2
            expr = VectorizedFnCall::create_shared(expr_node);
299
2
            break;
300
2
        }
301
0
        case TExprNodeType::MATCH_PRED: {
302
0
            expr = VMatchPredicate::create_shared(expr_node);
303
0
            break;
304
2
        }
305
0
        case TExprNodeType::CAST_EXPR: {
306
0
            expr = VCastExpr::create_shared(expr_node);
307
0
            break;
308
2
        }
309
0
        case TExprNodeType::IN_PRED: {
310
0
            expr = VInPredicate::create_shared(expr_node);
311
0
            break;
312
2
        }
313
0
        case TExprNodeType::CASE_EXPR: {
314
0
            if (!expr_node.__isset.case_expr) {
315
0
                return Status::InternalError("Case expression not set in thrift node");
316
0
            }
317
0
            expr = VCaseExpr::create_shared(expr_node);
318
0
            break;
319
0
        }
320
0
        case TExprNodeType::INFO_FUNC: {
321
0
            expr = VInfoFunc::create_shared(expr_node);
322
0
            break;
323
0
        }
324
0
        case TExprNodeType::TUPLE_IS_NULL_PRED: {
325
0
            expr = VTupleIsNullPredicate::create_shared(expr_node);
326
0
            break;
327
0
        }
328
0
        default:
329
0
            return Status::InternalError("Unknown expr node type: {}", expr_node.node_type);
330
12
        }
331
12
    } catch (const Exception& e) {
332
0
        if (e.code() == ErrorCode::INTERNAL_ERROR) {
333
0
            return Status::InternalError("Create Expr failed because {}\nTExprNode={}", e.what(),
334
0
                                         apache::thrift::ThriftDebugString(expr_node));
335
0
        }
336
0
        return Status::Error<false>(e.code(), "Create Expr failed because {}", e.what());
337
0
        LOG(WARNING) << "create expr failed, TExprNode={}, reason={}"
338
0
                     << apache::thrift::ThriftDebugString(expr_node) << e.what();
339
0
    }
340
12
    if (!expr->data_type()) {
341
0
        return Status::InvalidArgument("Unknown expr type: {}", expr_node.node_type);
342
0
    }
343
12
    return Status::OK();
344
12
}
345
// NOLINTEND(readability-function-size)
346
347
Status VExpr::create_tree_from_thrift(const std::vector<TExprNode>& nodes, int* node_idx,
348
10
                                      VExprSPtr& root_expr, VExprContextSPtr& ctx) {
349
    // propagate error case
350
10
    if (*node_idx >= nodes.size()) {
351
0
        return Status::InternalError("Failed to reconstruct expression tree from thrift.");
352
0
    }
353
354
    // create root expr
355
10
    int root_children = nodes[*node_idx].num_children;
356
10
    VExprSPtr root;
357
10
    RETURN_IF_ERROR(create_expr(nodes[*node_idx], root));
358
10
    DCHECK(root != nullptr);
359
10
    root_expr = root;
360
10
    ctx = std::make_shared<VExprContext>(root);
361
    // short path for leaf node
362
10
    if (root_children <= 0) {
363
8
        return Status::OK();
364
8
    }
365
366
    // non-recursive traversal
367
2
    std::stack<std::pair<VExprSPtr, int>> s;
368
2
    s.emplace(root, root_children);
369
4
    while (!s.empty()) {
370
2
        auto& parent = s.top();
371
2
        if (parent.second > 1) {
372
0
            parent.second -= 1;
373
2
        } else {
374
2
            s.pop();
375
2
        }
376
377
2
        if (++*node_idx >= nodes.size()) {
378
0
            return Status::InternalError("Failed to reconstruct expression tree from thrift.");
379
0
        }
380
2
        VExprSPtr expr;
381
2
        RETURN_IF_ERROR(create_expr(nodes[*node_idx], expr));
382
2
        DCHECK(expr != nullptr);
383
2
        parent.first->add_child(expr);
384
2
        int num_children = nodes[*node_idx].num_children;
385
2
        if (num_children > 0) {
386
0
            s.emplace(expr, num_children);
387
0
        }
388
2
    }
389
2
    return Status::OK();
390
2
}
391
392
10
Status VExpr::create_expr_tree(const TExpr& texpr, VExprContextSPtr& ctx) {
393
10
    if (texpr.nodes.empty()) {
394
0
        ctx = nullptr;
395
0
        return Status::OK();
396
0
    }
397
10
    int node_idx = 0;
398
10
    VExprSPtr e;
399
10
    Status status = create_tree_from_thrift(texpr.nodes, &node_idx, e, ctx);
400
10
    if (status.ok() && node_idx + 1 != texpr.nodes.size()) {
401
0
        status = Status::InternalError(
402
0
                "Expression tree only partially reconstructed. Not all thrift nodes were "
403
0
                "used.");
404
0
    }
405
10
    if (!status.ok()) {
406
0
        LOG(ERROR) << "Could not construct expr tree.\n"
407
0
                   << status << "\n"
408
0
                   << apache::thrift::ThriftDebugString(texpr);
409
0
    }
410
10
    return status;
411
10
}
412
413
0
Status VExpr::create_expr_trees(const std::vector<TExpr>& texprs, VExprContextSPtrs& ctxs) {
414
0
    ctxs.clear();
415
0
    for (const auto& texpr : texprs) {
416
0
        VExprContextSPtr ctx;
417
0
        RETURN_IF_ERROR(create_expr_tree(texpr, ctx));
418
0
        ctxs.push_back(ctx);
419
0
    }
420
0
    return Status::OK();
421
0
}
422
423
Status VExpr::check_expr_output_type(const VExprContextSPtrs& ctxs,
424
0
                                     const RowDescriptor& output_row_desc) {
425
0
    if (ctxs.empty()) {
426
0
        return Status::OK();
427
0
    }
428
0
    auto name_and_types = VectorizedUtils::create_name_and_data_types(output_row_desc);
429
0
    if (ctxs.size() != name_and_types.size()) {
430
0
        return Status::InternalError(
431
0
                "output type size not match expr size {} , expected output size {} ", ctxs.size(),
432
0
                name_and_types.size());
433
0
    }
434
0
    auto check_type_can_be_converted = [](DataTypePtr& from, DataTypePtr& to) -> bool {
435
0
        if (to->equals(*from)) {
436
0
            return true;
437
0
        }
438
0
        if (to->is_nullable() && !from->is_nullable()) {
439
0
            return remove_nullable(to)->equals(*from);
440
0
        }
441
0
        return false;
442
0
    };
443
0
    for (int i = 0; i < ctxs.size(); i++) {
444
0
        auto real_expr_type = ctxs[i]->root()->data_type();
445
0
        auto&& [name, expected_type] = name_and_types[i];
446
0
        if (!check_type_can_be_converted(real_expr_type, expected_type)) {
447
0
            return Status::InternalError(
448
0
                    "output type not match expr type  , col name {} , expected type {} , real type "
449
0
                    "{}",
450
0
                    name, expected_type->get_name(), real_expr_type->get_name());
451
0
        }
452
0
    }
453
0
    return Status::OK();
454
0
}
455
456
Status VExpr::prepare(const VExprContextSPtrs& ctxs, RuntimeState* state,
457
4
                      const RowDescriptor& row_desc) {
458
4
    for (auto ctx : ctxs) {
459
0
        RETURN_IF_ERROR(ctx->prepare(state, row_desc));
460
0
    }
461
4
    return Status::OK();
462
4
}
463
464
4
Status VExpr::open(const VExprContextSPtrs& ctxs, RuntimeState* state) {
465
4
    for (const auto& ctx : ctxs) {
466
0
        RETURN_IF_ERROR(ctx->open(state));
467
0
    }
468
4
    return Status::OK();
469
4
}
470
471
Status VExpr::clone_if_not_exists(const VExprContextSPtrs& ctxs, RuntimeState* state,
472
0
                                  VExprContextSPtrs& new_ctxs) {
473
0
    if (!new_ctxs.empty()) {
474
        // 'ctxs' was already cloned into '*new_ctxs', nothing to do.
475
0
        DCHECK_EQ(new_ctxs.size(), ctxs.size());
476
0
        for (auto& new_ctx : new_ctxs) {
477
0
            DCHECK(new_ctx->_is_clone);
478
0
        }
479
0
        return Status::OK();
480
0
    }
481
0
    new_ctxs.resize(ctxs.size());
482
0
    for (int i = 0; i < ctxs.size(); ++i) {
483
0
        RETURN_IF_ERROR(ctxs[i]->clone(state, new_ctxs[i]));
484
0
    }
485
0
    return Status::OK();
486
0
}
487
488
0
std::string VExpr::debug_string() const {
489
    // TODO: implement partial debug string for member vars
490
0
    std::stringstream out;
491
0
    out << " type=" << _type.debug_string();
492
493
0
    if (!_children.empty()) {
494
0
        out << " children=" << debug_string(_children);
495
0
    }
496
497
0
    return out.str();
498
0
}
499
500
0
std::string VExpr::debug_string(const VExprSPtrs& exprs) {
501
0
    std::stringstream out;
502
0
    out << "[";
503
504
0
    for (int i = 0; i < exprs.size(); ++i) {
505
0
        out << (i == 0 ? "" : " ") << exprs[i]->debug_string();
506
0
    }
507
508
0
    out << "]";
509
0
    return out.str();
510
0
}
511
512
0
std::string VExpr::debug_string(const VExprContextSPtrs& ctxs) {
513
0
    VExprSPtrs exprs;
514
0
    for (const auto& ctx : ctxs) {
515
0
        exprs.push_back(ctx->root());
516
0
    }
517
0
    return debug_string(exprs);
518
0
}
519
520
2
bool VExpr::is_constant() const {
521
2
    return std::all_of(_children.begin(), _children.end(),
522
2
                       [](const VExprSPtr& expr) { return expr->is_constant(); });
523
2
}
524
525
Status VExpr::get_const_col(VExprContext* context,
526
6
                            std::shared_ptr<ColumnPtrWrapper>* column_wrapper) {
527
6
    if (!is_constant()) {
528
6
        return Status::OK();
529
6
    }
530
531
0
    if (_constant_col != nullptr) {
532
0
        DCHECK(column_wrapper != nullptr);
533
0
        *column_wrapper = _constant_col;
534
0
        return Status::OK();
535
0
    }
536
537
0
    int result = -1;
538
0
    Block block;
539
    // If block is empty, some functions will produce no result. So we insert a column with
540
    // single value here.
541
0
    block.insert({ColumnUInt8::create(1), std::make_shared<DataTypeUInt8>(), ""});
542
543
0
    _getting_const_col = true;
544
0
    RETURN_IF_ERROR(execute(context, &block, &result));
545
0
    _getting_const_col = false;
546
547
0
    DCHECK(result != -1);
548
0
    const auto& column = block.get_by_position(result).column;
549
0
    _constant_col = std::make_shared<ColumnPtrWrapper>(column);
550
0
    if (column_wrapper != nullptr) {
551
0
        *column_wrapper = _constant_col;
552
0
    }
553
554
0
    return Status::OK();
555
0
}
556
557
2
void VExpr::register_function_context(RuntimeState* state, VExprContext* context) {
558
2
    std::vector<TypeDescriptor> arg_types;
559
2
    for (auto& i : _children) {
560
2
        arg_types.push_back(i->type());
561
2
    }
562
563
2
    _fn_context_index = context->register_function_context(state, _type, arg_types);
564
2
}
565
566
Status VExpr::init_function_context(RuntimeState* state, VExprContext* context,
567
                                    FunctionContext::FunctionStateScope scope,
568
2
                                    const FunctionBasePtr& function) const {
569
2
    FunctionContext* fn_ctx = context->fn_context(_fn_context_index);
570
2
    if (scope == FunctionContext::FRAGMENT_LOCAL) {
571
2
        std::vector<std::shared_ptr<ColumnPtrWrapper>> constant_cols;
572
2
        for (auto c : _children) {
573
2
            std::shared_ptr<ColumnPtrWrapper> const_col;
574
2
            RETURN_IF_ERROR(c->get_const_col(context, &const_col));
575
2
            constant_cols.push_back(const_col);
576
2
        }
577
2
        fn_ctx->set_constant_cols(constant_cols);
578
2
    } else {
579
0
        if (function->is_udf_function()) {
580
0
            auto* timer = ADD_TIMER(state->get_task()->get_task_profile(),
581
0
                                    "UDF[" + function->get_name() + "]");
582
0
            fn_ctx->set_udf_execute_timer(timer);
583
0
        }
584
0
    }
585
586
2
    if (scope == FunctionContext::FRAGMENT_LOCAL) {
587
2
        RETURN_IF_ERROR(function->open(fn_ctx, FunctionContext::FRAGMENT_LOCAL));
588
2
    }
589
2
    RETURN_IF_ERROR(function->open(fn_ctx, FunctionContext::THREAD_LOCAL));
590
2
    return Status::OK();
591
2
}
592
593
void VExpr::close_function_context(VExprContext* context, FunctionContext::FunctionStateScope scope,
594
2
                                   const FunctionBasePtr& function) const {
595
2
    if (_fn_context_index != -1) {
596
2
        FunctionContext* fn_ctx = context->fn_context(_fn_context_index);
597
        // `close_function_context` is called in VExprContext's destructor so do not throw exceptions here.
598
2
        static_cast<void>(function->close(fn_ctx, FunctionContext::THREAD_LOCAL));
599
2
        if (scope == FunctionContext::FRAGMENT_LOCAL) {
600
2
            static_cast<void>(function->close(fn_ctx, FunctionContext::FRAGMENT_LOCAL));
601
2
        }
602
2
    }
603
2
}
604
605
0
Status VExpr::check_constant(const Block& block, ColumnNumbers arguments) const {
606
0
    if (is_constant() && !VectorizedUtils::all_arguments_are_constant(block, arguments)) {
607
0
        return Status::InternalError("const check failed, expr={}", debug_string());
608
0
    }
609
0
    return Status::OK();
610
0
}
611
612
Status VExpr::get_result_from_const(vectorized::Block* block, const std::string& expr_name,
613
0
                                    int* result_column_id) {
614
0
    *result_column_id = block->columns();
615
0
    auto column = ColumnConst::create(_constant_col->column_ptr, block->rows());
616
0
    block->insert({std::move(column), _data_type, expr_name});
617
0
    return Status::OK();
618
0
}
619
620
Status VExpr::_evaluate_inverted_index(VExprContext* context, const FunctionBasePtr& function,
621
0
                                       uint32_t segment_num_rows) {
622
    // Pre-allocate vectors based on an estimated or known size
623
0
    std::vector<segment_v2::InvertedIndexIterator*> iterators;
624
0
    std::vector<vectorized::IndexFieldNameAndTypePair> data_type_with_names;
625
0
    std::vector<int> column_ids;
626
0
    vectorized::ColumnsWithTypeAndName arguments;
627
0
    VExprSPtrs children_exprs;
628
629
    // Reserve space to avoid multiple reallocations
630
0
    const size_t estimated_size = children().size();
631
0
    iterators.reserve(estimated_size);
632
0
    data_type_with_names.reserve(estimated_size);
633
0
    column_ids.reserve(estimated_size);
634
0
    children_exprs.reserve(estimated_size);
635
636
0
    auto index_context = context->get_inverted_index_context();
637
638
    // if child is cast expr, we need to ensure target data type is the same with storage data type.
639
    // or they are all string type
640
    // and if data type is array, we need to get the nested data type to ensure that.
641
0
    for (const auto& child : children()) {
642
0
        if (child->node_type() == TExprNodeType::CAST_EXPR) {
643
0
            auto* cast_expr = assert_cast<VCastExpr*>(child.get());
644
0
            DCHECK_EQ(cast_expr->children().size(), 1);
645
0
            if (cast_expr->get_child(0)->is_slot_ref()) {
646
0
                auto* column_slot_ref = assert_cast<VSlotRef*>(cast_expr->get_child(0).get());
647
0
                auto column_id = column_slot_ref->column_id();
648
0
                const auto* storage_name_type =
649
0
                        context->get_inverted_index_context()
650
0
                                ->get_storage_name_and_type_by_column_id(column_id);
651
0
                auto storage_type = remove_nullable(storage_name_type->second);
652
0
                auto target_type = remove_nullable(cast_expr->get_target_type());
653
0
                auto origin_primitive_type = storage_type->get_type_as_type_descriptor().type;
654
0
                auto target_primitive_type = target_type->get_type_as_type_descriptor().type;
655
0
                if (is_complex_type(storage_type)) {
656
0
                    if (is_array(storage_type) && is_array(target_type)) {
657
0
                        auto nested_storage_type =
658
0
                                (assert_cast<const DataTypeArray*>(storage_type.get()))
659
0
                                        ->get_nested_type();
660
0
                        origin_primitive_type =
661
0
                                nested_storage_type->get_type_as_type_descriptor().type;
662
0
                        auto nested_target_type =
663
0
                                (assert_cast<const DataTypeArray*>(target_type.get()))
664
0
                                        ->get_nested_type();
665
0
                        target_primitive_type =
666
0
                                nested_target_type->get_type_as_type_descriptor().type;
667
0
                    } else {
668
0
                        continue;
669
0
                    }
670
0
                }
671
0
                if (origin_primitive_type != TYPE_VARIANT &&
672
0
                    (storage_type->equals(*target_type) ||
673
0
                     (is_string_type(target_primitive_type) &&
674
0
                      is_string_type(origin_primitive_type)))) {
675
0
                    children_exprs.emplace_back(expr_without_cast(child));
676
0
                }
677
0
            }
678
0
        } else {
679
0
            children_exprs.emplace_back(child);
680
0
        }
681
0
    }
682
683
0
    if (children_exprs.empty()) {
684
0
        return Status::OK(); // Early exit if no children to process
685
0
    }
686
687
0
    for (const auto& child : children_exprs) {
688
0
        if (child->is_slot_ref()) {
689
0
            auto* column_slot_ref = assert_cast<VSlotRef*>(child.get());
690
0
            auto column_id = column_slot_ref->column_id();
691
0
            auto* iter =
692
0
                    context->get_inverted_index_context()->get_inverted_index_iterator_by_column_id(
693
0
                            column_id);
694
            //column does not have inverted index
695
0
            if (iter == nullptr) {
696
0
                continue;
697
0
            }
698
0
            const auto* storage_name_type =
699
0
                    context->get_inverted_index_context()->get_storage_name_and_type_by_column_id(
700
0
                            column_id);
701
0
            if (storage_name_type == nullptr) {
702
0
                auto err_msg = fmt::format(
703
0
                        "storage_name_type cannot be found for column {} while in {} "
704
0
                        "evaluate_inverted_index",
705
0
                        column_id, expr_name());
706
0
                LOG(ERROR) << err_msg;
707
0
                return Status::InternalError(err_msg);
708
0
            }
709
0
            iterators.emplace_back(iter);
710
0
            data_type_with_names.emplace_back(*storage_name_type);
711
0
            column_ids.emplace_back(column_id);
712
0
        } else if (child->is_literal()) {
713
0
            auto* column_literal = assert_cast<VLiteral*>(child.get());
714
0
            arguments.emplace_back(column_literal->get_column_ptr(),
715
0
                                   column_literal->get_data_type(), column_literal->expr_name());
716
0
        }
717
0
    }
718
719
0
    if (iterators.empty() || arguments.empty()) {
720
0
        return Status::OK(); // Nothing to evaluate or no literals to compare against
721
0
    }
722
723
0
    auto result_bitmap = segment_v2::InvertedIndexResultBitmap();
724
0
    auto res = function->evaluate_inverted_index(arguments, data_type_with_names, iterators,
725
0
                                                 segment_num_rows, result_bitmap);
726
0
    if (!res.ok()) {
727
0
        return res;
728
0
    }
729
0
    if (!result_bitmap.is_empty()) {
730
0
        index_context->set_inverted_index_result_for_expr(this, result_bitmap);
731
0
        for (int column_id : column_ids) {
732
0
            index_context->set_true_for_inverted_index_status(this, column_id);
733
0
        }
734
0
    }
735
0
    return Status::OK();
736
0
}
737
738
bool VExpr::fast_execute(doris::vectorized::VExprContext* context, doris::vectorized::Block* block,
739
0
                         int* result_column_id) {
740
0
    if (context->get_inverted_index_context() &&
741
0
        context->get_inverted_index_context()->get_inverted_index_result_column().contains(this)) {
742
0
        size_t num_columns_without_result = block->columns();
743
        // prepare a column to save result
744
0
        auto result_column =
745
0
                context->get_inverted_index_context()->get_inverted_index_result_column()[this];
746
0
        if (_data_type->is_nullable()) {
747
0
            block->insert(
748
0
                    {ColumnNullable::create(result_column, ColumnUInt8::create(block->rows(), 0)),
749
0
                     _data_type, expr_name()});
750
0
        } else {
751
0
            block->insert({result_column, _data_type, expr_name()});
752
0
        }
753
0
        *result_column_id = num_columns_without_result;
754
0
        return true;
755
0
    }
756
0
    return false;
757
0
}
758
759
0
bool VExpr::equals(const VExpr& other) {
760
0
    return false;
761
0
}
762
763
} // namespace doris::vectorized