ClickHouse

Форк
0
/
throwIf.cpp 
164 строки · 6.6 Кб
1
#include <Functions/IFunction.h>
2
#include <Functions/FunctionFactory.h>
3
#include <Functions/FunctionHelpers.h>
4
#include <Columns/ColumnString.h>
5
#include <Columns/ColumnsNumber.h>
6
#include <Columns/ColumnsCommon.h>
7
#include <Common/ErrorCodes.h>
8
#include <DataTypes/DataTypesNumber.h>
9
#include <IO/WriteHelpers.h>
10
#include <Interpreters/Context.h>
11

12
namespace DB
13
{
14
namespace ErrorCodes
15
{
16
    extern const int ILLEGAL_COLUMN;
17
    extern const int ILLEGAL_TYPE_OF_ARGUMENT;
18
    extern const int NUMBER_OF_ARGUMENTS_DOESNT_MATCH;
19
    extern const int FUNCTION_THROW_IF_VALUE_IS_NON_ZERO;
20
}
21

22
namespace
23
{
24

25
/// Throw an exception if the argument is non zero.
26
class FunctionThrowIf : public IFunction
27
{
28
public:
29
    static constexpr auto name = "throwIf";
30

31
    static FunctionPtr create(ContextPtr context) { return std::make_shared<FunctionThrowIf>(context); }
32

33
    explicit FunctionThrowIf(ContextPtr context_) : allow_custom_error_code_argument(context_->getSettingsRef().allow_custom_error_code_in_throwif) {}
34
    String getName() const override { return name; }
35
    bool isVariadic() const override { return true; }
36
    bool isSuitableForShortCircuitArgumentsExecution(const DataTypesWithConstInfo & /*arguments*/) const override { return true; }
37
    size_t getNumberOfArguments() const override { return 0; }
38

39
    DataTypePtr getReturnTypeImpl(const DataTypes & arguments) const override
40
    {
41
        const size_t number_of_arguments = arguments.size();
42

43
        if (number_of_arguments < 1 || number_of_arguments > (allow_custom_error_code_argument ? 3 : 2))
44
            throw Exception(ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH,
45
                "Number of arguments for function {} doesn't match: passed {}, should be {}",
46
                getName(), number_of_arguments, allow_custom_error_code_argument ? "1 or 2 or 3" : "1 or 2");
47

48
        if (!isNativeNumber(arguments[0]))
49
            throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT,
50
                "First argument of function {} must be a number (passed: {})", getName(), arguments[0]->getName());
51

52
        if (number_of_arguments > 1 && !isString(arguments[1]))
53
            throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT,
54
                "Second argument of function {} must be a string (passed: {})", getName(), arguments[1]->getName());
55

56
        if (allow_custom_error_code_argument && number_of_arguments > 2)
57
        {
58
            WhichDataType which(arguments[2]);
59
            if (!(which.isInt8() || which.isInt16() || which.isInt32()))
60
                throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT,
61
                    "Third argument of function {} must be Int8, Int16 or Int32 (passed: {})", getName(), arguments[2]->getName());
62
        }
63

64

65
        return std::make_shared<DataTypeUInt8>();
66
    }
67

68
    bool useDefaultImplementationForConstants() const override { return false; }
69
    ColumnNumbers getArgumentsThatAreAlwaysConstant() const override { return {1, 2}; }
70

71
    /** Prevent constant folding for FunctionThrowIf because for short circuit evaluation
72
      * it is unsafe to evaluate this function during DAG analysis.
73
      */
74
    bool isSuitableForConstantFolding() const override { return false; }
75

76
    ColumnPtr executeImpl(const ColumnsWithTypeAndName & arguments, const DataTypePtr & result_type, size_t input_rows_count) const override
77
    {
78
        if (input_rows_count == 0)
79
            return result_type->createColumn();
80

81
        std::optional<String> custom_message;
82
        if (arguments.size() == 2)
83
        {
84
            const auto * message_column = checkAndGetColumnConst<ColumnString>(arguments[1].column.get());
85
            if (!message_column)
86
                throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Second argument for function {} must be constant String", getName());
87

88
            custom_message = message_column->getValue<String>();
89
        }
90

91
        std::optional<ErrorCodes::ErrorCode> custom_error_code;
92
        if (allow_custom_error_code_argument && arguments.size() == 3)
93
        {
94
            if (!isColumnConst(*(arguments[2].column)))
95
                throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Third argument for function {} must be constant number", getName());
96

97
            custom_error_code = arguments[2].column->getInt(0);
98
        }
99

100
        auto first_argument_column = arguments.front().column;
101
        const auto * in = first_argument_column.get();
102

103
        ColumnPtr res;
104
        if (!((res = execute<UInt8>(in, custom_message, custom_error_code))
105
            || (res = execute<UInt16>(in, custom_message, custom_error_code))
106
            || (res = execute<UInt32>(in, custom_message, custom_error_code))
107
            || (res = execute<UInt64>(in, custom_message, custom_error_code))
108
            || (res = execute<Int8>(in, custom_message, custom_error_code))
109
            || (res = execute<Int16>(in, custom_message, custom_error_code))
110
            || (res = execute<Int32>(in, custom_message, custom_error_code))
111
            || (res = execute<Int64>(in, custom_message, custom_error_code))
112
            || (res = execute<Float32>(in, custom_message, custom_error_code))
113
            || (res = execute<Float64>(in, custom_message, custom_error_code))))
114
        {
115
            throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of first argument of function {}", in->getName(), getName());
116
        }
117

118
        return res;
119
    }
120

121
private:
122
    template <typename T>
123
    ColumnPtr execute(const IColumn * in_untyped, const std::optional<String> & message, const std::optional<ErrorCodes::ErrorCode> & error_code) const
124
    {
125
        const auto * in = checkAndGetColumn<ColumnVector<T>>(in_untyped);
126

127
        if (!in)
128
            in = checkAndGetColumnConstData<ColumnVector<T>>(in_untyped);
129

130
        if (in)
131
        {
132
            const auto & in_data = in->getData();
133
            if (!memoryIsZero(in_data.data(), 0, in_data.size() * sizeof(in_data[0])))
134
            {
135
                if (message.has_value())
136
                    throw Exception::createRuntime(
137
                        error_code.value_or(ErrorCodes::FUNCTION_THROW_IF_VALUE_IS_NON_ZERO),
138
                        *message);
139
                else
140
                    throw Exception(
141
                        error_code.value_or(ErrorCodes::FUNCTION_THROW_IF_VALUE_IS_NON_ZERO),
142
                        "Value passed to '{}' function is non-zero", getName());
143
            }
144

145
            size_t result_size = in_untyped->size();
146

147
            /// We return non constant to avoid constant folding.
148
            return ColumnUInt8::create(result_size, 0);
149
        }
150

151
        return nullptr;
152
    }
153

154
    bool allow_custom_error_code_argument;
155
};
156

157
}
158

159
REGISTER_FUNCTION(ThrowIf)
160
{
161
    factory.registerFunction<FunctionThrowIf>();
162
}
163

164
}
165

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.