Coverage Report

Created: 2025-08-18 03:01

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