Coverage Report

Created: 2026-01-23 18:48

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/root/doris/be/src/vec/exprs/vexpr.cpp
Line
Count
Source
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
#include "vec/exprs/vexpr.h"
19
20
#include <fmt/format.h>
21
#include <gen_cpp/Exprs_types.h>
22
#include <gen_cpp/FrontendService_types.h>
23
#include <thrift/protocol/TDebugProtocol.h>
24
25
#include <algorithm>
26
#include <boost/algorithm/string/split.hpp>
27
#include <boost/iterator/iterator_facade.hpp>
28
#include <cstdint>
29
#include <memory>
30
#include <stack>
31
#include <string_view>
32
#include <utility>
33
34
#include "common/config.h"
35
#include "common/exception.h"
36
#include "common/status.h"
37
#include "olap/inverted_index_parser.h"
38
#include "olap/rowset/segment_v2/ann_index/ann_search_params.h"
39
#include "olap/rowset/segment_v2/ann_index/ann_topn_runtime.h"
40
#include "pipeline/pipeline_task.h"
41
#include "runtime/define_primitive_type.h"
42
#include "vec/columns/column_vector.h"
43
#include "vec/core/field.h"
44
#include "vec/data_types/data_type_array.h"
45
#include "vec/data_types/data_type_decimal.h"
46
#include "vec/data_types/data_type_factory.hpp"
47
#include "vec/data_types/data_type_nullable.h"
48
#include "vec/data_types/data_type_number.h"
49
#include "vec/exprs/varray_literal.h"
50
#include "vec/exprs/vcase_expr.h"
51
#include "vec/exprs/vcast_expr.h"
52
#include "vec/exprs/vcolumn_ref.h"
53
#include "vec/exprs/vcompound_pred.h"
54
#include "vec/exprs/vcondition_expr.h"
55
#include "vec/exprs/vectorized_fn_call.h"
56
#include "vec/exprs/vexpr_context.h"
57
#include "vec/exprs/vexpr_fwd.h"
58
#include "vec/exprs/vin_predicate.h"
59
#include "vec/exprs/vinfo_func.h"
60
#include "vec/exprs/virtual_slot_ref.h"
61
#include "vec/exprs/vlambda_function_call_expr.h"
62
#include "vec/exprs/vlambda_function_expr.h"
63
#include "vec/exprs/vliteral.h"
64
#include "vec/exprs/vmap_literal.h"
65
#include "vec/exprs/vmatch_predicate.h"
66
#include "vec/exprs/vsearch.h"
67
#include "vec/exprs/vslot_ref.h"
68
#include "vec/exprs/vstruct_literal.h"
69
#include "vec/runtime/timestamptz_value.h"
70
#include "vec/utils/util.hpp"
71
72
namespace doris {
73
#include "common/compile_check_begin.h"
74
75
class RowDescriptor;
76
class RuntimeState;
77
78
// NOLINTBEGIN(readability-function-cognitive-complexity)
79
// NOLINTBEGIN(readability-function-size)
80
TExprNode create_texpr_node_from(const void* data, const PrimitiveType& type, int precision,
81
17
                                 int scale) {
82
17
    TExprNode node;
83
84
17
    switch (type) {
85
0
    case TYPE_BOOLEAN: {
86
0
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_BOOLEAN>(data, &node));
87
0
        break;
88
0
    }
89
0
    case TYPE_TINYINT: {
90
0
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_TINYINT>(data, &node));
91
0
        break;
92
0
    }
93
0
    case TYPE_SMALLINT: {
94
0
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_SMALLINT>(data, &node));
95
0
        break;
96
0
    }
97
5
    case TYPE_INT: {
98
5
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_INT>(data, &node));
99
5
        break;
100
5
    }
101
11
    case TYPE_BIGINT: {
102
11
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_BIGINT>(data, &node));
103
11
        break;
104
11
    }
105
11
    case TYPE_LARGEINT: {
106
0
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_LARGEINT>(data, &node));
107
0
        break;
108
0
    }
109
0
    case TYPE_FLOAT: {
110
0
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_FLOAT>(data, &node));
111
0
        break;
112
0
    }
113
0
    case TYPE_DOUBLE: {
114
0
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_DOUBLE>(data, &node));
115
0
        break;
116
0
    }
117
0
    case TYPE_DATEV2: {
118
0
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_DATEV2>(data, &node));
119
0
        break;
120
0
    }
121
0
    case TYPE_DATETIMEV2: {
122
0
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_DATETIMEV2>(data, &node, precision, scale));
123
0
        break;
124
0
    }
125
0
    case TYPE_DATE: {
126
0
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_DATE>(data, &node));
127
0
        break;
128
0
    }
129
0
    case TYPE_DATETIME: {
130
0
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_DATETIME>(data, &node));
131
0
        break;
132
0
    }
133
0
    case TYPE_DECIMALV2: {
134
0
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_DECIMALV2>(data, &node, precision, scale));
135
0
        break;
136
0
    }
137
0
    case TYPE_DECIMAL32: {
138
0
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_DECIMAL32>(data, &node, precision, scale));
139
0
        break;
140
0
    }
141
0
    case TYPE_DECIMAL64: {
142
0
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_DECIMAL64>(data, &node, precision, scale));
143
0
        break;
144
0
    }
145
0
    case TYPE_DECIMAL128I: {
146
0
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_DECIMAL128I>(data, &node, precision, scale));
147
0
        break;
148
0
    }
149
0
    case TYPE_DECIMAL256: {
150
0
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_DECIMAL256>(data, &node, precision, scale));
151
0
        break;
152
0
    }
153
0
    case TYPE_CHAR: {
154
0
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_CHAR>(data, &node));
155
0
        break;
