Coverage Report

Created: 2026-08-26 14:46

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/exprs/function/functions_multi_string_search.h
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
// This file is copied from
18
// https://github.com/ClickHouse/ClickHouse/blob/master/src/Functions/FunctionsMultiStringSearch.h
19
// and modified by Doris
20
21
#pragma once
22
23
#include <hs/hs_runtime.h>
24
25
#include <algorithm>
26
#include <cstddef>
27
#include <limits>
28
#include <memory>
29
#include <optional>
30
#include <vector>
31
32
#include "common/status.h"
33
#include "core/column/column_array.h"
34
#include "core/column/column_nullable.h"
35
#include "core/column/column_string.h"
36
#include "core/data_type/data_type_number.h"
37
#include "core/field.h"
38
#include "core/pod_array_fwd.h"
39
#include "core/string_ref.h"
40
#include "core/types.h"
41
#include "exprs/function/function_helpers.h"
42
#include "exprs/function/regexps.h"
43
44
namespace doris {
45
46
/// For more readable instantiations of MultiMatchAnyImpl<>
47
struct MultiMatchTraits {
48
    enum class Find { Any, AnyIndex };
49
};
50
51
template <PrimitiveType PType, MultiMatchTraits::Find Find, bool WithEditDistance>
52
struct FunctionMultiMatchAnyImpl {
53
    using ResultType = typename PrimitiveTypeTraits<PType>::CppType;
54
    static constexpr PrimitiveType ResultPType = PType;
55
56
    static constexpr bool FindAny = (Find == MultiMatchTraits::Find::Any);
57
    static constexpr bool FindAnyIndex = (Find == MultiMatchTraits::Find::AnyIndex);
58
59
    static constexpr auto name = "multi_match_any";
60
61
0
    static auto get_return_type() {
62
0
        return std::make_shared<typename PrimitiveTypeTraits<PType>::DataType>();
63
0
    }
64
65
    /**
66
     * Prepares the regular expressions and scratch space for Hyperscan.
67
     *
68
     * This function takes a vector of needles (substrings to search for) and initializes
69
     * the regular expressions and scratch space required for Hyperscan, a high-performance
70
     * regular expression matching library.
71
     *
72
     */
73
    static Status prepare_regexps_and_scratch(const std::vector<StringRef>& needles,
74
                                              multiregexps::RegexpsPtr& regexps,
75
1
                                              multiregexps::ScratchPtr& smart_scratch) {
76
1
        multiregexps::DeferredConstructedRegexpsPtr deferred_constructed_regexps =
77
1
                multiregexps::getOrSet</*SaveIndices*/
78
1
                                       FindAnyIndex, WithEditDistance>(needles, std::nullopt);
79
1
        regexps = deferred_constructed_regexps->get();
80
81
1
        hs_scratch_t* scratch = nullptr;
82
1
        hs_error_t err = hs_clone_scratch(regexps->getScratch(), &scratch);
83
84
1
        if (err != HS_SUCCESS) {
85
0
            return Status::InternalError("could not clone scratch space for vectorscan");
86
0
        }
87
88
1
        smart_scratch.reset(scratch);
89
1
        return Status::OK();
90
1
    }
91
92
    /**
93
     * Static callback function to handle the match results of the hs_scan function.
94
     *
95
     * This function is called when a matching substring is found while scanning with
96
     * Hyperscan. It updates the result based on the match information.
97
     *
98
     */
99
    static int on_match([[maybe_unused]] unsigned int id, unsigned long long /* from */, // NOLINT
100
                        unsigned long long /* to */,                                     // NOLINT
101
1
                        unsigned int /* flags */, void* context) {
102
        if constexpr (FindAnyIndex) {
103
            *reinterpret_cast<ResultType*>(context) = id;
104
1
        } else if constexpr (FindAny) {
105
1
            *reinterpret_cast<ResultType*>(context) = 1;
106
1
        }
107
        /// Once we hit the callback, there is no need to search for others.
108
1
        return 1;
109
1
    }
110
111
    static Status vector_constant(const ColumnString::Chars& haystack_data,
112
                                  const ColumnString::Offsets& haystack_offsets,
113
                                  const Array& needles_arr, PaddedPODArray<ResultType>& res,
114
                                  PaddedPODArray<UInt64>& offsets, bool allow_hyperscan,
115
                                  size_t max_hyperscan_regexp_length,
116
0
                                  size_t max_hyperscan_regexp_total_length) {
117
0
        if (!allow_hyperscan) {
118
0
            return Status::InvalidArgument("Hyperscan functions are disabled");
119
0
        }
120
121
0
        std::vector<StringRef> needles;
122
0
        needles.reserve(needles_arr.size());
123
0
        for (const auto& needle : needles_arr) {
124
0
            const auto& tmp = needle.get<TYPE_STRING>();
125
0
            needles.emplace_back(StringRef {tmp.data(), tmp.size()});
126
0
        }
127
128
0
        res.resize(haystack_offsets.size());
129
130
0
        if (needles_arr.empty()) {
131
0
            std::fill(res.begin(), res.end(), 0);
132
0
            return Status::OK();
133
0
        }
134
135
0
        multiregexps::RegexpsPtr regexps;
136
0
        multiregexps::ScratchPtr smart_scratch;
137
0
        RETURN_IF_ERROR(prepare_regexps_and_scratch(needles, regexps, smart_scratch));
138
139
0
        const size_t haystack_offsets_size = haystack_offsets.size();
140
0
        UInt64 offset = 0;
141
0
        for (size_t i = 0; i < haystack_offsets_size; ++i) {
142
0
            UInt64 length = haystack_offsets[i] - offset;
143
            /// vectorscan restriction.
144
0
            if (length > std::numeric_limits<UInt32>::max()) {
145
0
                return Status::InternalError("too long string to search");
146
0
            }
147
            /// zero the result, scan, check, update the offset.
148
0
            res[i] = 0;
149
0
            hs_error_t err = hs_scan(
150
0
                    regexps->getDB(), reinterpret_cast<const char*>(haystack_data.data()) + offset,
151
0
                    static_cast<unsigned>(length), 0, smart_scratch.get(), on_match, &res[i]);
152
0
            if (err != HS_SUCCESS && err != HS_SCAN_TERMINATED) {
153
0
                return Status::InternalError("failed to scan with vectorscan");
154
0
            }
155
0
            offset = haystack_offsets[i];
156
0
        }
157
158
0
        return Status::OK();
159
0
    }
160
161
    static Status vector_vector(const ColumnString::Chars& haystack_data,
162
                                const ColumnString::Offsets& haystack_offsets,
163
                                const IColumn& needles_data,
164
                                const ColumnArray::Offsets64& needles_offsets,
165
                                PaddedPODArray<ResultType>& res, PaddedPODArray<UInt64>& offsets,
166
                                bool allow_hyperscan, size_t max_hyperscan_regexp_length,
167
0
                                size_t max_hyperscan_regexp_total_length) {
168
0
        if (!allow_hyperscan) {
169
0
            return Status::InvalidArgument("Hyperscan functions are disabled");
170
0
        }
171
172
0
        res.resize(haystack_offsets.size());
173
174
0
        size_t prev_haystack_offset = 0;
175
0
        size_t prev_needles_offset = 0;
176
177
0
        const auto& nested_column =
178
0
                assert_cast<const ColumnNullable&>(needles_data).get_nested_column();
179
0
        const auto* needles_data_string = check_and_get_column<ColumnString>(nested_column);
180
181
0
        if (!needles_data_string) {
182
0
            return Status::InvalidArgument("needles should be string column");
183
0
        }
184
185
0
        std::vector<StringRef> needles;
186
0
        for (size_t i = 0; i < haystack_offsets.size(); ++i) {
187
0
            needles.reserve(needles_offsets[i] - prev_needles_offset);
188
189
0
            for (size_t j = prev_needles_offset; j < needles_offsets[i]; ++j) {
190
0
                needles.emplace_back(needles_data_string->get_data_at(j));
191
0
            }
192
0
            if (needles.empty()) {
193
0
                res[i] = 0;
194
0
                prev_haystack_offset = haystack_offsets[i];
195
0
                prev_needles_offset = needles_offsets[i];
196
0
                continue;
197
0
            }
198
199
0
            multiregexps::RegexpsPtr regexps;
200
0
            multiregexps::ScratchPtr smart_scratch;
201
0
            RETURN_IF_ERROR(prepare_regexps_and_scratch(needles, regexps, smart_scratch));
202
203
0
            const size_t cur_haystack_length = haystack_offsets[i] - prev_haystack_offset;
204
205
            /// vectorscan restriction.
206
0
            if (cur_haystack_length > std::numeric_limits<UInt32>::max()) {
207
0
                return Status::InternalError("too long string to search");
208
0
            }
209
210
            /// zero the result, scan, check, update the offset.
211
0
            res[i] = 0;
212
0
            hs_error_t err = hs_scan(
213
0
                    regexps->getDB(),
214
0
                    reinterpret_cast<const char*>(haystack_data.data()) + prev_haystack_offset,
215
0
                    static_cast<unsigned>(cur_haystack_length), 0, smart_scratch.get(), on_match,
216
0
                    &res[i]);
217
0
            if (err != HS_SUCCESS && err != HS_SCAN_TERMINATED) {
218
0
                return Status::InternalError("failed to scan with vectorscan");
219
0
            }
220
221
0
            prev_haystack_offset = haystack_offsets[i];
222
0
            prev_needles_offset = needles_offsets[i];
223
0
            needles.clear();
224
0
        }
225
226
0
        return Status::OK();
227
0
    }
228
};
229
230
} // namespace doris