uqa_sql/expr/scalar_helpers/
like_pattern.rs1use super::casing::CaseMapping;
10use crate::{
11 error::{Result, SQLError},
12 expr::conversion::value_to_string_with_control,
13};
14use uqa_core::{
15 memory::{Produced, ProductionControl, ProductionVec},
16 Value,
17};
18
19pub struct CompiledLikePattern {
21 lowercase: Option<CaseMapping>,
22 binary: bool,
23 pattern_chars: Produced<Vec<LikePatternToken<char>>>,
24 pattern_ascii: Option<Produced<Vec<LikePatternToken<u8>>>>,
25}
26
27#[derive(Clone, Copy, PartialEq, Eq)]
28enum LikePatternToken<T> {
29 Literal(T),
30 AnyOne,
31 AnyMany,
32 DanglingEscape,
33}
34
35impl CompiledLikePattern {
36 pub fn from_value_with_escape_with_control(
38 pattern: &Value,
39 case_insensitive: bool,
40 escape: Option<&Value>,
41 collation: u32,
42 control: &ProductionControl<'_>,
43 ) -> Result<Self> {
44 if let Some(pattern) = crate::expr::datums::binary_payload(pattern, control)? {
45 if case_insensitive {
46 return Err(SQLError::Internal("bytea has no ILIKE operator".into()));
47 }
48 let escape = escape
49 .map(|value| crate::expr::datums::binary_payload(value, control))
50 .transpose()?;
51 let escape = match escape.as_ref() {
52 None => Some(b'\\'),
53 Some(Some(bytes)) => match bytes.bytes() {
54 [] => None,
55 [byte] => Some(*byte),
56 _ => return Err(invalid_escape()),
57 },
58 Some(None) => {
59 return Err(SQLError::Internal(
60 "bytea escape has an invalid carrier".into(),
61 ))
62 }
63 };
64 let mut tokens = ProductionVec::new(*control);
65 let mut bytes = pattern.bytes().iter().copied();
66 while let Some(byte) = bytes.next() {
67 control.check()?;
68 let token = if escape == Some(byte) {
69 bytes
70 .next()
71 .map_or(LikePatternToken::DanglingEscape, LikePatternToken::Literal)
72 } else {
73 match byte {
74 b'%' => LikePatternToken::AnyMany,
75 b'_' => LikePatternToken::AnyOne,
76 other => LikePatternToken::Literal(other),
77 }
78 };
79 tokens.push_copy(token)?;
80 }
81 return Ok(Self {
82 lowercase: None,
83 binary: true,
84 pattern_chars: ProductionVec::new(*control).finish()?,
85 pattern_ascii: Some(tokens.finish()?),
86 });
87 }
88 let pattern = value_to_string_with_control(pattern, control)?;
89 let escape = escape
90 .map(|value| value_to_string_with_control(value, control))
91 .transpose()?;
92 Self::with_escape_with_control(
93 &pattern,
94 case_insensitive,
95 escape.as_deref().map(String::as_str),
96 collation,
97 control,
98 )
99 }
100
101 pub(in crate::expr) fn validate_escape(
103 pattern: &Value,
104 escape: &Value,
105 control: &ProductionControl<'_>,
106 ) -> Result<()> {
107 if crate::expr::datums::binary_payload(pattern, control)?.is_some() {
108 let escape = crate::expr::datums::binary_payload(escape, control)?
109 .ok_or_else(|| SQLError::Internal("bytea escape has an invalid carrier".into()))?;
110 return if escape.bytes().len() <= 1 {
111 Ok(())
112 } else {
113 Err(invalid_escape())
114 };
115 }
116 let escape = value_to_string_with_control(escape, control)?;
117 escape_character(Some(&escape)).map(|_| ())
118 }
119
120 pub fn with_escape(
121 pattern: &str,
122 case_insensitive: bool,
123 escape: Option<&str>,
124 collation: u32,
125 ) -> Result<Self> {
126 Self::with_escape_with_control(
127 pattern,
128 case_insensitive,
129 escape,
130 collation,
131 &ProductionControl::uncontrolled(),
132 )
133 }
134
135 pub fn with_escape_with_control(
137 pattern: &str,
138 case_insensitive: bool,
139 escape: Option<&str>,
140 collation: u32,
141 control: &ProductionControl<'_>,
142 ) -> Result<Self> {
143 control.check()?;
144 let mapping =
145 CaseMapping::select(collation, if case_insensitive { "ILIKE" } else { "LIKE" })?;
146 let escape = escape_character(escape)?;
147 let lowercase = case_insensitive.then_some(mapping);
148 let pattern_chars = match lowercase {
149 Some(mapping) => {
150 let normalized = if escape == Some('\\') {
151 None
152 } else {
153 Some(crate::expr::pattern::normalize_escape(
154 pattern, escape, control,
155 )?)
156 };
157 let lowered = mapping.lowercase(
158 normalized.as_deref().map_or(pattern, String::as_str),
159 control,
160 )?;
161 compile(&lowered, Some('\\'), control)?
162 }
163 None => compile(pattern, escape, control)?,
164 };
165 let mut ascii = ProductionVec::new(*control);
166 let mut all_ascii = true;
167 for token in pattern_chars.iter() {
168 control.check()?;
169 let token = match token {
170 LikePatternToken::Literal(character) if character.is_ascii() => {
171 LikePatternToken::Literal(*character as u8)
172 }
173 LikePatternToken::Literal(_) => {
174 all_ascii = false;
175 break;
176 }
177 LikePatternToken::AnyOne => LikePatternToken::AnyOne,
178 LikePatternToken::AnyMany => LikePatternToken::AnyMany,
179 LikePatternToken::DanglingEscape => LikePatternToken::DanglingEscape,
180 };
181 ascii.push_copy(token)?;
182 }
183 let pattern_ascii = if all_ascii {
184 Some(ascii.finish()?)
185 } else {
186 None
187 };
188 Ok(Self {
189 lowercase,
190 binary: false,
191 pattern_chars,
192 pattern_ascii,
193 })
194 }
195
196 pub fn try_is_match(&self, haystack: &str) -> Result<bool> {
197 self.try_is_match_with_control(haystack, &ProductionControl::uncontrolled())
198 }
199
200 pub fn try_is_match_with_control(
201 &self,
202 haystack: &str,
203 control: &ProductionControl<'_>,
204 ) -> Result<bool> {
205 control.check()?;
206 let normalized = self
207 .lowercase
208 .map(|mapping| mapping.lowercase(haystack, control))
209 .transpose()?;
210 let haystack = normalized.as_deref().map_or(haystack, String::as_str);
211 if let Some(pattern) = self
212 .pattern_ascii
213 .as_deref()
214 .filter(|_| self.binary || haystack.is_ascii())
215 {
216 return wildcard_match(haystack.as_bytes(), pattern, control);
217 }
218 let mut characters = ProductionVec::new(*control);
219 for character in haystack.chars() {
220 characters.push_copy(character)?;
221 }
222 wildcard_match(&characters, &self.pattern_chars, control)
223 }
224
225 pub fn try_matches_value(&self, haystack: &Value) -> Result<bool> {
226 self.try_matches_value_with_control(haystack, &ProductionControl::uncontrolled())
227 }
228
229 pub fn try_matches_value_with_control(
230 &self,
231 haystack: &Value,
232 control: &ProductionControl<'_>,
233 ) -> Result<bool> {
234 if self.binary {
235 let bytes =
236 crate::expr::datums::binary_payload(haystack, control)?.ok_or_else(|| {
237 SQLError::Internal("bytea LIKE source has an invalid carrier".into())
238 })?;
239 return wildcard_match(
240 bytes.bytes(),
241 self.pattern_ascii
242 .as_deref()
243 .expect("binary pattern tokens"),
244 control,
245 );
246 }
247 match haystack {
248 Value::Datum(datum) => self.try_matches_value_with_control(
249 &*crate::expr::datums::read_with_control(datum, control)?,
250 control,
251 ),
252 Value::Str(text) | Value::FixedChar(text) => {
253 self.try_is_match_with_control(text, control)
254 }
255 Value::Null => self.try_is_match_with_control("", control),
256 other => self
257 .try_is_match_with_control(&value_to_string_with_control(other, control)?, control),
258 }
259 }
260}
261
262pub(in crate::expr) fn escape_character(escape: Option<&str>) -> Result<Option<char>> {
263 let Some(escape) = escape else {
264 return Ok(Some('\\'));
265 };
266 let mut characters = escape.chars();
267 let first = characters.next();
268 if characters.next().is_some() {
269 return Err(invalid_escape());
270 }
271 Ok(first)
272}
273
274pub(in crate::expr) fn invalid_escape() -> SQLError {
275 SQLError::Diagnostic {
276 sqlstate: "22025".into(),
277 message: "invalid escape string".into(),
278 detail: None,
279 hint: Some("Escape string must be empty or one character.".into()),
280 }
281}
282
283fn compile(
284 pattern: &str,
285 escape: Option<char>,
286 control: &ProductionControl<'_>,
287) -> Result<Produced<Vec<LikePatternToken<char>>>> {
288 let mut output = ProductionVec::new(*control);
289 let mut characters = pattern.chars();
290 while let Some(character) = characters.next() {
291 control.check()?;
292 if escape == Some(character) {
293 let Some(literal) = characters.next() else {
294 output.push_copy(LikePatternToken::DanglingEscape)?;
295 break;
296 };
297 output.push_copy(LikePatternToken::Literal(literal))?;
298 continue;
299 }
300 output.push_copy(match character {
301 '%' => LikePatternToken::AnyMany,
302 '_' => LikePatternToken::AnyOne,
303 literal => LikePatternToken::Literal(literal),
304 })?;
305 }
306 Ok(output.finish()?)
307}
308
309fn wildcard_match<T: Copy + Eq>(
310 haystack: &[T],
311 pattern: &[LikePatternToken<T>],
312 control: &ProductionControl<'_>,
313) -> Result<bool> {
314 let mut haystack_index = 0;
315 let mut pattern_index = 0;
316 let mut star: Option<(usize, usize)> = None;
317 while haystack_index < haystack.len() {
318 control.check()?;
319 match pattern.get(pattern_index) {
320 Some(LikePatternToken::Literal(literal)) if *literal == haystack[haystack_index] => {
321 haystack_index += 1;
322 pattern_index += 1;
323 }
324 Some(LikePatternToken::AnyOne) => {
325 haystack_index += 1;
326 pattern_index += 1;
327 }
328 Some(LikePatternToken::AnyMany) => {
329 star = Some((pattern_index, haystack_index));
330 pattern_index += 1;
331 }
332 Some(LikePatternToken::DanglingEscape) => {
333 return Err(SQLError::Routine {
334 sqlstate: "22025".into(),
335 message: "LIKE pattern must not end with escape character".into(),
336 });
337 }
338 _ => {
339 if let Some((star_pattern, star_haystack)) = star {
340 pattern_index = star_pattern + 1;
341 haystack_index = star_haystack + 1;
342 star = Some((star_pattern, haystack_index));
343 } else {
344 return Ok(false);
345 }
346 }
347 }
348 }
349 while matches!(pattern.get(pattern_index), Some(LikePatternToken::AnyMany)) {
350 control.check()?;
351 pattern_index += 1;
352 }
353 Ok(pattern_index == pattern.len())
354}
355
356#[cfg(test)]
357mod tests;