Coverage Report

Created: 2026-10-23 22:39

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/exprs/function/function_string_misc.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 <crc32c/crc32c.h>
19
#include <fmt/format.h>
20
#include <glog/logging.h>
21
#include <unicode/normalizer2.h>
22
#include <unicode/stringpiece.h>
23
#include <unicode/unistr.h>
24
25
#include <algorithm>
26
#include <bit>
27
#include <boost/locale.hpp>
28
#include <cctype>
29
#include <climits>
30
#include <cstddef>
31
#include <cstdint>
32
#include <cstdlib>
33
#include <cstring>
34
#include <format>
35
#include <iomanip>
36
#include <memory>
37
#include <random>
38
#include <sstream>
39
#include <string>
40
#include <string_view>
41
#include <unordered_map>
42
#include <utility>
43
#include <vector>
44
45
#include "common/compiler_util.h"
46
#include "common/exception.h"
47
#include "common/status.h"
48
#include "core/assert_cast.h"
49
#include "core/block/block.h"
50
#include "core/block/column_numbers.h"
51
#include "core/block/column_with_type_and_name.h"
52
#include "core/column/column.h"
53
#include "core/column/column_const.h"
54
#include "core/column/column_nullable.h"
55
#include "core/column/column_string.h"
56
#include "core/column/column_vector.h"
57
#include "core/data_type/data_type.h"
58
#include "core/data_type/data_type_nullable.h"
59
#include "core/data_type/data_type_number.h"
60
#include "core/data_type/data_type_string.h"
61
#include "core/data_type/define_primitive_type.h"
62
#include "core/memcpy_small.h"
63
#include "core/pod_array.h"
64
#include "core/string_ref.h"
65
#include "core/types.h"
66
#include "exec/common/hash_table/phmap_fwd_decl.h"
67
#include "exec/common/pinyin.h"
68
#include "exec/common/stringop_substring.h"
69
#include "exec/common/template_helpers.hpp"
70
#include "exprs/function/function.h"
71
#include "exprs/function/function_helpers.h"
72
#include "exprs/function/function_needs_to_handle_null.h"
73
#include "exprs/function_context.h"
74
#include "pugixml.hpp"
75
#include "util/hash_util.hpp"
76
#include "util/raw_value.h"
77
#include "util/simd/vstring_function.h"
78
#include "util/string_util.h"
79
#include "util/utf8_check.h"
80
81
#ifndef USE_LIBCPP
82
#include <memory_resource>
83
#define PMR std::pmr
84
#else
85
#include <boost/container/pmr/monotonic_buffer_resource.hpp>
86
#include <boost/container/pmr/vector.hpp>
87
#define PMR boost::container::pmr
88
#endif
89
90
#include "exprs/function/simple_function_factory.h"
91
92
namespace doris {
93
#include "common/compile_check_avoid_begin.h"
94
95
class FunctionAutoPartitionName : public IFunction {
96
public:
97
    static constexpr auto name = "auto_partition_name";
98
6
    static FunctionPtr create() { return std::make_shared<FunctionAutoPartitionName>(); }
99
0
    String get_name() const override { return name; }
100
0
    size_t get_number_of_arguments() const override { return 0; }
101
5
    bool is_variadic() const override { return true; }
102
8
    bool use_default_implementation_for_nulls() const override { return false; }
103
4
    DataTypePtr get_return_type_impl(const DataTypes& arguments) const override {
104
4
        return std::make_shared<DataTypeString>();
105
4
    }
106
107
    Status execute_impl(FunctionContext* context, Block& block, const ColumnNumbers& arguments,
108
4
                        uint32_t result, size_t input_rows_count) const override {
109
4
        size_t argument_size = arguments.size();
110
4
        auto const_null_map = ColumnUInt8::create(input_rows_count, 0);
111
4
        auto null_map = ColumnUInt8::create(input_rows_count, 0);
112
4
        std::vector<const ColumnString::Chars*> chars_list(argument_size);
113
4
        std::vector<const ColumnString::Offsets*> offsets_list(argument_size);
114
4
        std::vector<bool> is_const_args(argument_size);
115
4
        std::vector<const ColumnUInt8::Container*> null_list(argument_size);
116
4
        std::vector<ColumnPtr> argument_null_columns(argument_size);
117
118
4
        std::vector<ColumnPtr> argument_columns(argument_size);
119
14
        for (int i = 0; i < argument_size; ++i) {
120
10
            argument_columns[i] =
121
10
                    block.get_by_position(arguments[i]).column->convert_to_full_column_if_const();
122
10
            if (const auto* nullable =
123
10
                        check_and_get_column<const ColumnNullable>(*argument_columns[i])) {
124
10
                null_list[i] = &nullable->get_null_map_data();
125
10
                argument_null_columns[i] = nullable->get_null_map_column_ptr();
126
10
                argument_columns[i] = nullable->get_nested_column_ptr();
127
10
            } else {
128
0
                null_list[i] = &const_null_map->get_data();
129
0
            }
130
131
10
            const auto& [col, is_const] =
132
10
                    unpack_if_const(block.get_by_position(arguments[i]).column);
133
134
10
            const auto* col_str = assert_cast<const ColumnString*>(argument_columns[i].get());
135
10
            chars_list[i] = &col_str->get_chars();
136
10
            offsets_list[i] = &col_str->get_offsets();
137
10
            is_const_args[i] = is_const;
138
10
        }
139
140
4
        auto res = ColumnString::create();
141
4
        auto& res_data = res->get_chars();
142
4
        auto& res_offset = res->get_offsets();
143
4
        res_offset.resize(input_rows_count);
144
145
4
        std::string partition_type(chars_list[0]->raw_data(), (*offsets_list[0])[0]);
146
4
        std::transform(partition_type.begin(), partition_type.end(), partition_type.begin(),
147
18
                       [](unsigned char c) { return static_cast<char>(std::tolower(c)); });
148
        // partition type is list|range
149
4
        if (partition_type == "list") {
150
2
            return _auto_partition_type_of_list(chars_list, offsets_list, is_const_args, null_list,
151
2
                                                res_data, res_offset, input_rows_count,
152
2
                                                argument_size, block, result, res);
153
2
        } else {
154
2
            return _auto_partition_type_of_range(chars_list, offsets_list, is_const_args, res_data,
155
2
                                                 res_offset, input_rows_count, argument_size, block,
156
2
                                                 result, res);
157
2
        }
158
0
        return Status::OK();
159
4
    }
160
161
private:
162
2
    std::u16string _string_to_u16string(const std::string& str) const {
163
2
        return boost::locale::conv::utf_to_utf<char16_t>(str);
164
2
    }
165
166
2
    std::string _string_to_unicode(const std::u16string& s) const {
167
2
        std::string res_s;
168
2
        res_s.reserve(s.size());
169
2
        if (s.length() > 0 && s[0] == '-') {
170
0
            res_s += '_';
171
0
        }
172
24
        for (int i = 0; i < s.length(); i++) {
173
22
            char16_t ch = s[i];
174
22
            if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')) {
175
20
                res_s += ch;
176
20
            } else {
177
2
                int unicodeValue = _get_code_point_at(s, i);
178
2
                res_s += fmt::format("{:02x}", static_cast<uint32_t>(unicodeValue));
179
2
            }
180
22
        }
181
2
        return res_s;
182
2
    }
183
184
2
    int _get_code_point_at(const std::u16string& str, std::size_t index) const {
185
2
        char16_t first = str[index];
186
        // [0xD800,0xDBFF] is the scope of the first code unit
187
2
        if ((first >= 0xD800 && first <= 0xDBFF) && (index + 1 < str.size())) {
188
0
            char16_t second = str[index + 1];
189
            // [0xDC00,0xDFFF] is the scope of the second code unit
190
0
            if (second >= 0xDC00 && second <= 0xDFFF) {
191
0
                return ((first - 0xD800) << 10) + (second - 0xDC00) + 0x10000;
192
0
            }
193
0
        }
194
195
2
        return first;
196
2
    }
197
    Status _auto_partition_type_of_list(std::vector<const ColumnString::Chars*>& chars_list,
198
                                        std::vector<const ColumnString::Offsets*>& offsets_list,
199
                                        std::vector<bool>& is_const_args,
200
                                        const std::vector<const ColumnUInt8::Container*>& null_list,
201
                                        auto& res_data, auto& res_offset, size_t input_rows_count,
202
                                        size_t argument_size, Block& block, uint32_t result,
203
2
                                        auto& res) const {
204
2
        int curr_len = 0;
205
4
        for (int row = 0; row < input_rows_count; row++) {
206
2
            std::string res_p;
207
2
            res_p.reserve(argument_size * 5);
208
2
            res_p += 'p';
209
4
            for (int col = 1; col < argument_size; col++) {
210
2
                const auto& current_offsets = *offsets_list[col];
211
2
                const auto& current_chars = *chars_list[col];
212
2
                const auto& current_nullmap = *null_list[col];
213
214
2
                if (current_nullmap[row]) {
215
0
                    res_p += 'X';
216
2
                } else {
217
2
                    auto idx = index_check_const(row, is_const_args[col]);
218
219
2
                    int size = current_offsets[idx] - current_offsets[idx - 1];
220
2
                    const char* raw_chars =
221
2
                            reinterpret_cast<const char*>(&current_chars[current_offsets[idx - 1]]);
222
                    // convert string to u16string in order to convert to unicode strings
223
2
                    const std::string raw_str(raw_chars, size);
224
2
                    auto u16string = _string_to_u16string(raw_str);
225
2
                    res_p += _string_to_unicode(u16string) + std::to_string(u16string.size());
226
2
                }
227
2
            }
228
229
            // check the name of length
230
2
            int len = res_p.size();
231
2
            if (len > 50) {
232
0
                res_p = std::format("{}_{:08x}", res_p.substr(0, 50), to_hash_code(res_p));
233
0
                len = res_p.size();
234
0
            }
235
2
            curr_len += len;
236
2
            res_data.resize(curr_len);
237
2
            memcpy(&res_data[res_offset[row - 1]], res_p.c_str(), len);
238
2
            res_offset[row] = res_offset[row - 1] + len;
239
2
        }
240
2
        block.get_by_position(result).column = std::move(res);
241
2
        return Status::OK();
242
2
    }
243
244
    size_t _copy_date_str_of_len_to_res_data(auto& res_data, auto& res_offset,
245
                                             std::vector<std::string>& date_str, size_t row,
246
2
                                             size_t len) const {
247
2
        size_t curr_len = 1;
248
7
        for (int j = 0; j < len; j++) {
249
5
            memcpy(&res_data[res_offset[row - 1]] + curr_len, date_str[j].c_str(),
250
5
                   date_str[j].size());
251
5
            curr_len += date_str[j].size();
252
5
        }
253
2
        return curr_len;
254
2
    }
255
256
    Status _auto_partition_type_of_range(std::vector<const ColumnString::Chars*>& chars_list,
257
                                         std::vector<const ColumnString::Offsets*>& offsets_list,
258
                                         std::vector<bool>& is_const_args, auto& res_data,
259
                                         auto& res_offset, size_t input_rows_count,
260
                                         size_t argument_size, Block& block, uint32_t result,
261
2
                                         auto& res) const {
262
2
        std::string range_type(chars_list[1]->raw_data(), (*offsets_list[1])[0]);
263
2
        std::transform(range_type.begin(), range_type.end(), range_type.begin(),
264
8
                       [](unsigned char c) { return static_cast<char>(std::tolower(c)); });
265
266
2
        res_data.resize(15 * input_rows_count);
267
4
        for (int i = 0; i < input_rows_count; i++) {
268
2
            const auto& current_offsets = *offsets_list[2];
269
2
            const auto& current_chars = *chars_list[2];
270
271
2
            auto idx = index_check_const(i, is_const_args[2]);
272
2
            int size = current_offsets[idx] - current_offsets[idx - 1];
273
2
            const char* tmp =
274
2
                    reinterpret_cast<const char*>(&current_chars[current_offsets[idx - 1]]);
275
2
            std::string to_split_s(tmp, size);
276
277
            // check the str if it is date|datetime
278
2
            RE2 date_regex(R"(^\d{4}-\d{2}-\d{2}( \d{2}:\d{2}:\d{2})?$)");
279
2
            if (!RE2::FullMatch(to_split_s, date_regex)) {
280
0
                return Status::InvalidArgument("The range partition only support DATE|DATETIME");
281
0
            }
282
283
            // split date_str from (yyyy-mm-dd hh:mm:ss) to ([yyyy, mm, dd, hh, mm, ss])
284
2
            std::vector<std::string> date_str(6);
285
2
            date_str[0] = to_split_s.substr(0, 4);
286
12
            for (int ni = 5, j = 1; ni <= size; ni += 3, j++) {
287
10
                date_str[j] = to_split_s.substr(ni, 2);
288
10
            }
289
2
            int curr_len = 0;
290
291
2
            res_data[res_offset[i - 1]] = 'p';
292
            // raw => 2022-12-12 11:30:20
293
            // year => 2022 01 01 00 00 00
294
            // month => 2022 12 01 00 00 00
295
            // day => 2022 12 12 00 00 00
296
            // hour => 2022 12 12 11 00 00
297
            // minute => 2022 12  11 30 00
298
            // second => 2022 12 12 12 30 20
299
300
2
            if (range_type == "year") {
301
0
                curr_len += _copy_date_str_of_len_to_res_data(res_data, res_offset, date_str, i, 1);
302
0
                memcpy(&res_data[res_offset[i - 1]] + curr_len, "0101", 4);
303
0
                curr_len += 4;
304
2
            } else if (range_type == "month") {
305
1
                curr_len += _copy_date_str_of_len_to_res_data(res_data, res_offset, date_str, i, 2);
306
1
                memcpy(&res_data[res_offset[i - 1]] + curr_len, "01", 2);
307
1
                curr_len += 2;
308
1
            } else if (range_type == "day") {
309
1
                curr_len += _copy_date_str_of_len_to_res_data(res_data, res_offset, date_str, i, 3);
310
1
            } else if (range_type == "hour") {
311
0
                curr_len += _copy_date_str_of_len_to_res_data(res_data, res_offset, date_str, i, 4);
312
0
            } else if (range_type == "minute") {
313
0
                curr_len += _copy_date_str_of_len_to_res_data(res_data, res_offset, date_str, i, 5);
314
0
            } else if (range_type == "second") {
315
0
                curr_len += _copy_date_str_of_len_to_res_data(res_data, res_offset, date_str, i, 6);
316
0
            }
317
318
            // fill in zero
319
2
            int zero = 15 - curr_len;
320
2
            std::fill_n(&res_data[res_offset[i - 1]] + curr_len, zero, '0');
321
2
            curr_len += zero;
322
2
            res_offset[i] = res_offset[i - 1] + curr_len;
323
2
        }
324
2
        block.get_by_position(result).column = std::move(res);
325
2
        return Status::OK();
326
2
    }
327
328
0
    int32_t to_hash_code(const std::string& str) const {
329
0
        uint64_t h = 0;
330
0
        for (uint8_t c : str) {
331
0
            h = (h * 31U + c) & 0xFFFFFFFFU;
332
0
        }
333
0
        return static_cast<int32_t>(h);
334
0
    }
335
};
336
337
class FunctionRandomBytes : public IFunction {
338
public:
339
    static constexpr auto name = "random_bytes";
340
2
    static FunctionPtr create() { return std::make_shared<FunctionRandomBytes>(); }
341
1
    String get_name() const override { return name; }
342
0
    size_t get_number_of_arguments() const override { return 1; }
343
1
    bool is_variadic() const override { return false; }
344
345
0
    DataTypePtr get_return_type_impl(const DataTypes& arguments) const override {
346
0
        return std::make_shared<DataTypeString>();
347
0
    }
348
349
0
    bool use_default_implementation_for_constants() const final { return false; }
350
351
    Status execute_impl(FunctionContext* context, Block& block, const ColumnNumbers& arguments,
352
0
                        uint32_t result, size_t input_rows_count) const override {
353
0
        auto res = ColumnString::create();
354
0
        auto& res_offsets = res->get_offsets();
355
0
        auto& res_chars = res->get_chars();
356
0
        res_offsets.resize(input_rows_count);
357
358
0
        auto [arg_col, arg_const] = unpack_if_const(block.get_by_position(arguments[0]).column);
359
0
        const auto* length_col = assert_cast<const ColumnInt32*>(arg_col.get());
360
361
0
        if (arg_const) {
362
0
            res_chars.reserve(input_rows_count * (length_col->get_element(0) + 2));
363
0
        }
364
365
0
        std::vector<uint8_t, Allocator_<uint8_t>> random_bytes;
366
0
        std::random_device rd;
367
0
        std::mt19937 gen(rd());
368
369
0
        std::uniform_int_distribution<unsigned short> distribution(0, 255);
370
0
        for (size_t i = 0; i < input_rows_count; ++i) {
371
0
            size_t index = index_check_const(i, arg_const);
372
0
            if (length_col->get_element(index) < 0) [[unlikely]] {
373
0
                return Status::InvalidArgument("argument {} of function {} at row {} was invalid.",
374
0
                                               length_col->get_element(index), name, index);
375
0
            }
376
0
            random_bytes.resize(length_col->get_element(index));
377
378
0
            for (auto& byte : random_bytes) {
379
0
                byte = distribution(gen) & 0xFF;
380
0
            }
381
382
0
            std::basic_ostringstream<char, std::char_traits<char>, Allocator_<char>> oss;
383
0
            for (const auto& byte : random_bytes) {
384
0
                oss << std::setw(2) << std::setfill('0') << std::hex << static_cast<int>(byte);
385
0
            }
386
387
0
            StringOP::push_value_string("0x" + oss.str(), i, res_chars, res_offsets);
388
0
            random_bytes.clear();
389
0
        }
390
391
0
        block.get_by_position(result).column = std::move(res);
392
393
0
        return Status::OK();
394
0
    }
395
};
396
397
class FunctionConvertTo : public IFunction {
398
public:
399
    static constexpr auto name = "convert_to";
400
401
2
    static FunctionPtr create() { return std::make_shared<FunctionConvertTo>(); }
402
403
1
    String get_name() const override { return name; }
404
405
0
    size_t get_number_of_arguments() const override { return 2; }
406
407
0
    DataTypePtr get_return_type_impl(const DataTypes& /*arguments*/) const override {
408
0
        return std::make_shared<DataTypeString>();
409
0
    }
410
411
0
    Status open(FunctionContext* context, FunctionContext::FunctionStateScope scope) override {
412
0
        if (scope != FunctionContext::FunctionStateScope::THREAD_LOCAL) {
413
0
            return Status::OK();
414
0
        }
415
0
        if (!context->is_col_constant(1)) {
416
0
            return Status::InvalidArgument(
417
0
                    "character argument to convert function must be constant.");
418
0
        }
419
0
        const auto& character_data = context->get_constant_col(1)->column_ptr->get_data_at(0);
420
0
        if (!iequal(character_data.to_string(), "gbk")) {
421
0
            return Status::RuntimeError(
422
0
                    "Illegal second argument column of function convert. now only support "
423
0
                    "convert to character set of gbk");
424
0
        }
425
426
0
        return Status::OK();
427
0
    }
428
429
    Status execute_impl(FunctionContext* context, Block& block, const ColumnNumbers& arguments,
430
0
                        uint32_t result, size_t input_rows_count) const override {
431
0
        ColumnPtr argument_column =
432
0
                block.get_by_position(arguments[0]).column->convert_to_full_column_if_const();
433
0
        const ColumnString* str_col = static_cast<const ColumnString*>(argument_column.get());
434
0
        const auto& str_offset = str_col->get_offsets();
435
0
        const auto& str_chars = str_col->get_chars();
436
0
        auto col_res = ColumnString::create();
437
0
        auto& res_offset = col_res->get_offsets();
438
0
        auto& res_chars = col_res->get_chars();
439
0
        res_offset.resize(input_rows_count);
440
        // max pinyin size is 6 + 1 (first '~') for utf8 chinese word 3
441
0
        size_t pinyin_size = (str_chars.size() + 2) / 3 * 7;
442
0
        ColumnString::check_chars_length(pinyin_size, 0);
443
0
        res_chars.resize(pinyin_size);
444
445
0
        size_t in_len = 0, out_len = 0;
446
0
        for (int i = 0; i < input_rows_count; ++i) {
447
0
            in_len = str_offset[i] - str_offset[i - 1];
448
0
            const char* in = reinterpret_cast<const char*>(&str_chars[str_offset[i - 1]]);
449
0
            char* out = reinterpret_cast<char*>(&res_chars[res_offset[i - 1]]);
450
0
            _utf8_to_pinyin(in, in_len, out, &out_len);
451
0
            res_offset[i] = res_offset[i - 1] + out_len;
452
0
        }
453
0
        res_chars.resize(res_offset[input_rows_count - 1]);
454
0
        block.replace_by_position(result, std::move(col_res));
455
0
        return Status::OK();
456
0
    }
457
458
0
    void _utf8_to_pinyin(const char* in, size_t in_len, char* out, size_t* out_len) const {
459
0
        auto do_memcpy = [](char*& dest, const char*& from, size_t size) {
460
0
            memcpy_small_allow_read_write_overflow15(dest, from, size);
461
0
            dest += size;
462
0
            from += size;
463
0
        };
464
0
        auto from = in;
465
0
        auto dest = out;
466
467
0
        while (from - in < in_len) {
468
0
            auto length = get_utf8_byte_length(*from);
469
0
            if (length != 3) {
470
0
                do_memcpy(dest, from, length);
471
0
            } else {
472
                // convert utf8 to unicode code to get pinyin offset
473
0
                if (auto tmp = (((int)(*from & 0x0F)) << 12) | (((int)(*(from + 1) & 0x3F)) << 6) |
474
0
                               (*(from + 2) & 0x3F);
475
0
                    tmp >= START_UNICODE_OFFSET and tmp < END_UNICODE_OFFSET) {
476
0
                    const char* buf = nullptr;
477
0
                    if (tmp >= START_UNICODE_OFFSET && tmp < MID_UNICODE_OFFSET) {
478
0
                        buf = PINYIN_DICT1 + (tmp - START_UNICODE_OFFSET) * MAX_PINYIN_LEN;
479
0
                    } else if (tmp >= MID_UNICODE_OFFSET && tmp < END_UNICODE_OFFSET) {
480
0
                        buf = PINYIN_DICT2 + (tmp - MID_UNICODE_OFFSET) * MAX_PINYIN_LEN;
481
0
                    }
482
483
0
                    auto end = strchr(buf, ' ');
484
                    // max len for pinyin is 6
485
0
                    int len = MAX_PINYIN_LEN;
486
0
                    if (end != nullptr && end - buf < MAX_PINYIN_LEN) {
487
0
                        len = end - buf;
488
0
                    }
489
                    // set first char '~' just make sure all english word lower than chinese word
490
0
                    *dest = 126;
491
0
                    memcpy(dest + 1, buf, len);
492
0
                    dest += (len + 1);
493
0
                    from += 3;
494
0
                } else {
495
0
                    do_memcpy(dest, from, 3);
496
0
                }
497
0
            }
498
0
        }
499
500
0
        *out_len = dest - out;
501
0
    }
502
};
503
// +-----------------------------------+
504
// | 丝                                |
505
// +-----------------------------------+
506
// 1 row in set, 1 warning (0.00 sec)
507
// mysql> select char(14989469 using utf8);
508
// +---------------------------+
509
// | char(14989469 using utf8) |
510
// +---------------------------+
511
// | 丝                        |
512
// +---------------------------+
513
// 1 row in set, 1 warning (0.00 sec)
514
// mysql> select char(0xe5, 0xa4, 0x9a, 0xe7, 0x9d, 0xbf, 0xe4, 0xb8, 0x9d, 68, 111, 114, 105, 115 using utf8);
515
// +---------------------------------------------------------------------------------------------+
516
// | char(0xe5, 0xa4, 0x9a, 0xe7, 0x9d, 0xbf, 0xe4, 0xb8, 0x9d, 68, 111, 114, 105, 115 using utf8) |
517
// +---------------------------------------------------------------------------------------------+
518
// | 多睿丝 Doris                                                                                 |
519
// +---------------------------------------------------------------------------------------------+
520
// mysql> select char(68, 111, 114, 0, 105, null, 115 using utf8);
521
// +--------------------------------------------------+
522
// | char(68, 111, 114, 0, 105, null, 115 using utf8) |
523
// +--------------------------------------------------+
524
// | Dor is                                           |
525
// +--------------------------------------------------+
526
527
// return null:
528
// mysql>  select char(255 using utf8);
529
// +----------------------+
530
// | char(255 using utf8) |
531
// +----------------------+
532
// | NULL                 |
533
// +----------------------+
534
// 1 row in set, 2 warnings (0.00 sec)
535
//
536
// mysql> show warnings;
537
// +---------+------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
538
// | Level   | Code | Message                                                                                                                                                                     |
539
// +---------+------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
540
// | Warning | 3719 | 'utf8' is currently an alias for the character set UTF8MB3, but will be an alias for UTF8MB4 in a future release. Please consider using UTF8MB4 in order to be unambiguous. |
541
// | Warning | 1300 | Invalid utf8mb3 character string: 'FF'                                                                                                                                      |
542
// +---------+------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
543
// 2 rows in set (0.01 sec)
544
545
// max int value:
546
// mysql> select char(18446744073709551615);
547
// +--------------------------------------------------------+
548
// | char(18446744073709551615)                             |
549
// +--------------------------------------------------------+
550
// | 0xFFFFFFFF                                             |
551
// +--------------------------------------------------------+
552
// 1 row in set (0.00 sec)
553
//
554
// mysql> select char(18446744073709551616);
555
// +--------------------------------------------------------+
556
// | char(18446744073709551616)                             |
557
// +--------------------------------------------------------+
558
// | 0xFFFFFFFF                                             |
559
// +--------------------------------------------------------+
560
// 1 row in set, 1 warning (0.00 sec)
561
//
562
// mysql> show warnings;
563
// +---------+------+-----------------------------------------------------------+
564
// | Level   | Code | Message                                                   |
565
// +---------+------+-----------------------------------------------------------+
566
// | Warning | 1292 | Truncated incorrect DECIMAL value: '18446744073709551616' |
567
// +---------+------+-----------------------------------------------------------+
568
// 1 row in set (0.00 sec)
569
570
// table columns:
571
// mysql> select * from t;
572
// +------+------+------+
573
// | f1   | f2   | f3   |
574
// +------+------+------+
575
// |  228 |  184 |  157 |
576
// |  228 |  184 |    0 |
577
// |  228 |  184 |   99 |
578
// |   99 |  228 |  184 |
579
// +------+------+------+
580
// 4 rows in set (0.00 sec)
581
//
582
// mysql> select char(f1, f2, f3 using utf8) from t;
583
// +-----------------------------+
584
// | char(f1, f2, f3 using utf8) |
585
// +-----------------------------+
586
// | 丝                          |
587
// |                             |
588
// |                             |
589
// | c                           |
590
// +-----------------------------+
591
// 4 rows in set, 4 warnings (0.00 sec)
592
//
593
// mysql> show warnings;
594
// +---------+------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
595
// | Level   | Code | Message                                                                                                                                                                     |
596
// +---------+------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
597
// | Warning | 3719 | 'utf8' is currently an alias for the character set UTF8MB3, but will be an alias for UTF8MB4 in a future release. Please consider using UTF8MB4 in order to be unambiguous. |
598
// | Warning | 1300 | Invalid utf8mb3 character string: 'E4B800'                                                                                                                                  |
599
// | Warning | 1300 | Invalid utf8mb3 character string: 'E4B863'                                                                                                                                  |
600
// | Warning | 1300 | Invalid utf8mb3 character string: 'E4B8'                                                                                                                                    |
601
// +---------+------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
602
class FunctionIntToChar : public IFunction {
603
public:
604
    static constexpr auto name = "char";
605
2
    static FunctionPtr create() { return std::make_shared<FunctionIntToChar>(); }
606
0
    String get_name() const override { return name; }
607
0
    size_t get_number_of_arguments() const override { return 0; }
608
1
    bool is_variadic() const override { return true; }
609
610
0
    DataTypePtr get_return_type_impl(const DataTypes& arguments) const override {
611
0
        return make_nullable(std::make_shared<DataTypeString>());
612
0
    }
613
0
    bool use_default_implementation_for_nulls() const override { return false; }
614
615
    Status execute_impl(FunctionContext* context, Block& block, const ColumnNumbers& arguments,
616
0
                        uint32_t result, size_t input_rows_count) const override {
617
0
        DCHECK_GE(arguments.size(), 2);
618
619
0
        int argument_size = arguments.size();
620
0
        std::vector<ColumnPtr> str_columns(argument_size - 1);
621
0
        std::vector<const ColumnString::Offsets*> offsets_list(argument_size - 1);
622
0
        std::vector<const ColumnString::Chars*> chars_list(argument_size - 1);
623
624
        // convert each argument columns to column string and then concat the string columns
625
0
        for (size_t i = 1; i < argument_size; ++i) {
626
0
            if (auto const_column = check_and_get_column<const ColumnConst>(
627
0
                        *block.get_by_position(arguments[i]).column)) {
628
                // ignore null
629
0
                if (const_column->only_null()) {
630
0
                    str_columns[i - 1] = nullptr;
631
0
                } else {
632
0
                    auto str_column = ColumnString::create();
633
0
                    auto& chars = str_column->get_chars();
634
0
                    auto& offsets = str_column->get_offsets();
635
0
                    offsets.resize(1);
636
0
                    const ColumnInt32* int_column;
637
0
                    if (auto* nullable = check_and_get_column<const ColumnNullable>(
638
0
                                const_column->get_data_column())) {
639
0
                        int_column = assert_cast<const ColumnInt32*>(
640
0
                                nullable->get_nested_column_ptr().get());
641
0
                    } else {
642
0
                        int_column =
643
0
                                assert_cast<const ColumnInt32*>(&const_column->get_data_column());
644
0
                    }
645
0
                    int int_val = int_column->get_int(0);
646
0
                    integer_to_char_(0, &int_val, chars, offsets);
647
0
                    str_columns[i - 1] =
648
0
                            ColumnConst::create(std::move(str_column), input_rows_count);
649
0
                }
650
0
                offsets_list[i - 1] = nullptr;
651
0
                chars_list[i - 1] = nullptr;
652
0
            } else {
653
0
                auto str_column = ColumnString::create();
654
0
                auto& chars = str_column->get_chars();
655
0
                auto& offsets = str_column->get_offsets();
656
                // data.resize(input_rows_count);
657
0
                offsets.resize(input_rows_count);
658
659
0
                if (auto nullable = check_and_get_column<const ColumnNullable>(
660
0
                            *block.get_by_position(arguments[i]).column)) {
661
0
                    const auto* int_data =
662
0
                            assert_cast<const ColumnInt32*>(nullable->get_nested_column_ptr().get())
663
0
                                    ->get_data()
664
0
                                    .data();
665
0
                    const auto* null_map_data = nullable->get_null_map_data().data();
666
0
                    for (size_t j = 0; j < input_rows_count; ++j) {
667
                        // ignore null
668
0
                        if (null_map_data[j]) {
669
0
                            offsets[j] = offsets[j - 1];
670
0
                        } else {
671
0
                            integer_to_char_(j, int_data + j, chars, offsets);
672
0
                        }
673
0
                    }
674
0
                } else {
675
0
                    const auto* int_data = assert_cast<const ColumnInt32*>(
676
0
                                                   block.get_by_position(arguments[i]).column.get())
677
0
                                                   ->get_data()
678
0
                                                   .data();
679
0
                    for (size_t j = 0; j < input_rows_count; ++j) {
680
0
                        integer_to_char_(j, int_data + j, chars, offsets);
681
0
                    }
682
0
                }
683
0
                offsets_list[i - 1] = &str_column->get_offsets();
684
0
                chars_list[i - 1] = &str_column->get_chars();
685
0
                str_columns[i - 1] = std::move(str_column);
686
0
            }
687
0
        }
688
689
0
        auto null_map = ColumnUInt8::create(input_rows_count, 0);
690
0
        auto res = ColumnString::create();
691
0
        auto& res_data = res->get_chars();
692
0
        auto& res_offset = res->get_offsets();
693
694
0
        size_t res_reserve_size = 0;
695
0
        for (size_t i = 0; i < argument_size - 1; ++i) {
696
0
            if (!str_columns[i]) {
697
0
                continue;
698
0
            }
699
0
            if (auto const_column = check_and_get_column<const ColumnConst>(*str_columns[i])) {
700
0
                auto str_column =
701
0
                        assert_cast<const ColumnString*>(&(const_column->get_data_column()));
702
0
                auto& offsets = str_column->get_offsets();
703
0
                res_reserve_size += (offsets[0] - offsets[-1]) * input_rows_count;
704
0
            } else {
705
0
                for (size_t j = 0; j < input_rows_count; ++j) {
706
0
                    size_t append = (*offsets_list[i])[j] - (*offsets_list[i])[j - 1];
707
                    // check whether the output might overflow(unlikely)
708
0
                    if (UNLIKELY(UINT_MAX - append < res_reserve_size)) {
709
0
                        return Status::BufferAllocFailed(
710
0
                                "function char output is too large to allocate");
711
0
                    }
712
0
                    res_reserve_size += append;
713
0
                }
714
0
            }
715
0
        }
716
0
        if ((UNLIKELY(UINT_MAX - input_rows_count < res_reserve_size))) {
717
0
            return Status::BufferAllocFailed("function char output is too large to allocate");
718
0
        }
719
0
        ColumnString::check_chars_length(res_reserve_size, 0);
720
0
        res_data.resize(res_reserve_size);
721
0
        res_offset.resize(input_rows_count);
722
723
0
        for (size_t i = 0; i < input_rows_count; ++i) {
724
0
            int current_length = 0;
725
0
            for (size_t j = 0; j < argument_size - 1; ++j) {
726
0
                if (!str_columns[j]) {
727
0
                    continue;
728
0
                }
729
0
                if (auto const_column = check_and_get_column<const ColumnConst>(*str_columns[j])) {
730
0
                    auto str_column = assert_cast<const ColumnString*, TypeCheckOnRelease::DISABLE>(
731
0
                            &(const_column->get_data_column()));
732
0
                    auto data_item = str_column->get_data_at(0);
733
0
                    memcpy_small_allow_read_write_overflow15(
734
0
                            &res_data[res_offset[i - 1]] + current_length, data_item.data,
735
0
                            data_item.size);
736
0
                    current_length += data_item.size;
737
0
                } else {
738
0
                    auto& current_offsets = *offsets_list[j];
739
0
                    auto& current_chars = *chars_list[j];
740
741
0
                    int size = current_offsets[i] - current_offsets[i - 1];
742
0
                    if (size > 0) {
743
0
                        memcpy_small_allow_read_write_overflow15(
744
0
                                &res_data[res_offset[i - 1]] + current_length,
745
0
                                &current_chars[current_offsets[i - 1]], size);
746
0
                        current_length += size;
747
0
                    }
748
0
                }
749
0
            }
750
0
            res_offset[i] = res_offset[i - 1] + current_length;
751
0
        }
752
753
        // validate utf8
754
0
        auto* null_map_data = null_map->get_data().data();
755
0
        for (size_t i = 0; i < input_rows_count; ++i) {
756
0
            if (!validate_utf8((const char*)(&res_data[res_offset[i - 1]]),
757
0
                               res_offset[i] - res_offset[i - 1])) {
758
0
                null_map_data[i] = 1;
759
0
            }
760
0
        }
761
762
0
        block.get_by_position(result).column =
763
0
                ColumnNullable::create(std::move(res), std::move(null_map));
764
0
        return Status::OK();
765
0
    }
766
767
private:
768
    void integer_to_char_(int line_num, const int* num, ColumnString::Chars& chars,
769
0
                          IColumn::Offsets& offsets) const {
770
0
        if (0 == *num) {
771
0
            chars.push_back('\0');
772
0
            offsets[line_num] = offsets[line_num - 1] + 1;
773
0
            return;
774
0
        }
775
0
        const char* bytes = (const char*)(num);
776
0
        if constexpr (std::endian::native == std::endian::little) {
777
0
            int k = 3;
778
0
            for (; k >= 0; --k) {
779
0
                if (bytes[k]) {
780
0
                    break;
781
0
                }
782
0
            }
783
0
            offsets[line_num] = offsets[line_num - 1] + k + 1;
784
0
            for (; k >= 0; --k) {
785
0
                chars.push_back(bytes[k] ? bytes[k] : '\0');
786
0
            }
787
        } else if constexpr (std::endian::native == std::endian::big) {
788
            int k = 0;
789
            for (; k < 4; ++k) {
790
                if (bytes[k]) {
791
                    break;
792
                }
793
            }
794
            offsets[line_num] = offsets[line_num - 1] + 4 - k;
795
            for (; k < 4; ++k) {
796
                chars.push_back(bytes[k] ? bytes[k] : '\0');
797
            }
798
        } else {
799
            static_assert(std::endian::native == std::endian::big ||
800
                                  std::endian::native == std::endian::little,
801
                          "Unsupported endianness");
802
        }
803
0
    }
804
};
805
806
class FunctionNgramSearch : public IFunction {
807
public:
808
    static constexpr auto name = "ngram_search";
809
7
    static FunctionPtr create() { return std::make_shared<FunctionNgramSearch>(); }
810
1
    String get_name() const override { return name; }
811
5
    size_t get_number_of_arguments() const override { return 3; }
812
5
    DataTypePtr get_return_type_impl(const DataTypes& arguments) const override {
813
5
        return std::make_shared<DataTypeFloat64>();
814
5
    }
815
816
    // ngram_search(text,pattern,gram_num)
817
    Status execute_impl(FunctionContext* context, Block& block, const ColumnNumbers& arguments,
818
5
                        uint32_t result, size_t input_rows_count) const override {
819
5
        CHECK_EQ(arguments.size(), 3);
820
5
        auto col_res = ColumnFloat64::create();
821
5
        bool col_const[3];
822
5
        ColumnPtr argument_columns[3];
823
20
        for (int i = 0; i < 3; ++i) {
824
15
            std::tie(argument_columns[i], col_const[i]) =
825
15
                    unpack_if_const(block.get_by_position(arguments[i]).column);
826
15
        }
827
5
        auto pattern = assert_cast<const ColumnString*>(argument_columns[1].get())->get_data_at(0);
828
5
        auto gram_num = assert_cast<const ColumnInt32*>(argument_columns[2].get())->get_element(0);
829
        // FE only rejects a nonpositive gram_num once it is a literal. A constant expression that
830
        // FE cannot evaluate (e.g. `crc32('abc') % 3 - 3`) reaches BE unchecked when the whole
831
        // call is folded on BE, so validate here before it is used as a substring length.
832
5
        if (gram_num <= 0) {
833
2
            return Status::InvalidArgument(
834
2
                    "ngram_search(text,pattern,gram_num): gram_num must be a positive constant.");
835
2
        }
836
3
        const auto* text_col = assert_cast<const ColumnString*>(argument_columns[0].get());
837
838
3
        if (col_const[0]) {
839
0
            _execute_impl<true>(text_col, pattern, gram_num, *col_res, input_rows_count);
840
3
        } else {
841
3
            _execute_impl<false>(text_col, pattern, gram_num, *col_res, input_rows_count);
842
3
        }
843
844
3
        block.replace_by_position(result, std::move(col_res));
845
3
        return Status::OK();
846
5
    }
847
848
private:
849
    using NgramMap = phmap::flat_hash_map<uint32_t, uint8_t>;
850
    constexpr static auto not_found = 0b00;
851
    constexpr static auto found_in_pattern = 0b01;
852
    constexpr static auto found_in_text = 0b10;
853
    constexpr static auto found_in_pattern_and_text = 0b11;
854
855
8
    uint32_t sub_str_hash(const char* data, int32_t length) const {
856
8
        constexpr static uint32_t seed = 0;
857
8
        return crc32c::Extend(seed, (const uint8_t*)data, length);
858
8
    }
859
860
    template <bool column_const>
861
    void _execute_impl(const ColumnString* text_col, StringRef& pattern, int gram_num,
862
3
                       ColumnFloat64& res, size_t size) const {
863
3
        auto& res_data = res.get_data();
864
3
        res_data.resize_fill(size, 0);
865
        // If the length of the pattern is less than gram_num, return 0.
866
3
        if (pattern.size < gram_num) {
867
0
            return;
868
0
        }
869
870
        // Build a map by pattern string, which will be used repeatedly in the following loop.
871
3
        NgramMap pattern_map;
872
3
        int pattern_count = get_pattern_set(pattern_map, pattern, gram_num);
873
        // Each time a loop is executed, the map will be modified, so it needs to be restored afterward.
874
3
        std::vector<uint32_t> restore_map;
875
876
6
        for (int i = 0; i < size; i++) {
877
3
            auto text = text_col->get_data_at(index_check_const<column_const>(i));
878
3
            if (text.size < gram_num) {
879
                // If the length of the text is less than gram_num, return 0.
880
1
                continue;
881
1
            }
882
2
            restore_map.reserve(text.size);
883
2
            auto [text_count, intersection_count] =
884
2
                    get_text_set(text, gram_num, pattern_map, restore_map);
885
886
            // 2 * |Intersection| / (|text substr set| + |pattern substr set|)
887
2
            res_data[i] = 2.0 * intersection_count / (text_count + pattern_count);
888
2
        }
889
3
    }
Unexecuted instantiation: _ZNK5doris19FunctionNgramSearch13_execute_implILb1EEEvPKNS_9ColumnStrIjEERNS_9StringRefEiRNS_12ColumnVectorILNS_13PrimitiveTypeE9EEEm
_ZNK5doris19FunctionNgramSearch13_execute_implILb0EEEvPKNS_9ColumnStrIjEERNS_9StringRefEiRNS_12ColumnVectorILNS_13PrimitiveTypeE9EEEm
Line
Count
Source
862
3
                       ColumnFloat64& res, size_t size) const {
863
3
        auto& res_data = res.get_data();
864
3
        res_data.resize_fill(size, 0);
865
        // If the length of the pattern is less than gram_num, return 0.
866
3
        if (pattern.size < gram_num) {
867
0
            return;
868
0
        }
869
870
        // Build a map by pattern string, which will be used repeatedly in the following loop.
871
3
        NgramMap pattern_map;
872
3
        int pattern_count = get_pattern_set(pattern_map, pattern, gram_num);
873
        // Each time a loop is executed, the map will be modified, so it needs to be restored afterward.
874
3
        std::vector<uint32_t> restore_map;
875
876
6
        for (int i = 0; i < size; i++) {
877
3
            auto text = text_col->get_data_at(index_check_const<column_const>(i));
878
3
            if (text.size < gram_num) {
879
                // If the length of the text is less than gram_num, return 0.
880
1
                continue;
881
1
            }
882
2
            restore_map.reserve(text.size);
883
2
            auto [text_count, intersection_count] =
884
2
                    get_text_set(text, gram_num, pattern_map, restore_map);
885
886
            // 2 * |Intersection| / (|text substr set| + |pattern substr set|)
887
2
            res_data[i] = 2.0 * intersection_count / (text_count + pattern_count);
888
2
        }
889
3
    }
