Coverage Report

Created: 2026-09-18 20:15

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/exprs/function/like.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
18
#pragma once
19
20
#include <hs/hs_common.h>
21
#include <hs/hs_runtime.h>
22
#include <re2/re2.h>
23
24
#include <algorithm>
25
#include <boost/iterator/iterator_facade.hpp>
26
#include <boost/regex.hpp>
27
#include <cstddef>
28
#include <cstdint>
29
#include <functional>
30
#include <memory>
31
#include <string>
32
#include <string_view>
33
34
#include "common/status.h"
35
#include "core/block/column_numbers.h"
36
#include "core/column/column_string.h"
37
#include "core/data_type/data_type_number.h"
38
#include "core/data_type/define_primitive_type.h"
39
#include "core/string_ref.h"
40
#include "core/types.h"
41
#include "exprs/aggregate/aggregate_function.h"
42
#include "exprs/function/function.h"
43
#include "exprs/function_context.h"
44
#include "util/string_search.hpp"
45
46
namespace doris {
47
class Block;
48
49
// FastPath types for LIKE pattern matching optimization
50
// This allows per-row pattern analysis to avoid regex when possible
51
enum class LikeFastPath {
52
    ALLPASS,     // Pattern is just '%' or '%%...' - matches everything
53
    EQUALS,      // No wildcards - exact string match
54
    STARTS_WITH, // Pattern ends with '%' only - prefix match
55
    ENDS_WITH,   // Pattern starts with '%' only - suffix match
56
    SUBSTRING,   // Pattern is '%xxx%' - substring search
57
    REGEX        // Contains '_' or multiple '%' - needs regex
58
};
59
60
// Lightweight pattern analysis without RE2
61
// Returns the fast path type and extracts the search string (without wildcards)
62
// Correctly handles escape sequences: backslash-% -> literal %, backslash-_ -> literal _
63
inline LikeFastPath extract_like_fast_path(const char* pattern, size_t len,
64
290
                                           std::string& search_string) {
65
290
    search_string.clear();
66
290
    if (len == 0) {
67
16
        return LikeFastPath::EQUALS;
68
16
    }
69
70
    // Returns true if the character is NOT escaped (even number of preceding backslashes)
71
274
    auto is_unescaped = [&pattern](size_t pos) -> bool {
72
150
        size_t backslash_count = 0;
73
171
        while (pos > 0 && pattern[pos - 1] == '\\') {
74
21
            backslash_count++;
75
21
            pos--;
76
21
        }
77
150
        return (backslash_count % 2 == 0);
78
150
    };
79
80
274
    bool starts_with_percent = (pattern[0] == '%');
81
274
    bool ends_with_percent = (pattern[len - 1] == '%' && is_unescaped(len - 1));
82
83
    // Quick check: if starts or ends with unescaped '_', need regex
84
274
    if (pattern[0] == '_') {
85
19
        return LikeFastPath::REGEX;
86
19
    }
87
255
    if (pattern[len - 1] == '_' && is_unescaped(len - 1)) {
88
28
        return LikeFastPath::REGEX;
89
28
    }
90
91
    // Helper lambda: check if character is a wildcard that needs escaping
92
227
    auto is_wildcard = [](char c) { return c == '%' || c == '_' || c == '\\'; };
93
94
227
    size_t i = 0;
95
    // Skip leading '%' characters (unescaped)
96
313
    while (i < len && pattern[i] == '%') {
97
86
        i++;
98
86
    }
99
    // If pattern is all '%', it's ALLPASS
100
227
    if (i >= len) {
101
12
        return LikeFastPath::ALLPASS;
102
12
    }
103
104
215
    search_string.reserve(len);
105
880
    while (i < len) {
106
815
        char c = pattern[i];
107
        // Escaped character - add the literal
108
815
        if (c == '\\' && i + 1 < len && is_wildcard(pattern[i + 1])) {
109
31
            search_string.push_back(pattern[i + 1]);
110
31
            i += 2;
111
31
            continue;
112
31
        }
113
114
        // Unescaped '_' requires regex
115
784
        if (c == '_') {
116
73
            return LikeFastPath::REGEX;
117
73
        }
118
119
        // Check for trailing '%' or middle '%' (which needs regex)
120
711
        if (c == '%') {
121
            // Check if this is a trailing '%' sequence
122
77
            size_t j = i;
123
154
            while (j < len && pattern[j] == '%') {
124
77
                j++;
125
77
            }
126
77
            if (j >= len) {
127
                // All remaining chars are '%', we're done parsing
128
57
                break;
129
57
            }
130
            // '%' in the middle with more content after - need regex
131
20
            return LikeFastPath::REGEX;
132
77
        }
133
134
634
        search_string.push_back(c);
135
634
        i++;
136
634
    }
137
138
    // Determine the pattern type based on '%' positions
139
122
    if (starts_with_percent && ends_with_percent) {
140
34
        return LikeFastPath::SUBSTRING;
141
88
    } else if (starts_with_percent) {
142
17
        return LikeFastPath::ENDS_WITH;
143
71
    } else if (ends_with_percent) {
144
23
        return LikeFastPath::STARTS_WITH;
145
48
    } else {
146
48
        return LikeFastPath::EQUALS;
147
48
    }
148
122
}
149
150
43
inline std::string replace_pattern_by_escape(const StringRef& pattern, char escape_char) {
151
43
    std::string result;
152
43
    result.reserve(pattern.size);
153
246
    for (size_t i = 0; i < pattern.size; ++i) {
154
203
        if (i + 1 < pattern.size && pattern.data[i] == escape_char &&
155
203
            (pattern.data[i + 1] == escape_char || pattern.data[i + 1] == '%' ||
156
42
             pattern.data[i + 1] == '_')) {
157
            // "^^" -> "^"
158
            // "^%" -> "\%"
159
            // "^_" -> "\_"
160
39
            if ((pattern.data[i + 1] == '%' || pattern.data[i + 1] == '_')) {
161
33
                result.push_back('\\');
162
33
            }
163
39
            result.push_back(pattern.data[i + 1]);
164
39
            ++i; // skip next char
165
164
        } else if (pattern.data[i] == '\\') {
166
            // "\" -> "\\"
167
4
            result.append("\\\\");
168
160
        } else {
169
160
            result.push_back(pattern.data[i]);
170
160
        }
171
203
    }
172
43
    return result;
173
43
}
174
175
// TODO: replace with std::string_view when `LikeSearchState.substring_pattern` can
176
// construct from std::string_view.
177
struct LikeSearchState {
178
    static constexpr char escape_char = '\\';
179
180
    /// Holds the string the StringRef points to and is set any time StringRef is
181
    /// used.
182
    std::string search_string;
183
184
    std::string pattern_str;
185
186
    bool enable_hyperscan_fallback = true;
187
188
    /// Used for LIKE predicates if the pattern is a constant argument, and is either a
189
    /// constant string or has a constant string at the beginning or end of the pattern.
190
    /// This will be set in order to check for that pattern in the corresponding part of
191
    /// the string.
192
    StringRef search_string_sv;
193
194
    /// Used for LIKE predicates if the pattern is a constant argument and has a constant
195
    /// string in the middle of it. This will be use in order to check for the substring
196
    /// in the value.
197
    doris::StringSearch substring_pattern;
198
199
    /// Used for RLIKE and REGEXP predicates if the pattern is a constant argument.
200
    std::unique_ptr<re2::RE2> regex;
201
202
    /// Used for REGEXP predicates when RE2 doesn't support the pattern (e.g., zero-width assertions like `?=`, `?!`, `?<=`, `?<!`)
203
    std::unique_ptr<boost::regex> boost_regex;
204
205
    template <typename Deleter, Deleter deleter>
206
    struct HyperscanDeleter {
207
        template <typename T>
208
3.27k
        void operator()(T* ptr) const {
209
3.27k
            deleter(ptr);
210
3.27k
        }
_ZNK5doris15LikeSearchState16HyperscanDeleterIPFiP10hs_scratchEXadL_Z15hs_free_scratchEEEclIS2_EEvPT_
Line
Count
Source
208
1.63k
        void operator()(T* ptr) const {
209
1.63k
            deleter(ptr);
210
1.63k
        }
_ZNK5doris15LikeSearchState16HyperscanDeleterIPFiP11hs_databaseEXadL_Z16hs_free_databaseEEEclIS2_EEvPT_
Line
Count
Source
208
1.63k
        void operator()(T* ptr) const {
209
1.63k
            deleter(ptr);
210
1.63k
        }
211
    };
212
213
    // hyperscan compiled pattern database and scratch space, reused for performance
214
    std::unique_ptr<hs_database_t, HyperscanDeleter<decltype(&hs_free_database), &hs_free_database>>
215
            hs_database;
216
    std::unique_ptr<hs_scratch_t, HyperscanDeleter<decltype(&hs_free_scratch), &hs_free_scratch>>
217
            hs_scratch;
218
219
    // hyperscan match callback
220
    static int hs_match_handler(unsigned int /* from */,       // NOLINT
221
                                unsigned long long /* from */, // NOLINT
222
                                unsigned long long /* to */,   // NOLINT
223
9.24k
                                unsigned int /* flags */, void* ctx) {
224
        // set result to 1 for matched row
225
9.24k
        *((unsigned char*)ctx) = 1;
226
        /// return non-zero to indicate hyperscan stop after first matched
227
9.24k
        return 1;
228
9.24k
    }
229
230
4.98k
    LikeSearchState() = default;
231
232
    Status clone(LikeSearchState& cloned) const;
233
234
3.11k
    void set_search_string(const std::string& search_string_arg) {
235
3.11k
        search_string = search_string_arg;
236
3.11k
        search_string_sv = StringRef(search_string);
237
3.11k
        substring_pattern.set_pattern(&search_string_sv);
238
3.11k
    }
239
};
240
241
using LikeFn = std::function<doris::Status(const LikeSearchState*, const ColumnString&,
242
                                           const StringRef&, ColumnUInt8::Container&)>;
243
244
using ScalarLikeFn = std::function<doris::Status(const LikeSearchState*, const StringRef&,
245
                                                 const StringRef&, unsigned char*)>;
246
247
using VectorLikeFn = std::function<doris::Status(const ColumnString&, const ColumnString&,
248
                                                 ColumnUInt8::Container&)>;
249
250
struct LikeState {
251
    bool is_like_pattern;
252
    bool has_custom_escape = false;
253
    char escape_char = {};
254
    LikeSearchState search_state;
255
    LikeFn function;
256
    ScalarLikeFn scalar_function;
257
};
258
259
struct VectorPatternSearchState {
260
    MutableColumnPtr _search_strings;
261
    std::string _search_string;
262
    VectorLikeFn _vector_function;
263
    bool _pattern_matched;
264
265
    VectorPatternSearchState(VectorLikeFn vector_function)
266
2.68k
            : _search_strings(ColumnString::create()),
267
2.68k
              _vector_function(vector_function),
268
2.68k
              _pattern_matched(true) {}
269
270
2.69k
    virtual ~VectorPatternSearchState() = default;
271
272
    virtual void like_pattern_match(const std::string& pattern_str) = 0;
273
274
    virtual void regexp_pattern_match(const std::string& pattern_str) = 0;
275
};
276
277
using VPatternSearchStateSPtr = std::shared_ptr<VectorPatternSearchState>;
278
279
class FunctionLikeBase : public IFunction {
280
public:
281
0
    size_t get_number_of_arguments() const override { return 0; }
282
1.20k
    bool is_variadic() const override { return true; }
283
284
1.20k
    DataTypePtr get_return_type_impl(const DataTypes& /*arguments*/) const override {
285
1.20k
        return std::make_shared<DataTypeUInt8>();
286
1.20k
    }
287
288
    Status execute_impl(FunctionContext* context, Block& block, const ColumnNumbers& arguments,
289
                        uint32_t result, size_t /*input_rows_count*/) const override;
290
291
    friend struct VectorAllpassSearchState;
292
    friend struct VectorEqualSearchState;
293
    friend struct VectorSubStringSearchState;
294
    friend struct VectorStartsWithSearchState;
295
    friend struct VectorEndsWithSearchState;
296
297
protected:
298
    static bool should_fallback_to_re2(std::string_view regexp);
299
300
    Status vector_const(const ColumnString& values, const StringRef* pattern_val,
301
                        ColumnUInt8::Container& result, const LikeFn& function,
302
                        LikeSearchState* search_state) const;
303
304
    Status vector_non_const(const ColumnString& values, const ColumnString& patterns,
305
                            ColumnUInt8::Container& result, LikeState* state,
306
                            size_t input_rows_count) const;
307
308
    template <bool LIKE_PATTERN>
309
    static VPatternSearchStateSPtr pattern_type_recognition(const ColumnString& patterns);
310
311
    static Status constant_allpass_fn(const LikeSearchState* state, const ColumnString& val,
312
                                      const StringRef& pattern, ColumnUInt8::Container& result);
313
314
    static Status constant_allpass_fn_scalar(const LikeSearchState* state, const StringRef& val,
315
                                             const StringRef& pattern, unsigned char* result);
316
317
    static Status vector_allpass_fn(const ColumnString& vals, const ColumnString& search_strings,
318
                                    ColumnUInt8::Container& result);
319
320
    static Status constant_starts_with_fn(const LikeSearchState* state, const ColumnString& val,
321
                                          const StringRef& pattern, ColumnUInt8::Container& result);
322
323
    static Status constant_starts_with_fn_scalar(const LikeSearchState* state, const StringRef& val,
324
                                                 const StringRef& pattern, unsigned char* result);
325
326
    static Status vector_starts_with_fn(const ColumnString& vals,
327
                                        const ColumnString& search_strings,
328
                                        ColumnUInt8::Container& result);
329
330
    static Status constant_ends_with_fn(const LikeSearchState* state, const ColumnString& val,
331
                                        const StringRef& pattern, ColumnUInt8::Container& result);
332
333
    static Status constant_ends_with_fn_scalar(const LikeSearchState* state, const StringRef& val,
334
                                               const StringRef& pattern, unsigned char* result);
335
336
    static Status vector_ends_with_fn(const ColumnString& vals, const ColumnString& search_strings,
337
                                      ColumnUInt8::Container& result);
338
339
    static Status constant_equals_fn(const LikeSearchState* state, const ColumnString& val,
340
                                     const StringRef& pattern, ColumnUInt8::Container& result);
341
342
    static Status constant_equals_fn_scalar(const LikeSearchState* state, const StringRef& val,
343
                                            const StringRef& pattern, unsigned char* result);
344
345
    static Status vector_equals_fn(const ColumnString& vals, const ColumnString& search_strings,
346
                                   ColumnUInt8::Container& result);
347
348
    static Status constant_substring_fn(const LikeSearchState* state, const ColumnString& val,
349
                                        const StringRef& pattern, ColumnUInt8::Container& result);
350
351
    static Status constant_substring_fn_scalar(const LikeSearchState* state, const StringRef& val,
352
                                               const StringRef& pattern, unsigned char* result);
353
354
    static Status vector_substring_fn(const ColumnString& vals, const ColumnString& search_strings,
355
                                      ColumnUInt8::Container& result);
356
357
    static Status constant_regex_fn(const LikeSearchState* state, const ColumnString& val,
358
                                    const StringRef& pattern, ColumnUInt8::Container& result);
359
360
    static Status constant_regex_fn_scalar(const LikeSearchState* state, const StringRef& val,
361
                                           const StringRef& pattern, unsigned char* result);
362
363
    static Status regexp_fn(const LikeSearchState* state, const ColumnString& val,
364
                            const StringRef& pattern, ColumnUInt8::Container& result);
365
366
    static Status regexp_fn_scalar(const LikeSearchState* state, const StringRef& val,
367
                                   const StringRef& pattern, unsigned char* result);
368
369
    // hyperscan compile expression to database and allocate scratch space
370
    static Status hs_prepare(FunctionContext* context, const char* expression,
371
                             hs_database_t** database, hs_scratch_t** scratch);
372
};
373
374
class FunctionLike : public FunctionLikeBase {
375
public:
376
    static constexpr auto name = "like";
377
378
1.06k
    static FunctionPtr create() { return std::make_shared<FunctionLike>(); }
379
380
0
    String get_name() const override { return name; }
381
382
    Status open(FunctionContext* context, FunctionContext::FunctionStateScope scope) override;
383
384
    static Status construct_like_const_state(FunctionContext* ctx, const StringRef& pattern,
385
                                             std::shared_ptr<LikeState>& state,
386
                                             bool try_hyperscan = true);
387
388
    friend struct LikeSearchState;
389
    friend struct VectorAllpassSearchState;
390
    friend struct VectorEqualSearchState;
391
    friend struct VectorSubStringSearchState;
392
    friend struct VectorStartsWithSearchState;
393
    friend struct VectorEndsWithSearchState;
394
395
private:
396
    static Status like_fn(const LikeSearchState* state, const ColumnString& val,
397
                          const StringRef& pattern, ColumnUInt8::Container& result);
398
399
    static Status like_fn_scalar(const LikeSearchState* state, const StringRef& val,
400
                                 const StringRef& pattern, unsigned char* result);
401
402
    static void convert_like_pattern(const LikeSearchState* state, const std::string& pattern,
403
                                     std::string* re_pattern);
404
405
    static void remove_escape_character(std::string* search_string);
406
};
407
408
class FunctionRegexpLike : public FunctionLikeBase {
409
public:
410
    static constexpr auto name = "regexp";
411
    static constexpr auto alias = "rlike";
412
413
154
    static FunctionPtr create() { return std::make_shared<FunctionRegexpLike>(); }
414
415
0
    String get_name() const override { return name; }
416
417
    Status open(FunctionContext* context, FunctionContext::FunctionStateScope scope) override;
418
};
419
420
} // namespace doris