156
0
    }
157
0
    case TYPE_VARCHAR: {
158
0
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_VARCHAR>(data, &node));
159
0
        break;
160
0
    }
161
0
    case TYPE_STRING: {
162
0
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_STRING>(data, &node));
163
0
        break;
164
0
    }
165
0
    case TYPE_IPV4: {
166
0
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_IPV4>(data, &node));
167
0
        break;
168
0
    }
169
0
    case TYPE_IPV6: {
170
0
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_IPV6>(data, &node));
171
0
        break;
172
0
    }
173
0
    case TYPE_TIMEV2: {
174
0
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_TIMEV2>(data, &node, precision, scale));
175
0
        break;
176
0
    }
177
1
    case TYPE_TIMESTAMPTZ: {
178
1
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_TIMESTAMPTZ>(data, &node, precision, scale));
179
1
        break;
180
1
    }
181
1
    default:
182
0
        throw Exception(ErrorCode::INTERNAL_ERROR, "runtime filter meet invalid type {}",
183
0
                        int(type));
184
17
    }
185
17
    return node;
186
17
}
187
188
TExprNode create_texpr_node_from(const vectorized::Field& field, const PrimitiveType& type,
189
23
                                 int precision, int scale) {
190
23
    TExprNode node;
191
23
    switch (type) {
192
1
    case TYPE_BOOLEAN: {
193
1
        const auto& storage = static_cast<bool>(field.get<TYPE_BOOLEAN>());
194
1
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_BOOLEAN>(&storage, &node));
195
1
        break;
196
1
    }
197
1
    case TYPE_TINYINT: {
198
0
        const auto& storage = static_cast<int8_t>(field.get<TYPE_TINYINT>());
199
0
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_TINYINT>(&storage, &node));
200
0
        break;
201
0
    }
202
1
    case TYPE_SMALLINT: {
203
1
        const auto& storage = static_cast<int16_t>(field.get<TYPE_SMALLINT>());
204
1
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_SMALLINT>(&storage, &node));
205
1
        break;
206
1
    }
207
1
    case TYPE_INT: {
208
1
        const auto& storage = static_cast<int32_t>(field.get<TYPE_INT>());
209
1
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_INT>(&storage, &node));
210
1
        break;
211
1
    }
212
1
    case TYPE_BIGINT: {
213
1
        const auto& storage = static_cast<int64_t>(field.get<TYPE_BIGINT>());
214
1
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_BIGINT>(&storage, &node));
215
1
        break;
216
1
    }
217
1
    case TYPE_LARGEINT: {
218
1
        const auto& storage = static_cast<int128_t>(field.get<TYPE_LARGEINT>());
219
1
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_LARGEINT>(&storage, &node));
220
1
        break;
221
1
    }
222
1
    case TYPE_FLOAT: {
223
1
        const auto& storage = static_cast<float>(field.get<TYPE_FLOAT>());
224
1
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_FLOAT>(&storage, &node));
225
1
        break;
226
1
    }
227
1
    case TYPE_DOUBLE: {
228
1
        const auto& storage = static_cast<double>(field.get<TYPE_DOUBLE>());
229
1
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_DOUBLE>(&storage, &node));
230
1
        break;
231
1
    }
232
1
    case TYPE_DATEV2: {
233
1
        const auto& storage = field.get<TYPE_DATEV2>();
234
235
1
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_DATEV2>(&storage, &node));
236
1
        break;
237
1
    }
238
1
    case TYPE_DATETIMEV2: {
239
1
        const auto& storage = field.get<TYPE_DATETIMEV2>();
240
1
        THROW_IF_ERROR(
241
1
                create_texpr_literal_node<TYPE_DATETIMEV2>(&storage, &node, precision, scale));
242
1
        break;
243
1
    }
244
1
    case TYPE_TIMESTAMPTZ: {
245
1
        const auto& storage = field.get<TYPE_TIMESTAMPTZ>();
246
247
1
        THROW_IF_ERROR(
248
1
                create_texpr_literal_node<TYPE_TIMESTAMPTZ>(&storage, &node, precision, scale));
249
1
        break;
250
1
    }
251
1
    case TYPE_DATE: {
252
1
        const auto& storage = field.get<TYPE_DATE>();
253
1
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_DATE>(&storage, &node));
254
1
        break;
255
1
    }
256
1
    case TYPE_DATETIME: {
257
1
        const auto& storage = field.get<TYPE_DATETIME>();
258
1
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_DATETIME>(&storage, &node));
259
1
        break;
260
1
    }
261
1
    case TYPE_DECIMALV2: {
262
1
        const auto& storage = field.get<TYPE_DECIMALV2>();
263
264
1
        THROW_IF_ERROR(
265
1
                create_texpr_literal_node<TYPE_DECIMALV2>(&storage, &node, precision, scale));
266
1
        break;
267
1
    }
268
2
    case TYPE_DECIMAL32: {
269
2
        const auto& storage = field.get<TYPE_DECIMAL32>();
270
2
        THROW_IF_ERROR(
271
2
                create_texpr_literal_node<TYPE_DECIMAL32>(&storage, &node, precision, scale));
272
2
        break;
273
2
    }
274
2
    case TYPE_DECIMAL64: {
275
2
        const auto& storage = field.get<TYPE_DECIMAL64>();
276
2
        THROW_IF_ERROR(
277
2
                create_texpr_literal_node<TYPE_DECIMAL64>(&storage, &node, precision, scale));
278
2
        break;
279
2
    }
280
2
    case TYPE_DECIMAL128I: {
281
2
        const auto& storage = field.get<TYPE_DECIMAL128I>();
282
2
        THROW_IF_ERROR(
283
2
                create_texpr_literal_node<TYPE_DECIMAL128I>(&storage, &node, precision, scale));
284
2
        break;
285
2
    }