890
891
3
    size_t get_pattern_set(NgramMap& pattern_map, StringRef& pattern, int gram_num) const {
892
3
        size_t pattern_count = 0;
893
8
        for (int i = 0; i + gram_num <= pattern.size; i++) {
894
5
            uint32_t cur_hash = sub_str_hash(pattern.data + i, gram_num);
895
5
            if (!pattern_map.contains(cur_hash)) {
896
5
                pattern_map[cur_hash] = found_in_pattern;
897
5
                pattern_count++;
898
5
            }
899
5
        }
900
3
        return pattern_count;
901
3
    }
902
903
    std::pair<size_t, size_t> get_text_set(StringRef& text, int gram_num, NgramMap& pattern_map,
904
2
                                           std::vector<uint32_t>& restore_map) const {
905
2
        restore_map.clear();
906
        //intersection_count indicates a substring both in pattern and text.
907
2
        size_t text_count = 0, intersection_count = 0;
908
5
        for (int i = 0; i + gram_num <= text.size; i++) {
909
3
            uint32_t cur_hash = sub_str_hash(text.data + i, gram_num);
910
3
            auto& val = pattern_map[cur_hash];
911
3
            if (val == not_found) {
912
0
                val ^= found_in_text;
913
0
                DCHECK(val == found_in_text);
914
                // only found in text
915
0
                text_count++;
916
0
                restore_map.push_back(cur_hash);
917
3
            } else if (val == found_in_pattern) {
918
3
                val ^= found_in_text;
919
3
                DCHECK(val == found_in_pattern_and_text);
920
                // found in text and pattern
921
3
                text_count++;
922
3
                intersection_count++;
923
3
                restore_map.push_back(cur_hash);
924
3
            }
925
3
        }
926
        // Restore the pattern_map.
927
3
        for (auto& restore_hash : restore_map) {
928
3
            pattern_map[restore_hash] ^= found_in_text;
929
3
        }
930
931
2
        return {text_count, intersection_count};
932
2
    }
