common_function/utils.rs
1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15pub use common_base::hash::{FixedRandomState, partition_expr_version};
16
17/// Escapes special characters in the provided pattern string for `LIKE`.
18///
19/// Specifically, it prefixes the backslash (`\`), percent (`%`), and underscore (`_`)
20/// characters with an additional backslash to ensure they are treated literally.
21///
22/// # Examples
23///
24/// ```rust
25/// let escaped = escape_pattern("100%_some\\path");
26/// assert_eq!(escaped, "100\\%\\_some\\\\path");
27/// ```
28pub fn escape_like_pattern(pattern: &str) -> String {
29 pattern
30 .chars()
31 .flat_map(|c| match c {
32 '\\' | '%' | '_' => vec!['\\', c],
33 _ => vec![c],
34 })
35 .collect::<String>()
36}
37
38#[cfg(test)]
39mod tests {
40 use super::*;
41
42 #[test]
43 fn test_escape_like_pattern() {
44 assert_eq!(
45 escape_like_pattern("100%_some\\path"),
46 "100\\%\\_some\\\\path"
47 );
48 assert_eq!(escape_like_pattern(""), "");
49 assert_eq!(escape_like_pattern("hello"), "hello");
50 assert_eq!(escape_like_pattern("\\%_"), "\\\\\\%\\_");
51 assert_eq!(escape_like_pattern("%%__\\\\"), "\\%\\%\\_\\_\\\\\\\\");
52 assert_eq!(escape_like_pattern("abc123"), "abc123");
53 assert_eq!(escape_like_pattern("%_\\"), "\\%\\_\\\\");
54 assert_eq!(
55 escape_like_pattern("%%__\\\\another%string"),
56 "\\%\\%\\_\\_\\\\\\\\another\\%string"
57 );
58 assert_eq!(escape_like_pattern("foo%bar_"), "foo\\%bar\\_");
59 assert_eq!(escape_like_pattern("\\_\\%"), "\\\\\\_\\\\\\%");
60 }
61}