ClickHouse

Форк
0
/
countDigits.cpp 
156 строк · 4.8 Кб
1
#include <Functions/IFunction.h>
2
#include <Functions/FunctionFactory.h>
3
#include <Functions/FunctionHelpers.h>
4
#include <DataTypes/DataTypesNumber.h>
5
#include <Columns/ColumnsNumber.h>
6
#include <Columns/ColumnDecimal.h>
7
#include <base/extended_types.h>
8
#include <base/itoa.h>
9

10

11
namespace DB
12
{
13

14
namespace ErrorCodes
15
{
16
    extern const int ILLEGAL_TYPE_OF_ARGUMENT;
17
    extern const int ILLEGAL_COLUMN;
18
}
19

20
namespace
21
{
22

23
template <typename T>
24
int digits10(T x)
25
{
26
    if (x < 10ULL)
27
        return 1;
28
    if (x < 100ULL)
29
        return 2;
30
    if (x < 1000ULL)
31
        return 3;
32

33
    if (x < 1000000000000ULL)
34
    {
35
        if (x < 100000000ULL)
36
        {
37
            if (x < 1000000ULL)
38
            {
39
                if (x < 10000ULL)
40
                    return 4;
41
                else
42
                    return 5 + (x >= 100000ULL);
43
            }
44

45
            return 7 + (x >= 10000000ULL);
46
        }
47

48
        if (x < 10000000000ULL)
49
            return 9 + (x >= 1000000000ULL);
50

51
        return 11 + (x >= 100000000000ULL);
52
    }
53

54
    return 12 + digits10(x / 1000000000000ULL);
55
}
56

57
/// Returns number of decimal digits you need to represent the value.
58
/// For Decimal values takes in account their scales: calculates result over underlying int type which is (value * scale).
59
/// countDigits(42) = 2, countDigits(42.000) = 5, countDigits(0.04200) = 4.
60
/// I.e. you may check decimal overflow for Decimal64 with 'countDecimal(x) > 18'. It's a slow variant of isDecimalOverflow().
61
class FunctionCountDigits : public IFunction
62
{
63
public:
64
    static constexpr auto name = "countDigits";
65

66
    static FunctionPtr create(ContextPtr)
67
    {
68
        return std::make_shared<FunctionCountDigits>();
69
    }
70

71
    String getName() const override { return name; }
72
    bool useDefaultImplementationForConstants() const override { return true; }
73
    size_t getNumberOfArguments() const override { return 1; }
74
    bool isSuitableForShortCircuitArgumentsExecution(const DataTypesWithConstInfo & /*arguments*/) const override { return false; }
75

76
    DataTypePtr getReturnTypeImpl(const DataTypes & arguments) const override
77
    {
78
        WhichDataType which_first(arguments[0]->getTypeId());
79

80
        if (!which_first.isInt() && !which_first.isUInt() && !which_first.isDecimal())
81
            throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, "Illegal type {} of argument of function {}",
82
                            arguments[0]->getName(), getName());
83

84
        return std::make_shared<DataTypeUInt8>(); /// Up to 255 decimal digits.
85
    }
86

87
    ColumnPtr executeImpl(const ColumnsWithTypeAndName & arguments, const DataTypePtr &, size_t input_rows_count) const override
88
    {
89
        const auto & src_column = arguments[0];
90
        if (!src_column.column)
91
            throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, "Illegal column while execute function {}", getName());
92

93
        auto result_column = ColumnUInt8::create();
94

95
        auto call = [&](const auto & types) -> bool
96
        {
97
            using Types = std::decay_t<decltype(types)>;
98
            using Type = typename Types::RightType;
99
            using ColVecType = ColumnVectorOrDecimal<Type>;
100

101
            if (const ColVecType * col_vec = checkAndGetColumn<ColVecType>(src_column.column.get()))
102
            {
103
                execute<Type>(*col_vec, *result_column, input_rows_count);
104
                return true;
105
            }
106

107
            throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, "Illegal column while execute function {}", getName());
108
        };
109

110
        TypeIndex dec_type_idx = src_column.type->getTypeId();
111
        if (!callOnBasicType<void, true, false, true, false>(dec_type_idx, call))
112
            throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Wrong call for {} with {}", getName(), src_column.type->getName());
113

114
        return result_column;
115
    }
116

117
private:
118
    template <typename T, typename ColVecType>
119
    static void execute(const ColVecType & col, ColumnUInt8 & result_column, size_t rows_count)
120
    {
121
        using NativeT = make_unsigned_t<NativeType<T>>;
122

123
        const auto & src_data = col.getData();
124
        auto & dst_data = result_column.getData();
125
        dst_data.resize(rows_count);
126

127
        for (size_t i = 0; i < rows_count; ++i)
128
        {
129
            if constexpr (is_decimal<T>)
130
            {
131
                auto value = src_data[i].value;
132
                if (unlikely(value < 0))
133
                    dst_data[i] = digits10<NativeT>(-static_cast<NativeT>(value));
134
                else
135
                    dst_data[i] = digits10<NativeT>(value);
136
            }
137
            else
138
            {
139
                auto value = src_data[i];
140
                if (unlikely(value < 0))
141
                    dst_data[i] = digits10<NativeT>(-static_cast<NativeT>(value));
142
                else
143
                    dst_data[i] = digits10<NativeT>(value);
144
            }
145
        }
146
    }
147
};
148

149
}
150

151
REGISTER_FUNCTION(CountDigits)
152
{
153
    factory.registerFunction<FunctionCountDigits>();
154
}
155

156
}
157

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

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

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

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