Coverage Report

Created: 2024-11-20 12:30

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