Coverage Report

Created: 2025-04-22 21:03

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