933
};
934
935
class FunctionTranslate : public IFunction {
936
public:
937
    static constexpr auto name = "translate";
938
    using AsciiMap = std::array<UInt8, 128>;
939
    constexpr static UInt8 DELETE_CHAR = 255; // 255 means delete this char
940
4
    static FunctionPtr create() { return std::make_shared<FunctionTranslate>(); }
941
1
    String get_name() const override { return name; }
942
2
    size_t get_number_of_arguments() const override { return 3; }
943
944
2
    DataTypePtr get_return_type_impl(const DataTypes& arguments) const override {
945
2
        return std::make_shared<DataTypeString>();
946
2
    };
947
948
1
    DataTypes get_variadic_argument_types_impl() const override {
949
1
        return {std::make_shared<DataTypeString>(), std::make_shared<DataTypeString>(),
950
1
                std::make_shared<DataTypeString>()};
951
1
    }
952
953
    Status execute_impl(FunctionContext* context, Block& block, const ColumnNumbers& arguments,
954
2
                        uint32_t result, size_t input_rows_count) const override {
955
2
        CHECK_EQ(arguments.size(), 3);
956
2
        auto col_res = ColumnString::create();
957
2
        bool col_const[3];
958
2
        ColumnPtr argument_columns[3];
959
8
        for (int i = 0; i < 3; ++i) {
960
6
            col_const[i] = is_column_const(*block.get_by_position(arguments[i]).column);
961
6
        }
962
2
        argument_columns[0] = col_const[0] ? static_cast<const ColumnConst&>(
963
0
                                                     *block.get_by_position(arguments[0]).column)
964
0
                                                     .convert_to_full_column()
965
2
                                           : block.get_by_position(arguments[0]).column;
966
2
        default_preprocess_parameter_columns(argument_columns, col_const, {1, 2}, block, arguments);
967
968
2
        const auto* col_source = assert_cast<const ColumnString*>(argument_columns[0].get());
969
2
        const auto* col_from = assert_cast<const ColumnString*>(argument_columns[1].get());
970
2
        const auto* col_to = assert_cast<const ColumnString*>(argument_columns[2].get());
971
972
2
        auto impl_vectors = impl_vectors_utf8<false>;
973
2
        if (col_const[1] && col_const[2]) {
974
            // Non-ASCII mappings require UTF-8 processing regardless of the source.
975
2
            const bool mapping_ascii = col_from->is_ascii() && col_to->is_ascii();
976
2
            if (mapping_ascii) {
977
2
                const bool source_ascii = col_source->is_ascii();
978
2
                impl_vectors = source_ascii ? impl_vectors_ascii<true> : impl_vectors_mixed<true>;
979
2
            } else {
980
0
                impl_vectors = impl_vectors_utf8<true>;
981
0
            }
982
2
        } else {
983
            // A non-ASCII source needs no mapping scans when the mappings vary by row.
984
0
            const bool all_ascii =
985
0
                    col_source->is_ascii() && col_from->is_ascii() && col_to->is_ascii();
986
0
            if (all_ascii) {
987
0
                impl_vectors = impl_vectors_ascii<false>;
988
0
            }
989
0
        }
990
2
        impl_vectors(col_source, col_from, col_to, col_res.get());
991
2
        block.get_by_position(result).column = std::move(col_res);
992
2
        return Status::OK();
993
2
    }
994
995
private:
996
5
    static bool bytes_is_ascii(const char* data, size_t size) {
997
5
        return simd::VStringFunctions::is_ascii({data, size});
998
5
    }
999
1000
    // Per-row dispatch: ASCII source rows use the 128-byte table; only non-ASCII
1001
    // rows fall back to the UTF-8 map. Requires from/to to be ASCII.
1002
    template <bool IsConst>
1003
    static void impl_vectors_mixed(const ColumnString* col_source, const ColumnString* col_from,
1004
2
                                   const ColumnString* col_to, ColumnString* col_res) {
1005
2
        auto& res_chars = col_res->get_chars();
1006
2
        auto& res_offsets = col_res->get_offsets();
1007
2
        res_chars.reserve(col_source->get_chars().size());
1008
2
        res_offsets.reserve(col_source->get_offsets().size());
1009
2
        DCHECK_EQ(col_res->size(), 0);
1010
2
        AsciiMap map;
1011
2
        std::unordered_map<std::string_view, std::string_view> translate_map;
1012
2
        if (IsConst) {
1013
2
            const auto& from_str = col_from->get_data_at(0);
1014
2
            const auto& to_str = col_to->get_data_at(0);
1015
2
            if (!build_translate_map_ascii(map, from_str, to_str)) {
1016
                // No deletes: whole-column table translate; high bytes (>=128) are
1017
                // identity in the map so multi-byte UTF-8 sequences are preserved.
1018
1
                res_offsets.insert(col_source->get_offsets().begin(),
1019
1
                                   col_source->get_offsets().end());
1020
1
                res_chars.insert(col_source->get_chars().begin(), col_source->get_chars().end());
1021
13
                for (size_t i = 0; i < res_chars.size(); ++i) {
1022
12
                    auto c = static_cast<UInt8>(res_chars[i]);
1023
12
                    if (c < 128) {
1024
6
                        res_chars[i] = static_cast<char>(map[c]);
1025
6
                    }
1026
12
                }
1027
1
                return;
1028
1
            }
1029
1
            translate_map =
1030
1
                    build_translate_map_utf8(from_str.to_string_view(), to_str.to_string_view());
1031
1
        }
1032
1033
1
        std::string row_buf;
1034
6
        for (size_t i = 0; i < col_source->size(); ++i) {
1035
5
            const auto& source_str = col_source->get_data_at(i);
1036
5
            if (!IsConst) {
1037
0
                const auto& from_str = col_from->get_data_at(i);
1038
0
                const auto& to_str = col_to->get_data_at(i);
1039
0
                build_translate_map_ascii(map, from_str, to_str);
1040
0
                translate_map = build_translate_map_utf8(from_str.to_string_view(),
1041
0
                                                         to_str.to_string_view());
1042
0
            }
1043
5
            if (bytes_is_ascii(source_str.data, source_str.size)) {
1044
                // ASCII row: O(n) table lookup, no hashing
1045
4
                row_buf.clear();
1046
4
                row_buf.resize(source_str.size);
1047
4
                auto written =
1048
4
                        translate_ascii(source_str, map, reinterpret_cast<UInt8*>(row_buf.data()));
1049
4
                row_buf.resize(written);
1050
4
                col_res->insert_data(row_buf.data(), row_buf.size());
1051
4
            } else {
1052
                // Non-ASCII row: UTF-8 map (built once when IsConst)
1053
1
                auto translated_str = translate_utf8(source_str.to_string_view(), translate_map);
1054
1
                col_res->insert_data(translated_str.data(), translated_str.size());
1055
1
            }
1056
5
        }
1057
1
    }
1058
1059
    template <bool IsConst>
1060
    static void impl_vectors_ascii(const ColumnString* col_source, const ColumnString* col_from,
1061
0
                                   const ColumnString* col_to, ColumnString* col_res) {
1062
0
        auto& res_chars = col_res->get_chars();
1063
0
        auto& res_offsets = col_res->get_offsets();
1064
0
        res_chars.reserve(col_source->get_chars().size());
1065
0
        res_offsets.reserve(col_source->get_offsets().size());
1066
0
        DCHECK_EQ(col_res->size(), 0);
1067
0
        AsciiMap map;
1068
0
        if (IsConst) {
1069
0
            const auto& from_str = col_from->get_data_at(0);
1070
0
            const auto& to_str = col_to->get_data_at(0);
1071
0
            if (!build_translate_map_ascii(map, from_str, to_str)) {
1072
                // if the map is not need delete char, we can directly copy the source string,then use map to translate
1073
0
                res_offsets.insert(col_source->get_offsets().begin(),
1074
0
                                   col_source->get_offsets().end());
1075
0
                res_chars.insert(col_source->get_chars().begin(), col_source->get_chars().end());
1076
0
                for (int i = 0; i < res_chars.size(); ++i) {
1077
0
                    res_chars[i] = map[res_chars[i]]; // translate the chars
1078
0
                }
1079
0
                return; // no need to translate
1080
0
            }
1081
0
        }
1082
1083
0
        auto res_size = 0;
1084
0
        auto* begin_data = col_res->get_chars().data();
1085
0
        for (size_t i = 0; i < col_source->size(); ++i) {
1086
0
            const auto& source_str = col_source->get_data_at(i);
1087
0
            if (!IsConst) {
1088
0
                const auto& from_str = col_from->get_data_at(i);
1089
0
                const auto& to_str = col_to->get_data_at(i);
1090
0
                build_translate_map_ascii(map, from_str, to_str);
1091
0
            }
1092
0
            auto* dst_data = begin_data + res_size;
1093
0
            res_size += translate_ascii(source_str, map, dst_data);
1094
1095
0
            res_offsets.push_back(res_size);
1096
0
        }
1097
0
        DCHECK_GE(res_chars.capacity(), res_size);
1098
0
        res_chars.resize(res_size);
1099
0
    }
Unexecuted instantiation: _ZN5doris17FunctionTranslate18impl_vectors_asciiILb1EEEvPKNS_9ColumnStrIjEES5_S5_PS3_
Unexecuted instantiation: _ZN5doris17FunctionTranslate18impl_vectors_asciiILb0EEEvPKNS_9ColumnStrIjEES5_S5_PS3_
1100
1101
    // return true if no need delete char
1102
    bool static build_translate_map_ascii(AsciiMap& map, const StringRef& from_str,
1103
2
                                          const StringRef& to_str) {
1104
258
        for (size_t i = 0; i < map.size(); ++i) {
1105
256
            map[i] = i; // initialize map to identity
1106
256
        }
1107
2
        std::array<UInt8, 128> set_map {0};
1108
2
        const auto min_size = std::min(from_str.size, to_str.size);
1109
        // all ascii characters are in the range [0, 127]
1110
5
        for (size_t i = 0; i < min_size; ++i) {
1111
3
            auto from_char = from_str.data[i];
1112
3
            auto to_char = to_str.data[i];
1113
3
            if (set_map[from_char] == 0) {
1114
3
                set_map[from_char] = 1;
1115
3
                map[from_char] = to_char;
1116
3
            }
1117
3
        }
1118
1119
2
        bool need_delete_char = false;
1120
1121
3
        for (size_t i = min_size; i < from_str.size; ++i) {
1122
1
            auto from_char = from_str.data[i];
1123
1
            if (set_map[from_char] == 0) {
1124
1
                set_map[from_char] = 1;
1125
1
                map[from_char] = DELETE_CHAR; // delete this char
1126
1
                need_delete_char = true;
1127
1
            }
1128
1
        }
1129
2
        return need_delete_char;
1130
2
    }
1131
1132
4
    static size_t translate_ascii(const StringRef& source_str, AsciiMap& map, UInt8* dst_data) {
1133
4
        auto* begin_data = dst_data;
1134
10
        for (size_t i = 0; i < source_str.size; ++i) {
1135
6
            auto c = source_str.data[i];
1136
6
            if (map[c] == DELETE_CHAR) {
1137
4
                continue; // delete this char
1138
4
            }
1139
2
            *dst_data++ = map[c];
1140
2
        }
1141
4
        return dst_data - begin_data;
1142
4
    }
1143
1144
    template <bool IsConst>
1145
    static void impl_vectors_utf8(const ColumnString* col_source, const ColumnString* col_from,
1146
0
                                  const ColumnString* col_to, ColumnString* col_res) {
1147
0
        col_res->get_chars().reserve(col_source->get_chars().size());
1148
0
        col_res->get_offsets().reserve(col_source->get_offsets().size());
1149
0
        std::unordered_map<std::string_view, std::string_view> translate_map;
1150
0
        if (IsConst) {
1151
0
            const auto& from_str = col_from->get_data_at(0);
1152
0
            const auto& to_str = col_to->get_data_at(0);
1153
0
            translate_map =
1154
0
                    build_translate_map_utf8(from_str.to_string_view(), to_str.to_string_view());
1155
0
        }
1156
0
        for (size_t i = 0; i < col_source->size(); ++i) {
1157
0
            const auto& source_str = col_source->get_data_at(i);
1158
0
            if (!IsConst) {
1159
0
                const auto& from_str = col_from->get_data_at(i);
1160
0
                const auto& to_str = col_to->get_data_at(i);
1161
0
                translate_map = build_translate_map_utf8(from_str.to_string_view(),
1162
0
                                                         to_str.to_string_view());
1163
0
            }
1164
0
            auto translated_str = translate_utf8(source_str.to_string_view(), translate_map);
1165
0
            col_res->insert_data(translated_str.data(), translated_str.size());
1166
0
        }
1167
0
    }
Unexecuted instantiation: _ZN5doris17FunctionTranslate17impl_vectors_utf8ILb0EEEvPKNS_9ColumnStrIjEES5_S5_PS3_
Unexecuted instantiation: _ZN5doris17FunctionTranslate17impl_vectors_utf8ILb1EEEvPKNS_9ColumnStrIjEES5_S5_PS3_
1168
1169
    static std::unordered_map<std::string_view, std::string_view> build_translate_map_utf8(
1170
1
            const std::string_view& from_str, const std::string_view& to_str) {
1171
1
        std::unordered_map<std::string_view, std::string_view> translate_map;
1172
3
        for (size_t i = 0, from_char_size = 0, j = 0, to_char_size = 0; i < from_str.size();
1173
2
             i += from_char_size, j += to_char_size) {
1174
2
            from_char_size = get_utf8_byte_length(from_str[i]);
1175
2
            to_char_size = j < to_str.size() ? get_utf8_byte_length(to_str[j]) : 0;
1176
2
            auto from_char = from_str.substr(i, from_char_size);
1177
2
            if (translate_map.find(from_char) == translate_map.end()) {
1178
2
                translate_map[from_char] =
1179
2
                        j < to_str.size() ? to_str.substr(j, to_char_size) : std::string_view();
1180
2
            }
1181
2
        }
1182
1
        return translate_map;
1183
1
    }
1184
1185
    static std::string translate_utf8(
1186
            const std::string_view& source_str,
1187
1
            std::unordered_map<std::string_view, std::string_view>& translate_map) {
1188
1
        std::string result;
1189
1
        result.reserve(source_str.size());
1190
6
        for (size_t i = 0, char_size = 0; i < source_str.size(); i += char_size) {
1191
5
            char_size = get_utf8_byte_length(source_str[i]);
1192
5
            auto c = source_str.substr(i, char_size);
1193
5
            auto it = translate_map.find(c);
1194
5
            if (it != translate_map.end()) {
1195
3
                if (!it->second.empty()) {
1196
2
                    result.append(it->second);
1197
2
                }
1198
3
            } else {
1199
2
                result.append(c);
1200
2
            }
1201
5
        }
1202
1
        return result;
1203
1
    }
1204
};
1205
1206
/// xpath_string(xml, xpath) -> String
1207
/// Returns the text content of the first node that matches the XPath expression.
1208
/// Returns NULL if either xml or xpath is NULL.
1209
/// Returns empty string if the XPath expression matches no nodes.
1210
/// The text content includes the node and all its descendants.
1211
/// Example:
1212
///   xpath_string('<a><b>b1</b><b>b2</b></a>', '/a/b[1]') = 'b1'
1213
///   xpath_string('<a><b>b1</b><b>b2</b></a>', '/a/b[2]') = 'b2'
1214
///   xpath_string('<a><b>b1</b><b>b2</b></a>', '/a/c') = ''
1215
///   xpath_string('invalid xml', '/a/b[1]') = NULL
1216
///   xpath_string(NULL, '/a/b[1]') = NULL
1217
///   xpath_string('<a><b>b1</b><b>b2</b></a>', NULL) = NULL
1218
class FunctionXPathString : public IFunction {
1219
public:
1220
    static constexpr auto name = "xpath_string";
1221
78
    static FunctionPtr create() { return std::make_shared<FunctionXPathString>(); }
1222
1
    String get_name() const override { return name; }
1223
76
    size_t get_number_of_arguments() const override { return 2; }
1224
76
    DataTypePtr get_return_type_impl(const DataTypes& arguments) const override {
1225
76
        return make_nullable(std::make_shared<DataTypeString>());
1226
76
    }
1227
1228
    Status execute_impl(FunctionContext* context, Block& block, const ColumnNumbers& arguments,
1229
67
                        uint32_t result, size_t input_rows_count) const override {
1230
67
        CHECK_EQ(arguments.size(), 2);
1231
67
        auto col_res = ColumnNullable::create(ColumnString::create(), ColumnUInt8::create());
1232
67
        const auto& [left_col, left_const] =
1233
67
                unpack_if_const(block.get_by_position(arguments[0]).column);
1234
67
        const auto& [right_col, right_const] =
1235
67
                unpack_if_const(block.get_by_position(arguments[1]).column);
1236
67
        const auto& xml_col = *assert_cast<const ColumnString*>(left_col.get());
1237
67
        const auto& xpath_col = *assert_cast<const ColumnString*>(right_col.get());
1238
1239
67
        Status status;
1240
67
        if (left_const && right_const) {
1241
0
            status = execute_vector<true, true>(input_rows_count, xml_col, xpath_col, *col_res);
1242
67
        } else if (left_const) {
1243
22
            status = execute_vector<true, false>(input_rows_count, xml_col, xpath_col, *col_res);
1244
45
        } else if (right_const) {
1245
22
            status = execute_vector<false, true>(input_rows_count, xml_col, xpath_col, *col_res);
1246
23
        } else {
1247
23
            status = execute_vector<false, false>(input_rows_count, xml_col, xpath_col, *col_res);
1248
23
        }
1249
67
        if (!status.ok()) {
1250
0
            return status;
1251
0
        }
1252
1253
67
        block.get_by_position(result).column = std::move(col_res);
1254
67
        return Status::OK();
1255
67
    }
1256
1257
private:
1258
81
    static Status parse_xml(const StringRef& xml_str, pugi::xml_document& xml_doc) {
1259
81
        pugi::xml_parse_result result = xml_doc.load_buffer(xml_str.data, xml_str.size);
1260
81
        if (!result) {
1261
0
            return Status::InvalidArgument("Function {} failed to parse XML string: {}", name,
1262
0
                                           result.description());
1263
0
        }
1264
81
        return Status::OK();
1265
81
    }
1266
1267
84
    static Status build_xpath_query(const StringRef& xpath_str, pugi::xpath_query& xpath_query) {
1268
        // xpath_query will throws xpath_exception on compilation errors.
1269
84
        try {
1270
            // NOTE!!!: don't use to_string_view(), because xpath_str maybe not null-terminated
1271
84
            xpath_query = pugi::xpath_query(xpath_str.to_string().c_str());
1272
84
        } catch (const pugi::xpath_exception& e) {
1273
0
            return Status::InvalidArgument("Function {} failed to build XPath query: {}", name,
1274
0
                                           e.what());
1275
0
        }
1276
84
        return Status::OK();
1277
84
    }
1278
1279
    template <bool left_const, bool right_const>
1280
    static Status execute_vector(const size_t input_rows_count, const ColumnString& xml_col,
1281
67
                                 const ColumnString& xpath_col, ColumnNullable& res_col) {
1282
67
        pugi::xml_document xml_doc;
1283
67
        pugi::xpath_query xpath_query;
1284
        // first check right_const, because we want to check empty input first
1285
67
        if constexpr (right_const) {
1286
22
            auto xpath_str = xpath_col.get_data_at(0);
1287
22
            if (xpath_str.empty()) {
1288
                // should return null if xpath_str is empty
1289
1
                res_col.insert_many_defaults(input_rows_count);
1290
1
                return Status::OK();
1291
1
            }
1292
21
            RETURN_IF_ERROR(build_xpath_query(xpath_str, xpath_query));
1293
21
        }
1294
22
        if constexpr (left_const) {
1295
22
            auto xml_str = xml_col.get_data_at(0);
1296
22
            if (xml_str.empty()) {
1297
                // should return null if xml_str is empty
1298
1
                res_col.insert_many_defaults(input_rows_count);
1299
1
                return Status::OK();
1300
1
            }
1301
21
            RETURN_IF_ERROR(parse_xml(xml_str, xml_doc));
1302
21
        }
1303
1304
156
        for (size_t i = 0; i < input_rows_count; ++i) {
1305
89
            if constexpr (!right_const) {
1306
68
                auto xpath_str = xpath_col.get_data_at(i);
1307
68
                if (xpath_str.empty()) {
1308
                    // should return null if xpath_str is empty
1309
5
                    res_col.insert_default();
1310
5
                    continue;
1311
5
                }
1312
63
                RETURN_IF_ERROR(build_xpath_query(xpath_str, xpath_query));
1313
63
            }
1314
68
            if constexpr (!left_const) {
1315
68
                auto xml_str = xml_col.get_data_at(i);
1316
68
                if (xml_str.empty()) {
1317
                    // should return null if xml_str is empty
1318
4
                    res_col.insert_default();
1319
4
                    continue;
1320
4
                }
1321
64
                RETURN_IF_ERROR(parse_xml(xml_str, xml_doc));
1322
64
            }
1323
64
            std::string text;
1324
89
            try {
1325
89
                text = xpath_query.evaluate_string(xml_doc);
1326
89
            } catch (const pugi::xpath_exception& e) {
1327
0
                return Status::InvalidArgument("Function {} failed to query XPath string: {}", name,
1328
0
                                               e.what());
1329
0
            }
1330
80
            res_col.insert_data(text.data(), text.size());
1331
80
        }
1332
67
        return Status::OK();
1333
67
    }
Unexecuted instantiation: _ZN5doris19FunctionXPathString14execute_vectorILb1ELb1EEENS_6StatusEmRKNS_9ColumnStrIjEES6_RNS_14ColumnNullableE
_ZN5doris19FunctionXPathString14execute_vectorILb1ELb0EEENS_6StatusEmRKNS_9ColumnStrIjEES6_RNS_14ColumnNullableE
Line
Count
Source
1281
22
                                 const ColumnString& xpath_col, ColumnNullable& res_col) {
1282
22
        pugi::xml_document xml_doc;
1283
22
        pugi::xpath_query xpath_query;
1284
        // first check right_const, because we want to check empty input first
1285
        if constexpr (right_const) {
1286
            auto xpath_str = xpath_col.get_data_at(0);
1287
            if (xpath_str.empty()) {
1288
                // should return null if xpath_str is empty
1289
                res_col.insert_many_defaults(input_rows_count);
1290
                return Status::OK();
1291
            }
1292
            RETURN_IF_ERROR(build_xpath_query(xpath_str, xpath_query));
1293
        }
1294
22
        if constexpr (left_const) {
1295
22
            auto xml_str = xml_col.get_data_at(0);
1296
22
            if (xml_str.empty()) {
1297
                // should return null if xml_str is empty
1298
1
                res_col.insert_many_defaults(input_rows_count);
1299
1
                return Status::OK();
1300
1
            }
1301
21
            RETURN_IF_ERROR(parse_xml(xml_str, xml_doc));
1302
21
        }
1303
1304
43
        for (size_t i = 0; i < input_rows_count; ++i) {
1305
21
            if constexpr (!right_const) {
1306
21
                auto xpath_str = xpath_col.get_data_at(i);
1307
21
                if (xpath_str.empty()) {
1308
                    // should return null if xpath_str is empty
1309
1
                    res_col.insert_default();
1310
1
                    continue;
1311
1
                }
1312
20
                RETURN_IF_ERROR(build_xpath_query(xpath_str, xpath_query));
1313
20
            }
1314
            if constexpr (!left_const) {
1315
                auto xml_str = xml_col.get_data_at(i);
1316
                if (xml_str.empty()) {
1317
                    // should return null if xml_str is empty
1318
                    res_col.insert_default();
1319
                    continue;
1320
                }
1321
                RETURN_IF_ERROR(parse_xml(xml_str, xml_doc));
1322
            }
1323
21
            std::string text;
1324
21
            try {
1325
21
                text = xpath_query.evaluate_string(xml_doc);
1326
21
            } catch (const pugi::xpath_exception& e) {
1327
0
                return Status::InvalidArgument("Function {} failed to query XPath string: {}", name,
1328
0
                                               e.what());
1329
0
            }
1330
20
            res_col.insert_data(text.data(), text.size());
1331
20
        }
1332
22
        return Status::OK();
1333
22
    }
