vortex_array/scalar_fn/fns/like/
mod.rs1mod kernel;
5
6use std::fmt::Display;
7use std::fmt::Formatter;
8
9pub use kernel::*;
10use prost::Message;
11use vortex_error::VortexResult;
12use vortex_error::vortex_bail;
13use vortex_proto::expr as pb;
14use vortex_session::VortexSession;
15
16use crate::ArrayRef;
17use crate::DynArray;
18use crate::ExecutionCtx;
19use crate::arrow::Datum;
20use crate::arrow::from_arrow_array_with_len;
21use crate::dtype::DType;
22use crate::expr::Expression;
23use crate::expr::StatsCatalog;
24use crate::expr::and;
25use crate::expr::gt;
26use crate::expr::gt_eq;
27use crate::expr::lit;
28use crate::expr::lt;
29use crate::expr::or;
30use crate::scalar::StringLike;
31use crate::scalar_fn::Arity;
32use crate::scalar_fn::ChildName;
33use crate::scalar_fn::ExecutionArgs;
34use crate::scalar_fn::ScalarFnId;
35use crate::scalar_fn::ScalarFnVTable;
36use crate::scalar_fn::fns::literal::Literal;
37
38#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash)]
40pub struct LikeOptions {
41 pub negated: bool,
42 pub case_insensitive: bool,
43}
44
45impl Display for LikeOptions {
46 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
47 if self.negated {
48 write!(f, "NOT ")?;
49 }
50 if self.case_insensitive {
51 write!(f, "ILIKE")
52 } else {
53 write!(f, "LIKE")
54 }
55 }
56}
57
58#[derive(Clone)]
60pub struct Like;
61
62impl ScalarFnVTable for Like {
63 type Options = LikeOptions;
64
65 fn id(&self) -> ScalarFnId {
66 ScalarFnId::from("vortex.like")
67 }
68
69 fn serialize(&self, instance: &Self::Options) -> VortexResult<Option<Vec<u8>>> {
70 Ok(Some(
71 pb::LikeOpts {
72 negated: instance.negated,
73 case_insensitive: instance.case_insensitive,
74 }
75 .encode_to_vec(),
76 ))
77 }
78
79 fn deserialize(
80 &self,
81 _metadata: &[u8],
82 _session: &VortexSession,
83 ) -> VortexResult<Self::Options> {
84 let opts = pb::LikeOpts::decode(_metadata)?;
85 Ok(LikeOptions {
86 negated: opts.negated,
87 case_insensitive: opts.case_insensitive,
88 })
89 }
90
91 fn arity(&self, _options: &Self::Options) -> Arity {
92 Arity::Exact(2)
93 }
94
95 fn child_name(&self, _instance: &Self::Options, child_idx: usize) -> ChildName {
96 match child_idx {
97 0 => ChildName::from("child"),
98 1 => ChildName::from("pattern"),
99 _ => unreachable!("Invalid child index {} for Like expression", child_idx),
100 }
101 }
102
103 fn fmt_sql(
104 &self,
105 options: &Self::Options,
106 expr: &Expression,
107 f: &mut Formatter<'_>,
108 ) -> std::fmt::Result {
109 expr.child(0).fmt_sql(f)?;
110 if options.negated {
111 write!(f, " not")?;
112 }
113 if options.case_insensitive {
114 write!(f, " ilike ")?;
115 } else {
116 write!(f, " like ")?;
117 }
118 expr.child(1).fmt_sql(f)
119 }
120
121 fn return_dtype(&self, _options: &Self::Options, arg_dtypes: &[DType]) -> VortexResult<DType> {
122 let input = &arg_dtypes[0];
123 let pattern = &arg_dtypes[1];
124
125 if !input.is_utf8() {
126 vortex_bail!("LIKE expression requires UTF8 input dtype, got {}", input);
127 }
128 if !pattern.is_utf8() {
129 vortex_bail!(
130 "LIKE expression requires UTF8 pattern dtype, got {}",
131 pattern
132 );
133 }
134
135 Ok(DType::Bool(
136 (input.is_nullable() || pattern.is_nullable()).into(),
137 ))
138 }
139
140 fn execute(
141 &self,
142 options: &Self::Options,
143 args: &dyn ExecutionArgs,
144 _ctx: &mut ExecutionCtx,
145 ) -> VortexResult<ArrayRef> {
146 let child = args.get(0)?;
147 let pattern = args.get(1)?;
148
149 arrow_like(&child, &pattern, *options)
150 }
151
152 fn validity(
153 &self,
154 _options: &Self::Options,
155 expression: &Expression,
156 ) -> VortexResult<Option<Expression>> {
157 tracing::warn!("Computing validity for LIKE expression");
158 let child_validity = expression.child(0).validity()?;
159 let pattern_validity = expression.child(1).validity()?;
160 Ok(Some(and(child_validity, pattern_validity)))
161 }
162
163 fn is_null_sensitive(&self, _instance: &Self::Options) -> bool {
164 false
165 }
166
167 fn stat_falsification(
168 &self,
169 like_opts: &LikeOptions,
170 expr: &Expression,
171 catalog: &dyn StatsCatalog,
172 ) -> Option<Expression> {
173 if like_opts.negated || like_opts.case_insensitive {
177 return None;
178 }
179
180 let pat = expr.child(1).as_::<Literal>();
182
183 let pat_str = pat.as_utf8().value()?;
185
186 let src = expr.child(0).clone();
187 let src_min = src.stat_min(catalog)?;
188 let src_max = src.stat_max(catalog)?;
189
190 match LikeVariant::from_str(pat_str)? {
191 LikeVariant::Exact(text) => {
192 Some(or(gt(src_min, lit(text)), lt(src_max, lit(text))))
194 }
195 LikeVariant::Prefix(prefix) => {
196 let succ = prefix.to_string().increment().ok()?;
198
199 Some(or(gt_eq(src_min, lit(succ)), lt(src_max, lit(prefix))))
200 }
201 }
202 }
203}
204
205pub(crate) fn arrow_like(
207 array: &ArrayRef,
208 pattern: &ArrayRef,
209 options: LikeOptions,
210) -> VortexResult<ArrayRef> {
211 let nullable = array.dtype().is_nullable() | pattern.dtype().is_nullable();
212 let len = array.len();
213 assert_eq!(
214 array.len(),
215 pattern.len(),
216 "Arrow Like: length mismatch for {}",
217 array.encoding_id()
218 );
219
220 let lhs = Datum::try_new(array)?;
222 let rhs = Datum::try_new_with_target_datatype(pattern, lhs.data_type())?;
223
224 let result = match (options.negated, options.case_insensitive) {
225 (false, false) => arrow_string::like::like(&lhs, &rhs)?,
226 (true, false) => arrow_string::like::nlike(&lhs, &rhs)?,
227 (false, true) => arrow_string::like::ilike(&lhs, &rhs)?,
228 (true, true) => arrow_string::like::nilike(&lhs, &rhs)?,
229 };
230
231 from_arrow_array_with_len(&result, len, nullable)
232}
233
234#[derive(Debug, PartialEq)]
236enum LikeVariant<'a> {
237 Exact(&'a str),
238 Prefix(&'a str),
239}
240
241impl<'a> LikeVariant<'a> {
242 fn from_str(string: &str) -> Option<LikeVariant<'_>> {
244 let Some(wildcard_pos) = string.find(['%', '_']) else {
245 return Some(LikeVariant::Exact(string));
246 };
247
248 if wildcard_pos == 0 {
250 return None;
251 }
252
253 let prefix = &string[..wildcard_pos];
254 Some(LikeVariant::Prefix(prefix))
255 }
256}
257
258#[cfg(test)]
259mod tests {
260 use crate::IntoArray;
261 use crate::arrays::BoolArray;
262 use crate::assert_arrays_eq;
263 use crate::dtype::DType;
264 use crate::dtype::Nullability;
265 use crate::expr::col;
266 use crate::expr::get_item;
267 use crate::expr::ilike;
268 use crate::expr::like;
269 use crate::expr::lit;
270 use crate::expr::not;
271 use crate::expr::not_ilike;
272 use crate::expr::not_like;
273 use crate::expr::pruning::pruning_expr::TrackingStatsCatalog;
274 use crate::expr::root;
275 use crate::scalar_fn::fns::like::LikeVariant;
276
277 #[test]
278 fn invert_booleans() {
279 let not_expr = not(root());
280 let bools = BoolArray::from_iter([false, true, false, false, true, true]);
281 assert_arrays_eq!(
282 bools.into_array().apply(¬_expr).unwrap(),
283 BoolArray::from_iter([true, false, true, true, false, false])
284 );
285 }
286
287 #[test]
288 fn dtype() {
289 let dtype = DType::Utf8(Nullability::NonNullable);
290 let like_expr = like(root(), lit("%test%"));
291 assert_eq!(
292 like_expr.return_dtype(&dtype).unwrap(),
293 DType::Bool(Nullability::NonNullable)
294 );
295 }
296
297 #[test]
298 fn test_display() {
299 let expr = like(get_item("name", root()), lit("%john%"));
300 assert_eq!(expr.to_string(), "$.name like \"%john%\"");
301
302 let expr2 = not_ilike(root(), lit("test*"));
303 assert_eq!(expr2.to_string(), "$ not ilike \"test*\"");
304 }
305
306 #[test]
307 fn test_like_variant() {
308 assert_eq!(
310 LikeVariant::from_str("simple"),
311 Some(LikeVariant::Exact("simple"))
312 );
313 assert_eq!(
314 LikeVariant::from_str("prefix%"),
315 Some(LikeVariant::Prefix("prefix"))
316 );
317 assert_eq!(
318 LikeVariant::from_str("first%rest_stuff"),
319 Some(LikeVariant::Prefix("first"))
320 );
321
322 assert_eq!(LikeVariant::from_str("%suffix"), None);
324 assert_eq!(LikeVariant::from_str("_pattern"), None);
325 }
326
327 #[test]
328 fn test_like_pushdown() {
329 let catalog = TrackingStatsCatalog::default();
332
333 let pruning_expr = like(col("a"), lit("prefix%"))
334 .stat_falsification(&catalog)
335 .expect("LIKE stat falsification");
336
337 insta::assert_snapshot!(pruning_expr, @r#"(($.a_min >= "prefiy") or ($.a_max < "prefix"))"#);
338
339 let pruning_expr = like(col("a"), lit("pref%ix%"))
341 .stat_falsification(&catalog)
342 .expect("LIKE stat falsification");
343 insta::assert_snapshot!(pruning_expr, @r#"(($.a_min >= "preg") or ($.a_max < "pref"))"#);
344
345 let pruning_expr = like(col("a"), lit("pref_ix_"))
346 .stat_falsification(&catalog)
347 .expect("LIKE stat falsification");
348 insta::assert_snapshot!(pruning_expr, @r#"(($.a_min >= "preg") or ($.a_max < "pref"))"#);
349
350 let pruning_expr = like(col("a"), lit("exactly"))
352 .stat_falsification(&catalog)
353 .expect("LIKE stat falsification");
354 insta::assert_snapshot!(pruning_expr, @r#"(($.a_min > "exactly") or ($.a_max < "exactly"))"#);
355
356 let pruning_expr = like(col("a"), lit("%suffix")).stat_falsification(&catalog);
358 assert_eq!(pruning_expr, None);
359
360 assert_eq!(
362 None,
363 not_like(col("a"), lit("a")).stat_falsification(&catalog)
364 );
365 assert_eq!(None, ilike(col("a"), lit("a")).stat_falsification(&catalog));
366 }
367}