Skip to main content

khive_types/
sql_like.rs

1//! Literal text for SQL `LIKE` patterns using a backslash escape character.
2
3use alloc::string::String;
4
5/// Escape `%`, `_`, and `\` so `input` matches literally under `LIKE ... ESCAPE '\'`.
6/// Callers can add their own wildcard prefix or suffix after escaping.
7pub fn escape_like_literal(input: &str) -> String {
8    let mut out = String::with_capacity(input.len());
9    for c in input.chars() {
10        if matches!(c, '\\' | '%' | '_') {
11            out.push('\\');
12        }
13        out.push(c);
14    }
15    out
16}
17
18#[cfg(test)]
19mod tests {
20    use super::escape_like_literal;
21
22    #[test]
23    fn escapes_only_like_wildcards_and_the_escape_character() {
24        for (input, expected) in [
25            ("", ""),
26            ("plain text", "plain text"),
27            ("%", "\\%"),
28            ("_", "\\_"),
29            ("\\", "\\\\"),
30            ("name%_\\tail", "name\\%\\_\\\\tail"),
31            ("中文_é%\\", "中文\\_é\\%\\\\"),
32            ("quote' and \"double\"", "quote' and \"double\""),
33        ] {
34            assert_eq!(escape_like_literal(input), expected, "input={input:?}");
35        }
36    }
37}