_ZN5doris19FunctionXPathString14execute_vectorILb0ELb1EEENS_6StatusEmRKNS_9ColumnStrIjEES6_RNS_14ColumnNullableE
Line
Count
Source
1281
22
                                 const ColumnString& xpath_col, ColumnNullable& res_col) {
1282
22
        pugi::xml_document xml_doc;
1283
22
        pugi::xpath_query xpath_query;
1284
        // first check right_const, because we want to check empty input first
1285
22
        if constexpr (right_const) {
1286
22
            auto xpath_str = xpath_col.get_data_at(0);
1287
22
            if (xpath_str.empty()) {
1288
                // should return null if xpath_str is empty
1289
1
                res_col.insert_many_defaults(input_rows_count);
1290
1
                return Status::OK();
1291
1
            }
1292
21
            RETURN_IF_ERROR(build_xpath_query(xpath_str, xpath_query));
1293
21
        }
1294
        if constexpr (left_const) {
1295
            auto xml_str = xml_col.get_data_at(0);
1296
            if (xml_str.empty()) {
1297
                // should return null if xml_str is empty
1298
                res_col.insert_many_defaults(input_rows_count);
1299
                return Status::OK();
1300
            }
1301
            RETURN_IF_ERROR(parse_xml(xml_str, xml_doc));
1302
        }
1303
1304
43
        for (size_t i = 0; i < input_rows_count; ++i) {
1305
            if constexpr (!right_const) {
1306
                auto xpath_str = xpath_col.get_data_at(i);
1307
                if (xpath_str.empty()) {
1308
                    // should return null if xpath_str is empty
1309
                    res_col.insert_default();
1310
                    continue;
1311
                }
1312
                RETURN_IF_ERROR(build_xpath_query(xpath_str, xpath_query));
1313
            }
1314
21
            if constexpr (!left_const) {
1315
21
                auto xml_str = xml_col.get_data_at(i);
1316
21
                if (xml_str.empty()) {
1317
                    // should return null if xml_str is empty
1318
1
                    res_col.insert_default();
1319
1
                    continue;
1320
1
                }
1321
20
                RETURN_IF_ERROR(parse_xml(xml_str, xml_doc));
1322
20
            }
1323
20
            std::string text;
1324
21
            try {
1325
21
                text = xpath_query.evaluate_string(xml_doc);
1326
21
            } catch (const pugi::xpath_exception& e) {
1327
0
                return Status::InvalidArgument("Function {} failed to query XPath string: {}", name,
1328
0
                                               e.what());
1329
0
            }
1330
20
            res_col.insert_data(text.data(), text.size());
1331
20
        }
1332
22
        return Status::OK();
1333
22
    }
