Coverage Report

Created: 2026-04-16 15:58

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/exprs/vtopn_pred.h
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
#pragma once
19
20
#include <gen_cpp/types.pb.h>
21
22
#include <utility>
23
24
#include "core/block/column_numbers.h"
25
#include "core/data_type/data_type.h"
26
#include "exec/common/util.hpp"
27
#include "exprs/function/simple_function_factory.h"
28
#include "exprs/vectorized_fn_call.h"
29
#include "exprs/vexpr.h"
30
#include "exprs/vslot_ref.h"
31
#include "runtime/query_context.h"
32
#include "runtime/runtime_predicate.h"
33
#include "runtime/runtime_state.h"
34
35
namespace doris {
36
37
// only used for dynamic topn filter
38
class VTopNPred : public VExpr {
39
    ENABLE_FACTORY_CREATOR(VTopNPred);
40
41
public:
42
    VTopNPred(const TExprNode& node, int source_node_id, VExprContextSPtr target_ctx)
43
0
            : VExpr(node),
44
0
              _source_node_id(source_node_id),
45
0
              _expr_name(fmt::format("VTopNPred(source_node_id={})", _source_node_id)),
46
0
              _target_ctx(std::move(target_ctx)) {}
47
0
    bool is_topn_filter() const override { return true; }
48
49
0
    static Status create_vtopn_pred(const TExpr& target_expr, int source_node_id, VExprSPtr& expr) {
50
0
        VExprContextSPtr target_ctx;
51
0
        RETURN_IF_ERROR(VExpr::create_expr_tree(target_expr, target_ctx));
52
53
0
        TExprNode node;
54
0
        node.__set_node_type(TExprNodeType::FUNCTION_CALL);
55
0
        node.__set_type(create_type_desc(PrimitiveType::TYPE_BOOLEAN));
56
0
        node.__set_is_nullable(target_ctx->root()->is_nullable());
57
0
        expr = VTopNPred::create_shared(node, source_node_id, target_ctx);
58
59
0
        DCHECK(target_ctx->root() != nullptr);
60
0
        expr->add_child(target_ctx->root());
61
62
0
        return Status::OK();
63
0
    }
64
65
0
    int source_node_id() const { return _source_node_id; }
66
67
0
    Status prepare(RuntimeState* state, const RowDescriptor& desc, VExprContext* context) override {
68
0
        _predicate = &state->get_query_ctx()->get_runtime_predicate(_source_node_id);
69
0
        RETURN_IF_ERROR_OR_PREPARED(VExpr::prepare(state, desc, context));
70
71
0
        ColumnsWithTypeAndName argument_template;
72
0
        argument_template.emplace_back(nullptr, _children[0]->data_type(),
73
0
                                       _children[0]->expr_name());
74
0
        argument_template.emplace_back(nullptr, _children[0]->data_type(), "topn value");
75
76
0
        _function = SimpleFunctionFactory::instance().get_function(
77
0
                _predicate->is_asc() ? "le" : "ge", argument_template, _data_type, {},
78
0
                state->be_exec_version());
79
0
        if (!_function) {
80
0
            return Status::InternalError("get function failed");
81
0
        }
82
0
        return Status::OK();
83
0
    }
84
85
    Status execute_column(VExprContext* context, const Block* block, Selector* selector,
86
0
                          size_t count, ColumnPtr& result_column) const override {
87
0
        if (!_predicate->has_value()) {
88
0
            result_column = create_always_true_column(count, _data_type->is_nullable());
89
0
            return Status::OK();
90
0
        }
91
92
0
        Block temp_block;
93
94
        // slot
95
0
        ColumnPtr slot_column;
96
0
        RETURN_IF_ERROR(_children[0]->execute_column(context, block, selector, count, slot_column));
97
0
        auto slot_type = _children[0]->execute_type(block);
98
0
        temp_block.insert({slot_column, slot_type, _children[0]->expr_name()});
99
0
        int slot_id = 0;
100
101
        // topn value
102
0
        Field field = _predicate->get_value();
103
0
        auto column_ptr = _children[0]->data_type()->create_column_const(1, field);
104
0
        int topn_value_id = VExpr::insert_param(&temp_block,
105
0
                                                {column_ptr, _children[0]->data_type(), _expr_name},
106
0
                                                std::max(count, column_ptr->size()));
107
108
        // if error(slot_id == -1), will return.
109
0
        ColumnNumbers arguments = {static_cast<uint32_t>(slot_id),
110
0
                                   static_cast<uint32_t>(topn_value_id)};
111
112
0
        uint32_t num_columns_without_result = temp_block.columns();
113
        // prepare a column to save result
114
0
        temp_block.insert({nullptr, _data_type, _expr_name});
115
116
0
        RETURN_IF_ERROR(_function->execute(nullptr, temp_block, arguments,
117
0
                                           num_columns_without_result, temp_block.rows()));
118
0
        result_column = std::move(temp_block.get_by_position(num_columns_without_result).column);
119
0
        if (is_nullable() && _predicate->nulls_first()) {
120
            // null values ​​are always not filtered
121
0
            change_null_to_true(result_column->assume_mutable());
122
0
        }
123
0
        DCHECK_EQ(result_column->size(), count);
124
0
        return Status::OK();
125
0
    }
126
127
0
    const std::string& expr_name() const override { return _expr_name; }
128
129
    // only used in external table (for min-max filter). get `slot > xxx`, not `function(slot) > xxx`.
130
0
    bool get_binary_expr(VExprSPtr& new_root) const {
131
0
        if (!get_child(0)->is_slot_ref()) {
132
            // top rf maybe is `xxx order by abs(column) limit xxx`.
133
0
            return false;
134
0
        }
135
136
0
        if (!_predicate->has_value()) {
137
0
            return false;
138
0
        }
139
140
0
        auto* slot_ref = assert_cast<VSlotRef*>(get_child(0).get());
141
0
        auto slot_data_type = remove_nullable(slot_ref->data_type());
142
0
        {
143
0
            TFunction fn;
144
0
            TFunctionName fn_name;
145
0
            fn_name.__set_db_name("");
146
0
            fn_name.__set_function_name(_predicate->is_asc() ? "le" : "ge");
147
0
            fn.__set_name(fn_name);
148
0
            fn.__set_binary_type(TFunctionBinaryType::BUILTIN);
149
0
            std::vector<TTypeDesc> arg_types;
150
0
            arg_types.push_back(create_type_desc(slot_data_type->get_primitive_type(),
151
0
                                                 slot_data_type->get_precision(),
152
0
                                                 slot_data_type->get_scale()));
153
154
0
            arg_types.push_back(create_type_desc(slot_data_type->get_primitive_type(),
155
0
                                                 slot_data_type->get_precision(),
156
0
                                                 slot_data_type->get_scale()));
157
0
            fn.__set_arg_types(arg_types);
158
0
            fn.__set_ret_type(create_type_desc(PrimitiveType::TYPE_BOOLEAN));
159
0
            fn.__set_has_var_args(false);
160
161
0
            TExprNode texpr_node;
162
0
            texpr_node.__set_type(create_type_desc(PrimitiveType::TYPE_BOOLEAN));
163
0
            texpr_node.__set_node_type(TExprNodeType::BINARY_PRED);
164
0
            texpr_node.__set_opcode(_predicate->is_asc() ? TExprOpcode::LE : TExprOpcode::GE);
165
0
            texpr_node.__set_fn(fn);
166
0
            texpr_node.__set_num_children(2);
167
0
            texpr_node.__set_is_nullable(is_nullable());
168
0
            new_root = VectorizedFnCall::create_shared(texpr_node);
169
0
        }
170
171
0
        {
172
            // add slot
173
0
            new_root->add_child(children().at(0));
174
0
        }
175
        // add Literal
176
0
        {
177
0
            Field field = _predicate->get_value();
178
0
            TExprNode node = create_texpr_node_from(field, slot_data_type->get_primitive_type(),
179
0
                                                    slot_data_type->get_precision(),
180
0
                                                    slot_data_type->get_scale());
181
0
            new_root->add_child(VLiteral::create_shared(node));
182
0
        }
183
184
        // Since the normal greater than or less than relationship does not consider the relationship of null values, the generated `col >=/<= xxx OR col is null.`
185
0
        if (_predicate->nulls_first()) {
186
0
            VExprSPtr col_is_null_node;
187
0
            {
188
0
                TFunction fn;
189
0
                TFunctionName fn_name;
190
0
                fn_name.__set_db_name("");
191
0
                fn_name.__set_function_name("is_null_pred");
192
0
                fn.__set_name(fn_name);
193
0
                fn.__set_binary_type(TFunctionBinaryType::BUILTIN);
194
0
                std::vector<TTypeDesc> arg_types;
195
0
                arg_types.push_back(create_type_desc(slot_data_type->get_primitive_type(),
196
0
                                                     slot_data_type->get_precision(),
197
0
                                                     slot_data_type->get_scale()));
198
0
                fn.__set_arg_types(arg_types);
199
0
                fn.__set_ret_type(create_type_desc(PrimitiveType::TYPE_BOOLEAN));
200
0
                fn.__set_has_var_args(false);
201
202
0
                TExprNode texpr_node;
203
0
                texpr_node.__set_type(create_type_desc(PrimitiveType::TYPE_BOOLEAN));
204
0
                texpr_node.__set_node_type(TExprNodeType::FUNCTION_CALL);
205
0
                texpr_node.__set_fn(fn);
206
0
                texpr_node.__set_num_children(1);
207
0
                col_is_null_node = VectorizedFnCall::create_shared(texpr_node);
208
209
                // add slot.
210
0
                col_is_null_node->add_child(children().at(0));
211
0
            }
212
213
0
            VExprSPtr or_node;
214
0
            {
215
0
                TExprNode texpr_node;
216
0
                texpr_node.__set_type(create_type_desc(PrimitiveType::TYPE_BOOLEAN));
217
0
                texpr_node.__set_node_type(TExprNodeType::COMPOUND_PRED);
218
0
                texpr_node.__set_opcode(TExprOpcode::COMPOUND_OR);
219
0
                texpr_node.__set_num_children(2);
220
0
                or_node = VectorizedFnCall::create_shared(texpr_node);
221
0
            }
222
223
0
            or_node->add_child(col_is_null_node);
224
0
            or_node->add_child(new_root);
225
0
            new_root = or_node;
226
0
        }
227
228
0
        return true;
229
0
    }
230
231
private:
232
    int _source_node_id;
233
    std::string _expr_name;
234
    RuntimePredicate* _predicate = nullptr;
235
    FunctionBasePtr _function;
236
    VExprContextSPtr _target_ctx;
237
};
238
239
} // namespace doris