286
2
    case TYPE_DECIMAL256: {
287
2
        const auto& storage = field.get<TYPE_DECIMAL256>();
288
2
        THROW_IF_ERROR(
289
2
                create_texpr_literal_node<TYPE_DECIMAL256>(&storage, &node, precision, scale));
290
2
        break;
291
2
    }
292
2
    case TYPE_CHAR: {
293
0
        const auto& storage = field.get<TYPE_CHAR>();
294
0
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_CHAR>(&storage, &node));
295
0
        break;
296
0
    }
297
0
    case TYPE_VARCHAR: {
298
0
        const auto& storage = field.get<TYPE_VARCHAR>();
299
0
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_VARCHAR>(&storage, &node));
300
0
        break;
301
0
    }
302
1
    case TYPE_STRING: {
303
1
        const auto& storage = field.get<TYPE_STRING>();
304
1
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_STRING>(&storage, &node));
305
1
        break;
306
1
    }
307
1
    case TYPE_IPV4: {
308
0
        const auto& storage = field.get<TYPE_IPV4>();
309
0
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_IPV4>(&storage, &node));
310
0
        break;
311
0
    }
312
0
    case TYPE_IPV6: {
313
0
        const auto& storage = field.get<TYPE_IPV6>();
314
0
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_IPV6>(&storage, &node));
315
0
        break;
316
0
    }
317
1
    case TYPE_TIMEV2: {
318
1
        const auto& storage = field.get<TYPE_TIMEV2>();
319
1
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_TIMEV2>(&storage, &node));
320
1
        break;
321
1
    }
322
1
    case TYPE_VARBINARY: {
323
0
        const auto& svf = field.get<TYPE_VARBINARY>();
324
0
        THROW_IF_ERROR(create_texpr_literal_node<TYPE_VARBINARY>(&svf, &node));
325
0
        break;
326
0
    }
327
0
    default:
328
0
        throw Exception(ErrorCode::INTERNAL_ERROR, "runtime filter meet invalid type {}",
329
0
                        int(type));
330
23
    }
331
23
    return node;