_ZN5doris19FunctionXPathString14execute_vectorILb0ELb0EEENS_6StatusEmRKNS_9ColumnStrIjEES6_RNS_14ColumnNullableE
Line
Count
Source
1281
23
                                 const ColumnString& xpath_col, ColumnNullable& res_col) {
1282
23
        pugi::xml_document xml_doc;
1283
23
        pugi::xpath_query xpath_query;
1284
        // first check right_const, because we want to check empty input first
1285
        if constexpr (right_const) {
1286
            auto xpath_str = xpath_col.get_data_at(0);
1287
            if (xpath_str.empty()) {
1288
                // should return null if xpath_str is empty
1289
                res_col.insert_many_defaults(input_rows_count);
1290
                return Status::OK();
1291
            }
1292
            RETURN_IF_ERROR(build_xpath_query(xpath_str, xpath_query));
1293
        }
1294
        if constexpr (left_const) {
1295
            auto xml_str = xml_col.get_data_at(0);
1296
            if (xml_str.empty()) {
1297
                // should return null if xml_str is empty
1298
                res_col.insert_many_defaults(input_rows_count);
1299
                return Status::OK();
1300
            }
1301
            RETURN_IF_ERROR(parse_xml(xml_str, xml_doc));
1302
        }
1303
1304
70
        for (size_t i = 0; i < input_rows_count; ++i) {
1305
47
            if constexpr (!right_const) {
1306
47
                auto xpath_str = xpath_col.get_data_at(i);
1307
47
                if (xpath_str.empty()) {
1308
                    // should return null if xpath_str is empty
1309
4
                    res_col.insert_default();
1310
4
                    continue;
1311
4
                }
1312
43
                RETURN_IF_ERROR(build_xpath_query(xpath_str, xpath_query));
1313
43
            }
1314
47
            if constexpr (!left_const) {
1315
47
                auto xml_str = xml_col.get_data_at(i);
1316
47
                if (xml_str.empty()) {
1317
                    // should return null if xml_str is empty
1318
3
                    res_col.insert_default();
1319
3
                    continue;
1320
3
                }
1321
44
                RETURN_IF_ERROR(parse_xml(xml_str, xml_doc));
1322
44
            }
1323
44
            std::string text;
1324
47
            try {
1325
47
                text = xpath_query.evaluate_string(xml_doc);
1326
47
            } catch (const pugi::xpath_exception& e) {
1327
0
                return Status::InvalidArgument("Function {} failed to query XPath string: {}", name,
1328
0
                                               e.what());
1329
0
            }
1330
40
            res_col.insert_data(text.data(), text.size());
1331
40
        }
1332
23
        return Status::OK();
1333
23
    }
