Coverage Report

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