Coverage Report

Created: 2026-04-14 13:01

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/exprs/function/random.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 <fmt/format.h>
19
#include <glog/logging.h>
20
21
#include <algorithm>
22
#include <boost/iterator/iterator_facade.hpp>
23
#include <cstdint>
24
#include <cstdlib>
25
#include <memory>
26
#include <random>
27
#include <utility>
28
29
#include "common/status.h"
30
#include "core/assert_cast.h"
31
#include "core/block/block.h"
32
#include "core/block/column_numbers.h"
33
#include "core/column/column.h"
34
#include "core/column/column_vector.h"
35
#include "core/data_type/data_type_number.h"
36
#include "core/types.h"
37
#include "exprs/aggregate/aggregate_function.h"
38
#include "exprs/function/function.h"
39
#include "exprs/function/simple_function_factory.h"
40
#include "exprs/function_context.h"
41
42
namespace doris {
43
44
class Random : public IFunction {
45
public:
46
    static constexpr auto name = "random";
47
48
261
    static FunctionPtr create() { return std::make_shared<Random>(); }
49
50
0
    String get_name() const override { return name; }
51
52
1.33k
    bool use_default_implementation_for_constants() const override { return false; }
53
54
0
    size_t get_number_of_arguments() const override { return 0; }
55
56
253
    bool is_variadic() const override { return true; }
57
58
252
    DataTypePtr get_return_type_impl(const DataTypes& arguments) const override {
59
252
        if (arguments.size() == 2) {
60
57
            return std::make_shared<DataTypeInt64>();
61
57
        }
62
195
        return std::make_shared<DataTypeFloat64>();
63
252
    }
64
65
2.58k
    Status open(FunctionContext* context, FunctionContext::FunctionStateScope scope) override {
66
2.58k
        std::shared_ptr<std::mt19937_64> generator(new std::mt19937_64());
67
2.58k
        context->set_function_state(scope, generator);
68
2.58k
        if (scope == FunctionContext::THREAD_LOCAL) {
69
2.33k
            if (context->get_num_args() == 1) {
70
                // This is a call to RandSeed, initialize the seed
71
42
                if (!context->is_col_constant(0)) {
72
0
                    return Status::InvalidArgument("The param of rand function must be literal");
73
0
                }
74
42
                uint32_t seed = 0;
75
42
                if (!context->get_constant_col(0)->column_ptr->is_null_at(0)) {
76
42
                    seed = (uint32_t)(*context->get_constant_col(0)->column_ptr)[0]
77
42
                                   .get<TYPE_BIGINT>();
78
42
                }
79
42
                generator->seed(seed);
80
2.29k
            } else if (context->get_num_args() == 2) {
81
1.38k
                if (!context->is_col_constant(0) || !context->is_col_constant(1)) {
82
0
                    return Status::InvalidArgument("The param of rand function must be literal");
83
0
                }
84
1.38k
                generator->seed(std::random_device()());
85
1.38k
            } else { // zero args
86
912
                generator->seed(std::random_device()());
87
912
            }
88
2.33k
        }
89
90
2.58k
        return Status::OK();
91
2.58k
    }
92
93
    Status execute_impl(FunctionContext* context, Block& block, const ColumnNumbers& arguments,
94
400
                        uint32_t result, size_t input_rows_count) const override {
95
400
        if (arguments.size() == 2) {
96
168
            return _execute_int_range(context, block, arguments, result, input_rows_count);
97
168
        }
98
232
        return _execute_float(context, block, arguments, result, input_rows_count);
99
400
    }
100
101
private:
102
    static Status _execute_int_range(FunctionContext* context, Block& block,
103
                                     const ColumnNumbers& arguments, uint32_t result,
104
168
                                     size_t input_rows_count) {
105
168
        auto res_column = ColumnInt64::create(input_rows_count);
106
168
        auto& res_data = static_cast<ColumnInt64&>(*res_column).get_data();
107
108
168
        auto* generator = reinterpret_cast<std::mt19937_64*>(
109
168
                context->get_function_state(FunctionContext::THREAD_LOCAL));
110
168
        DCHECK(generator != nullptr);
111
112
        // checked in open()
113
168
        Int64 min = assert_cast<const ColumnInt64*>(
114
168
                            assert_cast<const ColumnConst*>(
115
168
                                    block.get_by_position(arguments[0]).column.get())
116
168
                                    ->get_data_column_ptr()
117
168
                                    .get())
118
168
                            ->get_element(0);
119
168
        Int64 max = assert_cast<const ColumnInt64*>(
120
168
                            assert_cast<const ColumnConst*>(
121
168
                                    block.get_by_position(arguments[1]).column.get())
122
168
                                    ->get_data_column_ptr()
123
168
                                    .get())
124
168
                            ->get_element(0);
125
168
        if (min >= max) {
126
1
            return Status::InvalidArgument(fmt::format(
127
1
                    "random's lower bound should less than upper bound, but got [{}, {})", min,
128
1
                    max));
129
1
        }
130
131
167
        std::uniform_int_distribution<int64_t> distribution(min, max);
132
538
        for (int i = 0; i < input_rows_count; i++) {
133
371
            res_data[i] = distribution(*generator);
134
371
        }
135
136
167
        block.replace_by_position(result, std::move(res_column));
137
167
        return Status::OK();
138
168
    }
139
140
    static Status _execute_float(FunctionContext* context, Block& block,
141
                                 const ColumnNumbers& arguments, uint32_t result,
142
232
                                 size_t input_rows_count) {
143
232
        static const double min = 0.0;
144
232
        static const double max = 1.0;
145
232
        auto res_column = ColumnFloat64::create(input_rows_count);
146
232
        auto& res_data = static_cast<ColumnFloat64&>(*res_column).get_data();
147
148
232
        auto* generator = reinterpret_cast<std::mt19937_64*>(
149
232
                context->get_function_state(FunctionContext::THREAD_LOCAL));
150
232
        DCHECK(generator != nullptr);
151
152
232
        std::uniform_real_distribution<double> distribution(min, max);
153
1.04M
        for (int i = 0; i < input_rows_count; i++) {
154
1.04M
            res_data[i] = distribution(*generator);
155
1.04M
        }
156
157
232
        block.replace_by_position(result, std::move(res_column));
158
232
        return Status::OK();
159
232
    }
160
};
161
162
8
void register_function_random(SimpleFunctionFactory& factory) {
163
8
    factory.register_function<Random>();
164
8
    factory.register_alias(Random::name, "rand");
165
8
}
166
} // namespace doris