1334
};
1335
1336
class MakeSetImpl {
1337
public:
1338
    static constexpr auto name = "make_set";
1339
1340
0
    static size_t get_number_of_arguments() { return 0; }
1341
7
    static bool is_variadic() { return true; }
1342
6
    static DataTypePtr get_return_type_impl(const DataTypes& arguments) {
1343
6
        if (arguments[0].get()->is_nullable()) {
1344
3
            return make_nullable(std::make_shared<DataTypeString>());
1345
3
        }
1346
3
        return std::make_shared<DataTypeString>();
1347
6
    }
1348
1349
    static bool is_return_nullable(bool has_nullable,
1350
6
                                   const std::vector<ColumnWithConstAndNullMap>& cols_info) {
1351
6
        return cols_info[0].null_map != nullptr;
1352
6
    }
1353
1354
    static bool execute_const_null(ColumnString::MutablePtr& res_col,
1355
                                   PaddedPODArray<UInt8>& res_null_map_data,
1356
6
                                   size_t input_rows_count, size_t null_index) {
1357
        // Only a NULL bits argument makes the result NULL; NULL strings are skipped.
1358
6
        if (null_index == 0) {
1359
0
            res_col->insert_many_defaults(input_rows_count);
1360
0
            res_null_map_data.assign(input_rows_count, (UInt8)1);
1361
0
            return true;
1362
0
        }
1363
6
        return false;
1364
6
    }
1365
1366
    static void execute(const std::vector<ColumnWithConstAndNullMap>& column_infos,
1367
                        ColumnString::MutablePtr& res_col, PaddedPODArray<UInt8>& res_null_map_data,
1368
6
                        size_t input_rows_count) {
1369
6
        static constexpr char SEPARATOR = ',';
1370
6
        const auto& bit_data =
1371
6
                assert_cast<const ColumnInt64&>(*column_infos[0].nested_col).get_data();
1372
6
        std::vector<const ColumnString*> str_cols(column_infos.size());
1373
18
        for (size_t i = 1; i < column_infos.size(); ++i) {
1374
12
            str_cols[i] = assert_cast<const ColumnString*>(column_infos[i].nested_col);
1375
12
        }
1376
1377
12
        for (size_t row = 0; row < input_rows_count; ++row) {
1378
6
            if (column_infos[0].is_null_at(row)) {
1379
1
                res_col->insert_default();
1380
1
                res_null_map_data[row] = 1;
1381
1
                continue;
1382
1
            }
1383
1384
5
            uint64_t bit = bit_data[column_infos[0].is_const ? 0 : row];
1385
5
            uint64_t col_pos = __builtin_ffsll(bit);
1386
5
            ColumnString::Chars data;
1387
9
            while (col_pos != 0 && col_pos < column_infos.size() && bit != 0) {
1388
4
                if (!column_infos[col_pos].is_null_at(row)) {
1389
                    /* Here insert `str,` directly to support the case below:
1390
                     * SELECT MAKE_SET(3, '', 'a');
1391
                     * the exception result should be ',a'.
1392
                     */
1393
3
                    auto s_ref = str_cols[col_pos]->get_data_at(
1394
3
                            column_infos[col_pos].is_const ? 0 : row);
1395
3
                    data.insert(s_ref.data, s_ref.data + s_ref.size);
1396
3
                    data.push_back(SEPARATOR);
1397
3
                }
1398
4
                bit &= ~(1ULL << (col_pos - 1));
1399
4
                col_pos = __builtin_ffsll(bit);
1400
4
            }
1401
            // remove the last ','
1402
5
            if (!data.empty()) {
1403
3
                data.pop_back();
1404
3
            }
1405
5
            res_col->insert_data(reinterpret_cast<const char*>(data.data()), data.size());
1406
5
        }
1407
6
    }
1408
};
1409
1410
class FunctionExportSet : public IFunction {
1411
public:
1412
    static constexpr auto name = "export_set";
1413
2
    static FunctionPtr create() { return std::make_shared<FunctionExportSet>(); }
1414
0
    String get_name() const override { return name; }
1415
0
    size_t get_number_of_arguments() const override { return 0; }
1416
1
    bool is_variadic() const override { return true; }
1417
0
    DataTypePtr get_return_type_impl(const DataTypes& arguments) const override {
1418
0
        return std::make_shared<DataTypeString>();
1419
0
    }
1420
1421
    Status execute_impl(FunctionContext* context, Block& block, const ColumnNumbers& arguments,
1422
0
                        uint32_t result, size_t input_rows_count) const override {
1423
0
        auto res_col = ColumnString::create();
1424
1425
0
        const size_t arg_size = arguments.size();
1426
0
        bool col_const[5];
1427
0
        ColumnPtr arg_cols[5];
1428
0
        bool all_const = true;
1429
0
        for (int i = 1; i < arg_size; ++i) {
1430
0
            col_const[i] = is_column_const(*block.get_by_position(arguments[i]).column);
1431
0
            all_const = all_const && col_const[i];
1432
0
        }
1433
0
        std::tie(arg_cols[0], col_const[0]) =
1434
0
                unpack_if_const(block.get_by_position(arguments[0]).column);
1435
0
        if (arg_size == 3) {
1436
0
            default_preprocess_parameter_columns(arg_cols, col_const, {1, 2}, block, arguments);
1437
0
        } else if (arg_size == 4) {
1438
0
            default_preprocess_parameter_columns(arg_cols, col_const, {1, 2, 3}, block, arguments);
1439
0
        } else if (arg_size == 5) {
1440
0
            default_preprocess_parameter_columns(arg_cols, col_const, {1, 2, 3, 4}, block,
1441
0
                                                 arguments);
1442
0
        }
1443
1444
0
        const auto* bit_col = assert_cast<const ColumnInt128*>(arg_cols[0].get());
1445
0
        const auto* on_col = assert_cast<const ColumnString*>(arg_cols[1].get());
1446
0
        const auto* off_col = assert_cast<const ColumnString*>(arg_cols[2].get());
1447
0
        const ColumnString* sep_col = nullptr;
1448
0
        const ColumnInt32* num_bits_col = nullptr;
1449
0
        if (arg_size > 3) {
1450
0
            sep_col = assert_cast<const ColumnString*>(arg_cols[3].get());
1451
0
            if (arg_size == 5) {
1452
0
                num_bits_col = assert_cast<const ColumnInt32*>(arg_cols[4].get());
1453
0
            }
1454
0
        }
1455
1456
0
        for (size_t i = 0; i < input_rows_count; ++i) {
1457
0
            uint64_t bit =
1458
0
                    check_and_get_bit(bit_col->get_element(index_check_const(i, col_const[0])));
1459
1460
0
            size_t idx_for_args = all_const ? 0 : i;
1461
0
            StringRef on = on_col->get_data_at(idx_for_args);
1462
0
            StringRef off = off_col->get_data_at(idx_for_args);
1463
0
            StringRef separator(",", 1);
1464
0
            int8_t num_of_bits = 64;
1465
1466
0
            if (arg_size > 3) {
1467
0
                separator = sep_col->get_data_at(idx_for_args);
1468
0
                if (arg_size == 5) {
1469
0
                    num_of_bits =
1470
0
                            check_and_get_num_of_bits(num_bits_col->get_element(idx_for_args));
1471
0
                }
1472
0
            }
1473
1474
0
            execute_single(bit, on, off, separator, num_of_bits, *res_col);
1475
0
        }
1476
0
        block.replace_by_position(result, std::move(res_col));
1477
0
        return Status::OK();
1478
0
    }
1479
1480
private:
1481
    /* The valid range of the input `bit` parameter should be [-2^63, 2^64 - 1]
1482
     * If it exceeds this range, the MAX/MIN values of the signed 64-bit integer are used for calculation
1483
     * This behavior is consistent with MySQL.
1484
     */
1485
0
    uint64_t check_and_get_bit(__int128 col_bit_val) const {
1486
0
        if (col_bit_val > ULLONG_MAX) {
1487
0
            return LLONG_MAX;
1488
0
        } else if (col_bit_val < LLONG_MIN) {
1489
0
            return LLONG_MIN;
1490
0
        }
1491
0
        return static_cast<uint64_t>(col_bit_val);
1492
0
    }
1493
1494
    // If the input value is not in the range [0, 64], return default value 64
1495
0
    int8_t check_and_get_num_of_bits(int32_t col_num_of_bits_val) const {
1496
0
        if (col_num_of_bits_val >= 0 && col_num_of_bits_val <= 64) {
1497
0
            return static_cast<int8_t>(col_num_of_bits_val);
1498
0
        }
1499
0
        return 64;
1500
0
    }
1501
1502
    void execute_single(uint64_t bit, const StringRef& on, const StringRef& off,
1503
                        const StringRef& separator, int8_t num_of_bits,
1504
0
                        ColumnString& res_col) const {
1505
0
        ColumnString::Chars data;
1506
0
        data.reserve(std::max(on.size, off.size) * num_of_bits +
1507
0
                     separator.size * (num_of_bits - 1));
1508
1509
0
        while (bit && num_of_bits) {
1510
0
            if (bit & 1) {
1511
0
                data.insert(on.data, on.data + on.size);
1512
0
            } else {
1513
0
                data.insert(off.data, off.data + off.size);
1514
0
            }
1515
0
            bit >>= 1;
1516
0
            if (--num_of_bits) {
1517
0
                data.insert(separator.data, separator.data + separator.size);
1518
0
            }
1519
0
        }
1520
1521
0
        if (num_of_bits > 0) {
1522
0
            ColumnString::Chars off_sep_combo;
1523
0
            off_sep_combo.reserve(separator.size + off.size);
1524
0
            off_sep_combo.insert(off_sep_combo.end(), off.data, off.data + off.size);
1525
0
            off_sep_combo.insert(off_sep_combo.end(), separator.data,
1526
0
                                 separator.data + separator.size);
1527
1528
0
            for (size_t i = 0; i < num_of_bits; ++i) {
1529
0
                data.insert(off_sep_combo.data(), off_sep_combo.data() + off_sep_combo.size());
1530
0
            }
1531
0
            data.erase(data.end() - separator.size, data.end());
1532
0
        }
1533
1534
0
        res_col.insert_data(reinterpret_cast<const char*>(data.data()), data.size());
1535
0
    }
1536
};
1537
1538
// ATTN: for debug only
1539
// compute crc32 hash value as the same way in `VOlapTablePartitionParam::find_tablets()`
1540
class FunctionCrc32Internal : public IFunction {
1541
public:
1542
    static constexpr auto name = "crc32_internal";
1543
2
    static FunctionPtr create() { return std::make_shared<FunctionCrc32Internal>(); }
1544
0
    String get_name() const override { return name; }
1545
0
    size_t get_number_of_arguments() const override { return 0; }
1546
1
    bool is_variadic() const override { return true; }
1547
0
    bool use_default_implementation_for_nulls() const override { return false; }
1548
0
    DataTypePtr get_return_type_impl(const DataTypes& arguments) const override {
1549
0
        return std::make_shared<DataTypeInt64>();
1550
0
    }
1551
1552
    Status execute_impl(FunctionContext* context, Block& block, const ColumnNumbers& arguments,
1553
0
                        uint32_t result, size_t input_rows_count) const override {
1554
0
        DCHECK_GE(arguments.size(), 1);
1555
1556
0
        auto argument_size = arguments.size();
1557
0
        std::vector<ColumnPtr> argument_columns(argument_size);
1558
0
        std::vector<PrimitiveType> argument_primitive_types(argument_size);
1559
1560
0
        for (size_t i = 0; i < argument_size; ++i) {
1561
0
            argument_columns[i] =
1562
0
                    block.get_by_position(arguments[i]).column->convert_to_full_column_if_const();
1563
0
            argument_primitive_types[i] =
1564
0
                    block.get_by_position(arguments[i]).type->get_primitive_type();
1565
0
        }
1566
1567
0
        auto res_col = ColumnInt64::create();
1568
0
        auto& res_data = res_col->get_data();
1569
0
        res_data.resize_fill(input_rows_count, 0);
1570
1571
0
        for (size_t i = 0; i < input_rows_count; ++i) {
1572
0
            uint32_t hash_val = 0;
1573
0
            for (size_t j = 0; j < argument_size; ++j) {
1574
0
                const auto& column = argument_columns[j];
1575
0
                auto primitive_type = argument_primitive_types[j];
1576
0
                auto val = column->get_data_at(i);
1577
0
                if (val.data != nullptr) {
1578
0
                    hash_val = RawValue::zlib_crc32(val.data, val.size, primitive_type, hash_val);
1579
0
                } else {
1580
0
                    hash_val = HashUtil::zlib_crc_hash_null(hash_val);
1581
0
                }
1582
0
            }
1583
0
            res_data[i] = hash_val;
1584
0
        }
1585
1586
0
        block.replace_by_position(result, std::move(res_col));
1587
0
        return Status::OK();
1588
0
    }
1589
};
1590
1591
class FunctionUnicodeNormalize : public IFunction {
1592
public:
1593
    static constexpr auto name = "unicode_normalize";
1594
1595
9
    static FunctionPtr create() { return std::make_shared<FunctionUnicodeNormalize>(); }
1596
1597
3
    String get_name() const override { return name; }
1598
1599
7
    size_t get_number_of_arguments() const override { return 2; }
1600
1601
7
    DataTypePtr get_return_type_impl(const DataTypes& arguments) const override {
1602
7
        if (arguments.size() != 2 || !is_string_type(arguments[0]->get_primitive_type()) ||
1603
7
            !is_string_type(arguments[1]->get_primitive_type())) {
1604
0
            throw doris::Exception(ErrorCode::INVALID_ARGUMENT,
1605
0
                                   "Illegal type {} and {} of arguments of function {}",
1606
0
                                   arguments[0]->get_name(), arguments[1]->get_name(), get_name());
1607
0
        }
1608
7
        return arguments[0];
1609
7
    }
1610
1611
10
    ColumnNumbers get_arguments_that_are_always_constant() const override { return {1}; }
1612
1613
12
    Status open(FunctionContext* context, FunctionContext::FunctionStateScope scope) override {
1614
12
        if (scope == FunctionContext::FunctionStateScope::THREAD_LOCAL) {
1615
5
            return Status::OK();
1616
5
        }
1617
1618
7
        if (!context->is_col_constant(1)) {
1619
1
            return Status::InvalidArgument(
1620
1
                    "The second argument 'mode' of function {} must be constant", get_name());
1621
1
        }
1622
1623
6
        auto* const_col = context->get_constant_col(1);
1624
6
        auto mode_ref = const_col->column_ptr->get_data_at(0);
1625
6
        std::string lower_mode = doris::to_lower(std::string(doris::trim(mode_ref.to_string())));
1626
1627
6
        UErrorCode status = U_ZERO_ERROR;
1628
6
        const icu::Normalizer2* normalizer = nullptr;
1629
1630
6
        if (lower_mode == "nfc") {
1631
2
            normalizer = icu::Normalizer2::getInstance(nullptr, "nfc", UNORM2_COMPOSE, status);
1632
4
        } else if (lower_mode == "nfd") {
1633
1
            normalizer = icu::Normalizer2::getNFDInstance(status);
1634
3
        } else if (lower_mode == "nfkc") {
1635
0
            normalizer = icu::Normalizer2::getInstance(nullptr, "nfkc", UNORM2_COMPOSE, status);
1636
3
        } else if (lower_mode == "nfkd") {
1637
1
            normalizer = icu::Normalizer2::getNFKDInstance(status);
1638
2
        } else if (lower_mode == "nfkc_cf") {
1639
1
            normalizer = icu::Normalizer2::getInstance(nullptr, "nfkc_cf", UNORM2_COMPOSE, status);
1640
1
        } else {
1641
1
            return Status::InvalidArgument(
1642
1
                    "Invalid normalization mode '{}' for function {}. "
1643
1
                    "Supported modes: NFC, NFD, NFKC, NFKD, NFKC_CF",
1644
1
                    lower_mode, get_name());
1645
1
        }
1646
1647
5
        if (U_FAILURE(status) || normalizer == nullptr) {
1648
0
            return Status::InvalidArgument(
1649
0
                    "Failed to get normalizer instance for mode '{}' in function {}: {}",
1650
0
                    lower_mode, get_name(), u_errorName(status));
1651
0
        }
1652
1653
5
        auto state = std::make_shared<UnicodeNormalizeState>();
1654
5
        state->normalizer = normalizer;
1655
5
        context->set_function_state(scope, state);
1656
5
        return Status::OK();
1657
5
    }
1658
1659
    Status execute_impl(FunctionContext* context, Block& block, const ColumnNumbers& arguments,
1660
5
                        uint32_t result, size_t input_rows_count) const override {
1661
5
        auto* state = reinterpret_cast<UnicodeNormalizeState*>(
1662
5
                context->get_function_state(FunctionContext::FunctionStateScope::FRAGMENT_LOCAL));
1663
5
        if (state == nullptr || state->normalizer == nullptr) {
1664
0
            return Status::RuntimeError("unicode_normalize function state is not initialized");
1665
0
        }
1666
1667
5
        ColumnPtr col =
1668
5
                block.get_by_position(arguments[0]).column->convert_to_full_column_if_const();
1669
5
        const auto* col_str = check_and_get_column<ColumnString>(col.get());
1670
5
        if (col_str == nullptr) {
1671
0
            return Status::RuntimeError("Illegal column {} of argument of function {}",
1672
0
                                        block.get_by_position(arguments[0]).column->get_name(),
1673
0
                                        get_name());
1674
0
        }
1675
1676
5
        const auto& data = col_str->get_chars();
1677
5
        const auto& offsets = col_str->get_offsets();
1678
1679
5
        auto res = ColumnString::create();
1680
5
        auto& res_data = res->get_chars();
1681
5
        auto& res_offsets = res->get_offsets();
1682
1683
5
        size_t rows = offsets.size();
1684
5
        res_offsets.resize(rows);
1685
1686
5
        std::string tmp;
1687
10
        for (size_t i = 0; i < rows; ++i) {
1688
5
            const char* begin = reinterpret_cast<const char*>(&data[offsets[i - 1]]);
1689
5
            size_t len = offsets[i] - offsets[i - 1];
1690
1691
5
            normalize_one(state->normalizer, begin, len, tmp);
1692
5
            StringOP::push_value_string(tmp, i, res_data, res_offsets);
1693
5
        }
1694
1695
5
        block.replace_by_position(result, std::move(res));
1696
5
        return Status::OK();
1697
5
    }
1698
1699
private:
1700
    struct UnicodeNormalizeState {
1701
        const icu::Normalizer2* normalizer = nullptr;
1702
    };
1703
1704
    static void normalize_one(const icu::Normalizer2* normalizer, const char* input, size_t length,
1705
5
                              std::string& output) {
1706
5
        if (length == 0) {
1707
0
            output.clear();
1708
0
            return;
1709
0
        }
1710
1711
5
        icu::StringPiece sp(input, static_cast<int32_t>(length));
1712
5
        icu::UnicodeString src16 = icu::UnicodeString::fromUTF8(sp);
1713
1714
5
        UErrorCode status = U_ZERO_ERROR;
1715
5
        UNormalizationCheckResult quick = normalizer->quickCheck(src16, status);
1716
5
        if (U_SUCCESS(status) && quick == UNORM_YES) {
1717
2
            output.assign(input, length);
1718
2
            return;
1719
2
        }
1720
1721
3
        icu::UnicodeString result16;
1722
3
        status = U_ZERO_ERROR;
1723
3
        normalizer->normalize(src16, result16, status);
1724
3
        if (U_FAILURE(status)) {
1725
0
            output.assign(input, length);
1726
0
            return;
1727
0
        }
1728
1729
3
        output.clear();
1730
3
        result16.toUTF8String(output);
1731
3
    }
1732
};
1733
1734
using FunctionMakeSet = FunctionNeedsToHandleNull<MakeSetImpl, PrimitiveType::TYPE_STRING>;
1735
1736
1
void register_function_string_misc(SimpleFunctionFactory& factory) {
1737
1
    factory.register_function<FunctionAutoPartitionName>();
1738
1
    factory.register_function<FunctionConvertTo>();
1739
1
    factory.register_function<FunctionIntToChar>();
1740
1
    factory.register_function<FunctionRandomBytes>();
1741
1
    factory.register_function<FunctionTranslate>();
1742
1
    factory.register_function<FunctionNgramSearch>();
1743
1
    factory.register_function<FunctionXPathString>();
1744
1
    factory.register_function<FunctionCrc32Internal>();
1745
1
    factory.register_function<FunctionMakeSet>();
1746
1
    factory.register_function<FunctionExportSet>();
1747
1
    factory.register_function<FunctionUnicodeNormalize>();
1748
1
}
1749
1750
#include "common/compile_check_avoid_end.h"
1751
} // namespace doris