Coverage Report

Created: 2026-07-07 22:21

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