Coverage Report

Created: 2025-10-30 14:39

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