Coverage Report

Created: 2025-09-16 20:17

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