ClickHouse

Форк
0
/
regexpQuoteMeta.cpp 
118 строк · 3.6 Кб
1
#include <Columns/ColumnString.h>
2
#include <DataTypes/DataTypeString.h>
3
#include <Functions/FunctionFactory.h>
4
#include <Functions/FunctionHelpers.h>
5
#include <base/find_symbols.h>
6

7

8
namespace DB
9
{
10
namespace ErrorCodes
11
{
12
    extern const int ILLEGAL_COLUMN;
13
    extern const int ILLEGAL_TYPE_OF_ARGUMENT;
14
}
15

16
namespace
17
{
18

19
class FunctionRegexpQuoteMeta : public IFunction
20
{
21
public:
22
    static constexpr auto name = "regexpQuoteMeta";
23

24
    static FunctionPtr create(ContextPtr)
25
    {
26
        return std::make_shared<FunctionRegexpQuoteMeta>();
27
    }
28

29
    String getName() const override
30
    {
31
        return name;
32
    }
33

34
    size_t getNumberOfArguments() const override
35
    {
36
        return 1;
37
    }
38

39
    bool useDefaultImplementationForConstants() const override
40
    {
41
        return true;
42
    }
43

44
    bool isSuitableForShortCircuitArgumentsExecution(const DataTypesWithConstInfo & /*arguments*/) const override { return true; }
45

46
    DataTypePtr getReturnTypeImpl(const ColumnsWithTypeAndName & arguments) const override
47
    {
48
        if (!WhichDataType(arguments[0].type).isString())
49
            throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, "Illegal type {} of 1 argument of function {}. Must be String.",
50
                arguments[0].type->getName(), getName());
51

52
        return std::make_shared<DataTypeString>();
53
    }
54

55
    ColumnPtr executeImpl(const ColumnsWithTypeAndName & arguments, const DataTypePtr &, size_t input_rows_count) const override
56
    {
57
        const ColumnPtr & column_string = arguments[0].column;
58
        const ColumnString * input = checkAndGetColumn<ColumnString>(column_string.get());
59

60
        if (!input)
61
            throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of first argument of function {}",
62
                arguments[0].column->getName(), getName());
63

64
        auto dst_column = ColumnString::create();
65
        auto & dst_data = dst_column->getChars();
66
        auto & dst_offsets = dst_column->getOffsets();
67

68
        dst_offsets.resize(input_rows_count);
69

70
        const ColumnString::Offsets & src_offsets = input->getOffsets();
71

72
        const auto * src_begin = reinterpret_cast<const char *>(input->getChars().data());
73
        const auto * src_pos = src_begin;
74

75
        for (size_t row_idx = 0; row_idx < input_rows_count; ++row_idx)
76
        {
77
            /// NOTE This implementation slightly differs from re2::RE2::QuoteMeta.
78
            /// It escapes zero byte as \0 instead of \x00
79
            ///  and it escapes only required characters.
80
            /// This is Ok. Look at comments in re2.cc
81

82
            const char * src_end = src_begin + src_offsets[row_idx] - 1;
83

84
            while (true)
85
            {
86
                const char * next_src_pos = find_first_symbols<'\0', '\\', '|', '(', ')', '^', '$', '.', '[', ']', '?', '*', '+', '{', ':', '-'>(src_pos, src_end);
87

88
                size_t bytes_to_copy = next_src_pos - src_pos;
89
                size_t old_dst_size = dst_data.size();
90
                dst_data.resize(old_dst_size + bytes_to_copy);
91
                memcpySmallAllowReadWriteOverflow15(dst_data.data() + old_dst_size, src_pos, bytes_to_copy);
92
                src_pos = next_src_pos + 1;
93

94
                if (next_src_pos == src_end)
95
                {
96
                    dst_data.emplace_back('\0');
97
                    break;
98
                }
99

100
                dst_data.emplace_back('\\');
101
                dst_data.emplace_back(*next_src_pos);
102
            }
103

104
            dst_offsets[row_idx] = dst_data.size();
105
        }
106

107
        return dst_column;
108
    }
109
};
110

111
}
112

113
REGISTER_FUNCTION(RegexpQuoteMeta)
114
{
115
    factory.registerFunction<FunctionRegexpQuoteMeta>();
116
}
117

118
}
119

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

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

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

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