332
23
}
333
334
// NOLINTEND(readability-function-size)
335
// NOLINTEND(readability-function-cognitive-complexity)
336
} // namespace doris
337
338
namespace doris::vectorized {
339
340
0
bool VExpr::is_acting_on_a_slot(const VExpr& expr) {
341
0
    const auto& children = expr.children();
342
343
0
    auto is_a_slot = std::any_of(children.begin(), children.end(),
344
0
                                 [](const auto& child) { return is_acting_on_a_slot(*child); });
345
346
0
    return is_a_slot ? true
347
0
                     : (expr.node_type() == TExprNodeType::SLOT_REF ||
348
0
                        expr.node_type() == TExprNodeType::VIRTUAL_SLOT_REF);
349
0
}
350
351
VExpr::VExpr(const TExprNode& node)
352
400k
        : _node_type(node.node_type),
353
400k
          _opcode(node.__isset.opcode ? node.opcode : TExprOpcode::INVALID_OPCODE) {
354
400k
    if (node.__isset.fn) {
355
72
        _fn = node.fn;
356
72
    }
357
358
400k
    bool is_nullable = true;
359
400k
    if (node.__isset.is_nullable) {
360
396k
        is_nullable = node.is_nullable;
361
396k
    }
362
    // If we define null literal ,should make nullable data type to get correct field instead of undefined ptr
363
400k
    if (node.node_type == TExprNodeType::NULL_LITERAL) {
364
1
        CHECK(is_nullable);
365
1
    }
366
400k
    _data_type = get_data_type_with_default_argument(
367
400k
            DataTypeFactory::instance().create_data_type(node.type, is_nullable));
368
400k
}
369
370
0
VExpr::VExpr(const VExpr& vexpr) = default;
371
372
VExpr::VExpr(DataTypePtr type, bool is_slotref)
373
9
        : _opcode(TExprOpcode::INVALID_OPCODE),
374
9
          _data_type(get_data_type_with_default_argument(type)) {
375
9
    if (is_slotref) {
376
0
        _node_type = TExprNodeType::SLOT_REF;
377
0
    }
378
9
}
379
380
258k
Status VExpr::prepare(RuntimeState* state, const RowDescriptor& row_desc, VExprContext* context) {
381
258k
    ++context->_depth_num;
382
258k
    if (context->_depth_num > config::max_depth_of_expr_tree) {
383
0
        return Status::Error<ErrorCode::EXCEEDED_LIMIT>(
384
0
                "The depth of the expression tree is too big, make it less than {}",
385
0
                config::max_depth_of_expr_tree);
386
0
    }
387
388
258k
    for (auto& i : _children) {
389
232
        RETURN_IF_ERROR(i->prepare(state, row_desc, context));
390
232
    }
391
258k
    --context->_depth_num;
392
#ifndef BE_TEST
393
    _enable_inverted_index_query = state->query_options().enable_inverted_index_query;
394
#endif
395
258k
    return Status::OK();
396
258k
}
397
398
Status VExpr::open(RuntimeState* state, VExprContext* context,
399
512k
                   FunctionContext::FunctionStateScope scope) {
400
512k
    for (auto& i : _children) {
401
66
        RETURN_IF_ERROR(i->open(state, context, scope));
402
66
    }
403
512k
    if (scope == FunctionContext::FRAGMENT_LOCAL) {
404
258k
        RETURN_IF_ERROR(VExpr::get_const_col(context, nullptr));
405
258k
    }
406
512k
    return Status::OK();
407
512k
}
408
409
514k
void VExpr::close(VExprContext* context, FunctionContext::FunctionStateScope scope) {
410
514k
    for (auto& i : _children) {
411
273
        i->close(context, scope);
412
273
    }
413
514k
}
414
415
// NOLINTBEGIN(readability-function-size)
416
400k
Status VExpr::create_expr(const TExprNode& expr_node, VExprSPtr& expr) {
417
400k
    try {
418
400k
        switch (expr_node.node_type) {
419
0
        case TExprNodeType::BOOL_LITERAL:
420
31
        case TExprNodeType::INT_LITERAL:
421
31
        case TExprNodeType::LARGE_INT_LITERAL:
422
32
        case TExprNodeType::IPV4_LITERAL:
423
32
        case TExprNodeType::IPV6_LITERAL:
424
143
        case TExprNodeType::FLOAT_LITERAL:
425
144
        case TExprNodeType::DECIMAL_LITERAL:
426
147
        case TExprNodeType::DATE_LITERAL:
427
147
        case TExprNodeType::TIMEV2_LITERAL:
428
153
        case TExprNodeType::STRING_LITERAL:
429
153
        case TExprNodeType::JSON_LITERAL:
430
153
        case TExprNodeType::VARBINARY_LITERAL:
431
154
        case TExprNodeType::NULL_LITERAL: {
432
154
            expr = VLiteral::create_shared(expr_node);
433
154
            break;
434
153
        }
435
13
        case TExprNodeType::ARRAY_LITERAL: {
436
13
            expr = VArrayLiteral::create_shared(expr_node);
437
13
            break;
438
153
        }
439
0
        case TExprNodeType::MAP_LITERAL: {
440
0
            expr = VMapLiteral::create_shared(expr_node);
441
0
            break;
442
153
        }
443
0
        case TExprNodeType::STRUCT_LITERAL: {
444
0
            expr = VStructLiteral::create_shared(expr_node);
445
0
            break;
446
153
        }
447
400k
        case TExprNodeType::SLOT_REF: {
448
400k
            if (expr_node.slot_ref.__isset.is_virtual_slot && expr_node.slot_ref.is_virtual_slot) {
449
11
                expr = VirtualSlotRef::create_shared(expr_node);
450
11
                expr->_node_type = TExprNodeType::VIRTUAL_SLOT_REF;
451
400k
            } else {
452
400k
                expr = VSlotRef::create_shared(expr_node);
453
400k
            }
454
400k
            break;
455
153
        }
456
0
        case TExprNodeType::COLUMN_REF: {
457
0
            expr = VColumnRef::create_shared(expr_node);
458
0
            break;
459
153
        }
460
17
        case TExprNodeType::COMPOUND_PRED: {
461
17
            expr = VCompoundPred::create_shared(expr_node);
462
17
            break;
463
153
        }
464
0
        case TExprNodeType::LAMBDA_FUNCTION_EXPR: {
465
0
            expr = VLambdaFunctionExpr::create_shared(expr_node);
466
0
            break;
467
153
        }
468
0
        case TExprNodeType::LAMBDA_FUNCTION_CALL_EXPR: {
469
0
            expr = VLambdaFunctionCallExpr::create_shared(expr_node);
470
0
            break;
471
153
        }
472
0
        case TExprNodeType::ARITHMETIC_EXPR:
473
44
        case TExprNodeType::BINARY_PRED:
474
45
        case TExprNodeType::NULL_AWARE_BINARY_PRED:
475
45
        case TExprNodeType::COMPUTE_FUNCTION_CALL: {
476
45
            expr = VectorizedFnCall::create_shared(expr_node);
477
45
            break;
478
45
        }
479
21
        case TExprNodeType::FUNCTION_CALL: {
480
21
            if (expr_node.fn.name.function_name == "if") {
481
0
                expr = VectorizedIfExpr::create_shared(expr_node);
482
0
                break;
483
21
            } else if (expr_node.fn.name.function_name == "ifnull" ||
484
21
                       expr_node.fn.name.function_name == "nvl") {
485
0
                expr = VectorizedIfNullExpr::create_shared(expr_node);
486
0
                break;
487
21
            } else if (expr_node.fn.name.function_name == "coalesce") {
488
0
                expr = VectorizedCoalesceExpr::create_shared(expr_node);
489
0
                break;
490
0
            }
491
21
            expr = VectorizedFnCall::create_shared(expr_node);
492
21
            break;
493
21
        }
494
0
        case TExprNodeType::MATCH_PRED: {
495
0
            expr = VMatchPredicate::create_shared(expr_node);
496
0
            break;
497
21
        }
498
2
        case TExprNodeType::CAST_EXPR: {
499
2
            expr = VCastExpr::create_shared(expr_node);
500
2
            break;
501
21
        }
502
0
        case TExprNodeType::TRY_CAST_EXPR: {
503
0
            expr = TryCastExpr::create_shared(expr_node);
504
0
            break;
505
21
        }
506
5
        case TExprNodeType::IN_PRED: {
507
5
            expr = VInPredicate::create_shared(expr_node);
508
5
            break;
509
21
        }
510
0
        case TExprNodeType::CASE_EXPR: {
511
0
            if (!expr_node.__isset.case_expr) {
512
0
                return Status::InternalError("Case expression not set in thrift node");
513
0
            }
514
0
            expr = VCaseExpr::create_shared(expr_node);
515
0
            break;
516
0
        }
517
0
        case TExprNodeType::INFO_FUNC: {
518
0
            expr = VInfoFunc::create_shared(expr_node);
519
0
            break;
520
0
        }
521
0
        case TExprNodeType::SEARCH_EXPR: {
522
0
            expr = VSearchExpr::create_shared(expr_node);
523
0
            break;
524
0
        }
525
0
        default:
526
0
            return Status::InternalError("Unknown expr node type: {}", expr_node.node_type);
527
400k
        }
528
400k
    } catch (const Exception& e) {
529
0
        if (e.code() == ErrorCode::INTERNAL_ERROR) {
530
0
            return Status::InternalError("Create Expr failed because {}\nTExprNode={}", e.what(),
531
0
                                         apache::thrift::ThriftDebugString(expr_node));
532
0
        }
533
0
        return Status::Error<false>(e.code(), "Create Expr failed because {}", e.what());
534
0
        LOG(WARNING) << "create expr failed, TExprNode={}, reason={}"
535
0
                     << apache::thrift::ThriftDebugString(expr_node) << e.what();
536
0
    }
537
400k
    if (!expr->data_type()) {
538
0
        return Status::InvalidArgument("Unknown expr type: {}", expr_node.node_type);
539
0
    }
540
400k
    return Status::OK();
541
400k
}
542
// NOLINTEND(readability-function-size)
543
544
Status VExpr::create_tree_from_thrift(const std::vector<TExprNode>& nodes, int* node_idx,
545
400k
                                      VExprSPtr& root_expr, VExprContextSPtr& ctx) {
546
    // propagate error case
547
400k
    if (*node_idx >= nodes.size()) {
548
0
        return Status::InternalError("Failed to reconstruct expression tree from thrift.");
549
0
    }
550
551
    // create root expr
552
400k
    int root_children = nodes[*node_idx].num_children;
553
400k
    VExprSPtr root;
554
400k
    RETURN_IF_ERROR(create_expr(nodes[*node_idx], root));
555
400k
    DCHECK(root != nullptr);
556
400k
    root_expr = root;
557
400k
    ctx = std::make_shared<VExprContext>(root);
558
    // short path for leaf node
559
400k
    if (root_children <= 0) {
560
399k
        return Status::OK();
561
399k
    }
562
563
    // non-recursive traversal
564
45
    using VExprSPtrCountPair = std::pair<VExprSPtr, int>;
565
45
    std::stack<std::shared_ptr<VExprSPtrCountPair>> s;
566
45
    s.emplace(std::make_shared<VExprSPtrCountPair>(root, root_children));
567
312
    while (!s.empty()) {
568
        // copy the shared ptr resource to avoid dangling reference
569
267
        auto parent = s.top();
570
        // Decrement or pop
571
267
        if (parent->second > 1) {
572
173
            parent->second -= 1;
573
173
        } else {
574
94
            s.pop();
575
94
        }
576
577
267
        DCHECK(parent->first != nullptr);
578
267
        if (++*node_idx >= nodes.size()) {
579
0
            return Status::InternalError("Failed to reconstruct expression tree from thrift.");
580
0
        }
581
582
267
        VExprSPtr expr;
583
267
        RETURN_IF_ERROR(create_expr(nodes[*node_idx], expr));
584
267
        DCHECK(expr != nullptr);
585
267
        parent->first->add_child(expr);
586
        // push to stack if has children
587
267
        int num_children = nodes[*node_idx].num_children;
588
267
        if (num_children > 0) {
589
49
            s.emplace(std::make_shared<VExprSPtrCountPair>(expr, num_children));
590
49
        }
591
267
    }
592
45
    return Status::OK();
593
45
}
594
595
400k
Status VExpr::create_expr_tree(const TExpr& texpr, VExprContextSPtr& ctx) {
596
400k
    if (texpr.nodes.empty()) {
597
7
        ctx = nullptr;
598
7
        return Status::OK();
599
7
    }
600
400k
    int node_idx = 0;
601
400k
    VExprSPtr e;
602
400k
    Status status = create_tree_from_thrift(texpr.nodes, &node_idx, e, ctx);
603
400k
    if (status.ok() && node_idx + 1 != texpr.nodes.size()) {
604
0
        status = Status::InternalError(
605
0
                "Expression tree only partially reconstructed. Not all thrift nodes were "
606
0
                "used.");
607
0
    }
608
400k
    if (!status.ok()) {
609
0
        LOG(ERROR) << "Could not construct expr tree.\n"
610
0
                   << status << "\n"
611
0
                   << apache::thrift::ThriftDebugString(texpr);
612
0
    }
613
400k
    return status;
614
400k
}
615
616
28.1k
Status VExpr::create_expr_trees(const std::vector<TExpr>& texprs, VExprContextSPtrs& ctxs) {
617
28.1k
    ctxs.clear();
618
70.0k
    for (const auto& texpr : texprs) {
619
70.0k
        VExprContextSPtr ctx;
620
70.0k
        RETURN_IF_ERROR(create_expr_tree(texpr, ctx));
621
70.0k
        ctxs.push_back(ctx);
622
70.0k
    }
623
28.1k
    return Status::OK();
624
28.1k
}
625
626
Status VExpr::check_expr_output_type(const VExprContextSPtrs& ctxs,
627
24.0k
                                     const RowDescriptor& output_row_desc) {
628
24.0k
    if (ctxs.empty()) {
629
2
        return Status::OK();
630
2
    }
631
24.0k
    auto name_and_types = VectorizedUtils::create_name_and_data_types(output_row_desc);
632
24.0k
    if (ctxs.size() != name_and_types.size()) {
633
0
        return Status::InternalError(
634
0
                "output type size not match expr size {} , expected output size {} ", ctxs.size(),
635
0
                name_and_types.size());
636
0
    }
637
65.9k
    auto check_type_can_be_converted = [](DataTypePtr& from, DataTypePtr& to) -> bool {
638
65.9k
        if (to->equals_ignore_precision(*from)) {
639
65.9k
            return true;
640
65.9k
        }
641
0
        if (to->is_nullable() && !from->is_nullable()) {
642
0
            return remove_nullable(to)->equals_ignore_precision(*from);
643
0
        }
644
0
        return false;
645
0
    };
646
89.9k
    for (int i = 0; i < ctxs.size(); i++) {
647
65.9k
        auto real_expr_type = get_data_type_with_default_argument(ctxs[i]->root()->data_type());
648
65.9k
        auto&& [name, expected_type] = name_and_types[i];
649
65.9k
        if (!check_type_can_be_converted(real_expr_type, expected_type)) {
650
0
            return Status::InternalError(
651
0
                    "output type not match expr type, col name {} , expected type {} , real type "
652
0
                    "{}",
653
0
                    name, expected_type->get_name(), real_expr_type->get_name());
654
0
        }
655
65.9k
    }
656
24.0k
    return Status::OK();
657
24.0k
}
658
659
Status VExpr::prepare(const VExprContextSPtrs& ctxs, RuntimeState* state,
660
148k
                      const RowDescriptor& row_desc) {
661
258k
    for (auto ctx : ctxs) {
662
258k
        RETURN_IF_ERROR(ctx->prepare(state, row_desc));
663
258k
    }
664
148k
    return Status::OK();
665
148k
}
666
667
148k
Status VExpr::open(const VExprContextSPtrs& ctxs, RuntimeState* state) {
668
258k
    for (const auto& ctx : ctxs) {
669
258k
        RETURN_IF_ERROR(ctx->open(state));
670
258k
    }
671
148k
    return Status::OK();
672
148k
}
673
674
Status VExpr::clone_if_not_exists(const VExprContextSPtrs& ctxs, RuntimeState* state,
675
0
                                  VExprContextSPtrs& new_ctxs) {
676
0
    if (!new_ctxs.empty()) {
677
        // 'ctxs' was already cloned into '*new_ctxs', nothing to do.
678
0
        DCHECK_EQ(new_ctxs.size(), ctxs.size());
679
0
        for (auto& new_ctx : new_ctxs) {
680
0
            DCHECK(new_ctx->_is_clone);
681
0
        }
682
0
        return Status::OK();
683
0
    }
684
0
    new_ctxs.resize(ctxs.size());
685
0
    for (int i = 0; i < ctxs.size(); ++i) {
686
0
        RETURN_IF_ERROR(ctxs[i]->clone(state, new_ctxs[i]));
687
0
    }
688
0
    return Status::OK();
689
0
}
690
691
7
std::string VExpr::debug_string() const {
692
    // TODO: implement partial debug string for member vars
693
7
    std::stringstream out;
694
7
    out << " type=" << _data_type->get_name();
695
696
7
    if (!_children.empty()) {
697
0
        out << " children=" << debug_string(_children);
698
0
    }
699
700
7
    return out.str();
701
7
}
702
703
0
std::string VExpr::debug_string(const VExprSPtrs& exprs) {
704
0
    std::stringstream out;
705
0
    out << "[";
706
707
0
    for (int i = 0; i < exprs.size(); ++i) {
708
0
        out << (i == 0 ? "" : " ") << exprs[i]->debug_string();
709
0
    }
710
711
0
    out << "]";
712
0
    return out.str();
713
0
}
714
715
0
std::string VExpr::debug_string(const VExprContextSPtrs& ctxs) {
716
0
    VExprSPtrs exprs;
717
0
    for (const auto& ctx : ctxs) {
718
0
        exprs.push_back(ctx->root());
719
0
    }
720
0
    return debug_string(exprs);
721
0
}
722
723
530
bool VExpr::is_constant() const {
724
530
    return std::all_of(_children.begin(), _children.end(),
725
530
                       [](const VExprSPtr& expr) { return expr->is_constant(); });
726
530
}
727
728
Status VExpr::get_const_col(VExprContext* context,
729
258k
                            std::shared_ptr<ColumnPtrWrapper>* column_wrapper) {
730
258k
    if (!is_constant()) {
731
258k
        return Status::OK();
732
258k
    }
733
734
112
    if (_constant_col != nullptr) {
735
27
        DCHECK(column_wrapper != nullptr);
736
27
        *column_wrapper = _constant_col;
737
27
        return Status::OK();
738
27
    }
739
740
85
    ColumnPtr result;
741
85
    RETURN_IF_ERROR(execute_column(context, nullptr, 1, result));
742
85
    _constant_col = std::make_shared<ColumnPtrWrapper>(result);
743
85
    if (column_wrapper != nullptr) {
744
0
        *column_wrapper = _constant_col;
745
0
    }
746
747
85
    return Status::OK();
748
85
}
749
750
79
void VExpr::register_function_context(RuntimeState* state, VExprContext* context) {
751
79
    std::vector<DataTypePtr> arg_types;
752
156
    for (auto& i : _children) {
753
156
        arg_types.push_back(i->data_type());
754
156
    }
755
756
79
    _fn_context_index = context->register_function_context(state, _data_type, arg_types);
757
79
}
758
759
Status VExpr::init_function_context(RuntimeState* state, VExprContext* context,
760
                                    FunctionContext::FunctionStateScope scope,
761
39
                                    const FunctionBasePtr& function) const {
762
39
    FunctionContext* fn_ctx = context->fn_context(_fn_context_index);
763
39
    if (scope == FunctionContext::FRAGMENT_LOCAL) {
764
27
        std::vector<std::shared_ptr<ColumnPtrWrapper>> constant_cols;
765
52
        for (auto c : _children) {
766
52
            std::shared_ptr<ColumnPtrWrapper> const_col;
767
52
            RETURN_IF_ERROR(c->get_const_col(context, &const_col));
768
52
            constant_cols.push_back(const_col);
769
52
        }
770
27
        fn_ctx->set_constant_cols(constant_cols);
771
27
    }
772
773
39
    if (scope == FunctionContext::FRAGMENT_LOCAL) {
774
27
        RETURN_IF_ERROR(function->open(fn_ctx, FunctionContext::FRAGMENT_LOCAL));
775
27
    }
776
39
    RETURN_IF_ERROR(function->open(fn_ctx, FunctionContext::THREAD_LOCAL));
777
39
    return Status::OK();
778
39
}
779
780
void VExpr::close_function_context(VExprContext* context, FunctionContext::FunctionStateScope scope,
781
148
                                   const FunctionBasePtr& function) const {
782
148
    if (_fn_context_index != -1) {
783
41
        FunctionContext* fn_ctx = context->fn_context(_fn_context_index);
784
        // `close_function_context` is called in VExprContext's destructor so do not throw exceptions here.
785
41
        static_cast<void>(function->close(fn_ctx, FunctionContext::THREAD_LOCAL));
786
41
        if (scope == FunctionContext::FRAGMENT_LOCAL) {
787
29
            static_cast<void>(function->close(fn_ctx, FunctionContext::FRAGMENT_LOCAL));
788
29
        }
789
41
    }
790
148
}
791
792
0
Status VExpr::check_constant(const Block& block, ColumnNumbers arguments) const {
793
0
    if (is_constant() && !VectorizedUtils::all_arguments_are_constant(block, arguments)) {
794
0
        return Status::InternalError("const check failed, expr={}", debug_string());
795
0
    }
796
0
    return Status::OK();
797
0
}
798
799
0
ColumnPtr VExpr::get_result_from_const(size_t count) const {
800
0
    return ColumnConst::create(_constant_col->column_ptr, count);
801
0
}
802
803
Status VExpr::_evaluate_inverted_index(VExprContext* context, const FunctionBasePtr& function,
804
1
                                       uint32_t segment_num_rows) {
805
    // Pre-allocate vectors based on an estimated or known size
806
1
    std::vector<segment_v2::IndexIterator*> iterators;
807
1
    std::vector<vectorized::IndexFieldNameAndTypePair> data_type_with_names;
808
1
    std::vector<int> column_ids;
809
1
    vectorized::ColumnsWithTypeAndName arguments;
810
1
    VExprSPtrs children_exprs;
811
812
    // Reserve space to avoid multiple reallocations
813
1
    const size_t estimated_size = get_num_children();
814
1
    iterators.reserve(estimated_size);
815
1
    data_type_with_names.reserve(estimated_size);
816
1
    column_ids.reserve(estimated_size);
817
1
    children_exprs.reserve(estimated_size);
818
819
1
    auto index_context = context->get_index_context();
820
821
    // if child is cast expr, we need to ensure target data type is the same with storage data type.
822
    // or they are all string type
823
    // and if data type is array, we need to get the nested data type to ensure that.
824
2
    for (const auto& child : children()) {
825
2
        if (child->node_type() == TExprNodeType::CAST_EXPR) {
826
1
            auto* cast_expr = assert_cast<VCastExpr*>(child.get());
827
1
            DCHECK_EQ(cast_expr->get_num_children(), 1);
828
1
            if (cast_expr->get_child(0)->is_slot_ref()) {
829
0
                auto* column_slot_ref = assert_cast<VSlotRef*>(cast_expr->get_child(0).get());
830
0
                auto column_id = column_slot_ref->column_id();
831
0
                const auto* storage_name_type =
832
0
                        context->get_index_context()->get_storage_name_and_type_by_column_id(
833
0
                                column_id);
834
0
                auto storage_type = remove_nullable(storage_name_type->second);
835
0
                auto target_type = remove_nullable(cast_expr->get_target_type());
836
0
                auto origin_primitive_type = storage_type->get_primitive_type();
837
0
                auto target_primitive_type = target_type->get_primitive_type();
838
0
                if (is_complex_type(storage_type->get_primitive_type())) {
839
0
                    if (storage_type->get_primitive_type() == TYPE_ARRAY &&
840
0
                        target_type->get_primitive_type() == TYPE_ARRAY) {
841
0
                        auto nested_storage_type =
842
0
                                (assert_cast<const DataTypeArray*>(storage_type.get()))
843
0
                                        ->get_nested_type();
844
0
                        origin_primitive_type = nested_storage_type->get_primitive_type();
845
0
                        auto nested_target_type =
846
0
                                (assert_cast<const DataTypeArray*>(target_type.get()))
847
0
                                        ->get_nested_type();
848
0
                        target_primitive_type = nested_target_type->get_primitive_type();
849
0
                    } else {
850
0
                        continue;
851
0
                    }
852
0
                }
853
0
                if (origin_primitive_type != TYPE_VARIANT &&
854
0
                    (storage_type->equals(*target_type) ||
855
0
                     (is_string_type(target_primitive_type) &&
856
0
                      is_string_type(origin_primitive_type)))) {
857
0
                    children_exprs.emplace_back(expr_without_cast(child));
858
0
                }
859
1
            } else {
860
1
                return Status::OK(); // for example: cast("abc") as ipv4 case
861
1
            }
862
1
        } else {
863
1
            children_exprs.emplace_back(child);
864
1
        }
865
2
    }
866
867
0
    if (children_exprs.empty()) {
868
0
        return Status::OK(); // Early exit if no children to process
869
0
    }
870
871
0
    for (const auto& child : children_exprs) {
872
0
        if (child->is_slot_ref()) {
873
0
            auto* column_slot_ref = assert_cast<VSlotRef*>(child.get());
874
0
            auto column_id = column_slot_ref->column_id();
875
0
            auto* iter = context->get_index_context()->get_inverted_index_iterator_by_column_id(
876
0
                    column_id);
877
            //column does not have inverted index
878
0
            if (iter == nullptr) {
879
0
                continue;
880
0
            }
881
0
            const auto* storage_name_type =
882
0
                    context->get_index_context()->get_storage_name_and_type_by_column_id(column_id);
883
0
            if (storage_name_type == nullptr) {
884
0
                auto err_msg = fmt::format(
885
0
                        "storage_name_type cannot be found for column {} while in {} "
886
0
                        "evaluate_inverted_index",
887
0
                        column_id, expr_name());
888
0
                LOG(ERROR) << err_msg;
889
0
                return Status::InternalError(err_msg);
890
0
            }
891
0
            iterators.emplace_back(iter);
892
0
            data_type_with_names.emplace_back(*storage_name_type);
893
0
            column_ids.emplace_back(column_id);
894
0
        } else if (child->is_literal()) {
895
0
            auto* column_literal = assert_cast<VLiteral*>(child.get());
896
0
            arguments.emplace_back(column_literal->get_column_ptr(),
897
0
                                   column_literal->get_data_type(), column_literal->expr_name());
898
0
        } else if (child->can_push_down_to_index()) {
899
0
            RETURN_IF_ERROR(child->evaluate_inverted_index(context, segment_num_rows));
900
0
        } else {
901
0
            return Status::OK(); // others cases
902
0
        }
903
0
    }
904
905
    // is null or is not null has no arguments
906
0
    if (iterators.empty() || (arguments.empty() && !(function->get_name() == "is_not_null_pred" ||
907
0
                                                     function->get_name() == "is_null_pred"))) {
908
0
        return Status::OK(); // Nothing to evaluate or no literals to compare against
909
0
    }
910
911
0
    const InvertedIndexAnalyzerCtx* analyzer_ctx = nullptr;
912
0
    if (auto index_ctx = context->get_index_context(); index_ctx != nullptr) {
913
0
        analyzer_ctx = index_ctx->get_analyzer_ctx_for_expr(this);
914
0
    }
915
916
0
    auto result_bitmap = segment_v2::InvertedIndexResultBitmap();
917
0
    auto res = function->evaluate_inverted_index(arguments, data_type_with_names, iterators,
918
0
                                                 segment_num_rows, analyzer_ctx, result_bitmap);
919
0
    if (!res.ok()) {
920
0
        return res;
921
0
    }
922
0
    if (!result_bitmap.is_empty()) {
923
0
        index_context->set_index_result_for_expr(this, result_bitmap);
924
0
        for (int column_id : column_ids) {
925
0
            index_context->set_true_for_index_status(this, column_id);
926
0
        }
927
0
    }
928
0
    return Status::OK();
929
0
}
930
931
0
size_t VExpr::estimate_memory(const size_t rows) {
932
0
    if (is_const_and_have_executed()) {
933
0
        return 0;
934
0
    }
935
936
0
    size_t estimate_size = 0;
937
0
    for (auto& child : _children) {
938
0
        estimate_size += child->estimate_memory(rows);
939
0
    }
940
941
0
    if (_data_type->have_maximum_size_of_value()) {
942
0
        estimate_size += rows * _data_type->get_size_of_value_in_memory();
943
0
    } else {
944
0
        estimate_size += rows * 64; /// TODO: need a more reasonable value
945
0
    }
946
0
    return estimate_size;
947
0
}
948
949
11
bool VExpr::fast_execute(VExprContext* context, ColumnPtr& result_column) const {
950
11
    if (context->get_index_context() &&
951
11
        context->get_index_context()->get_index_result_column().contains(this)) {
952
        // prepare a column to save result
953
1
        result_column = context->get_index_context()->get_index_result_column()[this];
954
1
        if (_data_type->is_nullable()) {
955
1
            result_column = make_nullable(result_column);
956
1
        }
957
1
        return true;
958
1
    }
959
10
    return false;
960
11
}
961
962
0
bool VExpr::equals(const VExpr& other) {
963
0
    return false;
964
0
}
965
966
Status VExpr::evaluate_ann_range_search(
967
        const segment_v2::AnnRangeSearchRuntime& runtime,
968
        const std::vector<std::unique_ptr<segment_v2::IndexIterator>>& index_iterators,
969
        const std::vector<ColumnId>& idx_to_cid,
970
        const std::vector<std::unique_ptr<segment_v2::ColumnIterator>>& column_iterators,
971
0
        roaring::Roaring& row_bitmap, AnnIndexStats& ann_index_stats) {
972
0
    return Status::OK();
973
0
}
974
975
void VExpr::prepare_ann_range_search(const doris::VectorSearchUserParams& params,
976
                                     segment_v2::AnnRangeSearchRuntime& range_search_runtime,
977
0
                                     bool& suitable_for_ann_index) {
978
0
    if (!suitable_for_ann_index) {
979
0
        return;
980
0
    }
981
0
    for (auto& child : _children) {
982
0
        child->prepare_ann_range_search(params, range_search_runtime, suitable_for_ann_index);
983
0
        if (!suitable_for_ann_index) {
984
0
            return;
985
0
        }
986
0
    }
987
0
}
988
989
2
bool VExpr::ann_range_search_executedd() {
990
2
    return _has_been_executed;
991
2
}
992
993
2
bool VExpr::ann_dist_is_fulfilled() const {
994
2
    return _virtual_column_is_fulfilled;
995
2
}
996
997
#include "common/compile_check_end.h"
998
} // namespace doris::vectorized