Skip to main content

vortex_functions/like/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4mod dict;
5mod kernel;
6mod pattern;
7
8use std::fmt::Display;
9use std::fmt::Formatter;
10
11pub use kernel::*;
12use pattern::LikePattern;
13use prost::Message;
14use vortex_array::AnyColumnar;
15use vortex_array::ArrayRef;
16use vortex_array::Canonical;
17use vortex_array::ExecutionCtx;
18use vortex_array::IntoArray;
19use vortex_array::arrays::BoolArray;
20use vortex_array::arrays::ConstantArray;
21use vortex_array::arrays::Dict;
22use vortex_array::arrays::ScalarFnArray;
23use vortex_array::arrays::VarBinViewArray;
24use vortex_array::arrays::varbinview::BinaryView;
25use vortex_array::arrays::varbinview::ResolvedViews;
26use vortex_array::dtype::DType;
27use vortex_array::dtype::Nullability;
28use vortex_array::optimizer::kernels::ArrayKernelsExt;
29use vortex_array::proto::expr as pb;
30use vortex_array::require_input;
31use vortex_array::scalar::Scalar;
32use vortex_array::scalar_fn::Arity;
33use vortex_array::scalar_fn::ChildName;
34use vortex_array::scalar_fn::ExecutionArgs;
35use vortex_array::scalar_fn::ScalarFnExecutionResult;
36use vortex_array::scalar_fn::ScalarFnId;
37use vortex_array::scalar_fn::ScalarFnVTable;
38use vortex_array::scalar_fn::ScalarFnVTableExt;
39use vortex_array::scalar_fn::display::ExprDisplay;
40use vortex_array::scalar_fn::session::ScalarFnSessionExt;
41use vortex_buffer::BitBuffer;
42use vortex_buffer::BitBufferMut;
43use vortex_buffer::BufferAllocatorRef;
44use vortex_error::VortexResult;
45use vortex_error::vortex_bail;
46use vortex_error::vortex_err;
47use vortex_session::VortexSession;
48use vortex_session::registry::CachedId;
49
50/// Registers [`Like`] and its rule for dictionary-encoded arrays.
51pub(crate) fn initialize(session: &VortexSession) {
52    session.scalar_fns().register(Like);
53    session
54        .kernels()
55        .register_reduce_parent_rule(Like, Dict, const { &LikeReduceAdaptor(Dict) });
56}
57
58/// Options for SQL LIKE function
59#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash)]
60pub struct LikeOptions {
61    pub negated: bool,
62    pub case_insensitive: bool,
63}
64
65impl Display for LikeOptions {
66    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
67        if self.negated {
68            write!(f, "NOT ")?;
69        }
70        if self.case_insensitive {
71            write!(f, "ILIKE")
72        } else {
73            write!(f, "LIKE")
74        }
75    }
76}
77
78/// Expression that performs SQL LIKE pattern matching.
79#[derive(Clone)]
80pub struct Like;
81
82impl Like {
83    /// Creates a lazy SQL `LIKE` operation over `input` and `pattern`.
84    ///
85    /// # Errors
86    ///
87    /// Returns an error if the children have different lengths or are not UTF-8 arrays.
88    pub fn try_new(
89        input: ArrayRef,
90        pattern: ArrayRef,
91        options: LikeOptions,
92    ) -> VortexResult<ScalarFnArray> {
93        ScalarFnArray::try_new(Like.bind(options), [input, pattern])
94    }
95}
96
97impl ScalarFnVTable for Like {
98    type Options = LikeOptions;
99
100    fn id(&self) -> ScalarFnId {
101        static ID: CachedId = CachedId::new("vortex.like");
102        *ID
103    }
104
105    fn serialize(&self, instance: &Self::Options) -> VortexResult<Option<Vec<u8>>> {
106        Ok(Some(
107            pb::LikeOpts {
108                negated: instance.negated,
109                case_insensitive: instance.case_insensitive,
110            }
111            .encode_to_vec(),
112        ))
113    }
114
115    fn deserialize(
116        &self,
117        _metadata: &[u8],
118        _session: &VortexSession,
119    ) -> VortexResult<Self::Options> {
120        let opts = pb::LikeOpts::decode(_metadata)?;
121        Ok(LikeOptions {
122            negated: opts.negated,
123            case_insensitive: opts.case_insensitive,
124        })
125    }
126
127    fn arity(&self, _options: &Self::Options) -> Arity {
128        Arity::Exact(2)
129    }
130
131    fn child_name(&self, _instance: &Self::Options, child_idx: usize) -> ChildName {
132        match child_idx {
133            0 => ChildName::from("child"),
134            1 => ChildName::from("pattern"),
135            _ => unreachable!("Invalid child index {} for Like expression", child_idx),
136        }
137    }
138
139    fn fmt_sql(
140        &self,
141        options: &Self::Options,
142        expr: &dyn ExprDisplay,
143        f: &mut Formatter<'_>,
144    ) -> std::fmt::Result {
145        Display::fmt(expr.display_child(0), f)?;
146        if options.negated {
147            write!(f, " not")?;
148        }
149        if options.case_insensitive {
150            write!(f, " ilike ")?;
151        } else {
152            write!(f, " like ")?;
153        }
154        Display::fmt(expr.display_child(1), f)
155    }
156
157    fn return_dtype(&self, _options: &Self::Options, arg_dtypes: &[DType]) -> VortexResult<DType> {
158        let input = &arg_dtypes[0];
159        let pattern = &arg_dtypes[1];
160
161        if !input.is_utf8() {
162            vortex_bail!("LIKE expression requires UTF8 input dtype, got {}", input);
163        }
164        if !pattern.is_utf8() {
165            vortex_bail!(
166                "LIKE expression requires UTF8 pattern dtype, got {}",
167                pattern
168            );
169        }
170
171        Ok(DType::Bool(
172            (input.is_nullable() || pattern.is_nullable()).into(),
173        ))
174    }
175
176    fn execute(
177        &self,
178        options: &Self::Options,
179        args: &dyn ExecutionArgs,
180        ctx: &mut ExecutionCtx,
181    ) -> VortexResult<ArrayRef> {
182        let child = args.get(0)?;
183        let pattern = args.get(1)?;
184
185        execute_like(&child, &pattern, *options, ctx)
186    }
187
188    fn execute_step(
189        &self,
190        options: &Self::Options,
191        args: &dyn ExecutionArgs,
192        ctx: &mut ExecutionCtx,
193    ) -> VortexResult<ScalarFnExecutionResult> {
194        // A null pattern decides every row without reading the input.
195        if !args.input_matches(1, |pattern| {
196            pattern
197                .as_constant()
198                .is_some_and(|pattern| pattern.is_null())
199        })? {
200            require_input!(args, 0 => AnyColumnar);
201            require_input!(args, 1 => AnyColumnar);
202        }
203        self.execute(options, args, ctx)
204            .map(ScalarFnExecutionResult::done)
205    }
206
207    fn is_strict(&self, _instance: &Self::Options) -> bool {
208        true
209    }
210
211    fn is_infallible(&self, _options: &Self::Options) -> bool {
212        true
213    }
214}
215
216/// Native implementation of LIKE over canonical [`VarBinViewArray`]s.
217///
218/// Patterns are compiled once per distinct pattern (see [`LikePattern`]) and evaluated per
219/// value directly on the view bytes.
220pub(crate) fn execute_like(
221    array: &ArrayRef,
222    pattern: &ArrayRef,
223    options: LikeOptions,
224    ctx: &mut ExecutionCtx,
225) -> VortexResult<ArrayRef> {
226    assert_eq!(
227        array.len(),
228        pattern.len(),
229        "LIKE: length mismatch for {}",
230        array.encoding_id()
231    );
232    let len = array.len();
233    let nullability =
234        Nullability::from(array.dtype().is_nullable() || pattern.dtype().is_nullable());
235
236    if len == 0 {
237        return Ok(Canonical::empty(&DType::Bool(nullability)).into_array());
238    }
239
240    if let Some(pattern_const) = pattern.as_constant() {
241        let Some(pattern_str) = pattern_const.as_utf8().value() else {
242            // A null pattern makes every row null.
243            return Ok(
244                ConstantArray::new(Scalar::null(DType::Bool(Nullability::Nullable)), len)
245                    .into_array(),
246            );
247        };
248        let values = array.clone().execute::<VarBinViewArray>(ctx)?;
249        let haystack = values.resolved_views();
250        // The ASCII case-insensitive fast paths are only sound when the haystack is pure
251        // ASCII; see `LikePattern::compile`.
252        let ascii_haystack =
253            options.case_insensitive && pattern_str.as_str().is_ascii() && is_ascii(&haystack);
254        let compiled = LikePattern::compile(
255            pattern_str.as_str(),
256            options.case_insensitive,
257            ascii_haystack,
258        )?;
259        let bits = eval_pattern(&haystack, &compiled, options.negated, ctx.allocator());
260        let validity = values.validity()?.union_nullability(nullability);
261        return Ok(BoolArray::new(bits, validity).into_array());
262    }
263
264    // Per-row patterns: compile each pattern individually.
265    let values = array.clone().execute::<VarBinViewArray>(ctx)?;
266    let patterns = pattern.clone().execute::<VarBinViewArray>(ctx)?;
267    let haystack = values.resolved_views();
268    let pattern_views = patterns.resolved_views();
269    let ascii_haystack = options.case_insensitive && is_ascii(&haystack);
270
271    // Reuse the previous row's compiled pattern while the pattern bytes repeat, so runs of
272    // identical patterns (the common case for non-constant pattern children) compile once.
273    let mut cached: Option<(&[u8], LikePattern)> = None;
274    let mut bits = BitBufferMut::with_capacity_in(len, ctx.allocator().clone());
275    for i in 0..len {
276        let pattern_bytes = pattern_views.bytes(i);
277        let compiled = match &cached {
278            Some((bytes, compiled)) if *bytes == pattern_bytes => compiled,
279            _ => {
280                let pattern_str = std::str::from_utf8(pattern_bytes)
281                    .map_err(|e| vortex_err!("LIKE pattern is not valid UTF-8: {e}"))?;
282                let compiled = LikePattern::compile(
283                    pattern_str,
284                    options.case_insensitive,
285                    ascii_haystack && pattern_str.is_ascii(),
286                )?;
287                &cached.insert((pattern_bytes, compiled)).1
288            }
289        };
290        bits.append(compiled.matches(haystack.bytes(i)) != options.negated);
291    }
292    let validity = values
293        .validity()?
294        .and(patterns.validity()?)?
295        .union_nullability(nullability);
296    Ok(BoolArray::new(bits.freeze(), validity).into_array())
297}
298
299/// Evaluate `pattern` against every element of `haystack`.
300///
301/// The equality, prefix, and suffix patterns exploit the view layout: a view stores the value
302/// length and its first four bytes inline, which settles most elements without touching the
303/// data buffers (values of up to 12 bytes are stored entirely inline).
304fn eval_pattern(
305    haystack: &ResolvedViews<'_>,
306    pattern: &LikePattern,
307    negated: bool,
308    allocator: &BufferAllocatorRef,
309) -> BitBuffer {
310    let len = haystack.len();
311    match pattern {
312        LikePattern::Eq(needle) if needle.len() <= BinaryView::MAX_INLINED_SIZE => {
313            // The needle fits in a view, so equality is a single 16-byte comparison: a view
314            // of a different length or prefix can never share the same bit pattern.
315            let needle_view = BinaryView::new_inlined(needle).as_u128();
316            BitBuffer::collect_bool_in(
317                len,
318                |i| (haystack.views()[i].as_u128() == needle_view) != negated,
319                allocator.clone(),
320            )
321        }
322        LikePattern::Eq(needle) => {
323            // Compare the view head (length plus 4-byte prefix) first; only views that agree
324            // on both dereference their data buffer for the remaining bytes.
325            let needle_head = BinaryView::head_of(needle);
326            BitBuffer::collect_bool_in(
327                len,
328                |i| {
329                    let view = &haystack.views()[i];
330                    let matched =
331                        view.head() == needle_head && haystack.bytes(i)[4..] == needle[4..];
332                    matched != negated
333                },
334                allocator.clone(),
335            )
336        }
337        LikePattern::StartsWith(needle) => {
338            // A branch-free masked comparison of the view's inline 4-byte prefix rejects
339            // almost every element without touching the data buffers; only elements whose
340            // prefix matches compare the remaining needle bytes.
341            let needle_len = needle.len();
342            let prefix_len = needle_len.min(4);
343            // Raw prefix bytes, unswapped: this is a masked equality, not an ordering.
344            let needle_prefix = u32::from_le_bytes(BinaryView::prefix_of(needle));
345            let prefix_mask = if prefix_len == 4 {
346                u32::MAX
347            } else {
348                (1u32 << (8 * prefix_len)) - 1
349            };
350            BitBuffer::collect_bool_in(
351                len,
352                |i| {
353                    let view = &haystack.views()[i];
354                    let matched = view.len() as usize >= needle_len
355                        && (u32::from_le_bytes(view.prefix()) & prefix_mask) == needle_prefix
356                        && (needle_len <= 4 || haystack.bytes(i)[4..needle_len] == needle[4..]);
357                    matched != negated
358                },
359                allocator.clone(),
360            )
361        }
362        LikePattern::EndsWith(needle) => {
363            // Inlined values compare their suffix inside the view struct without touching the
364            // data buffers; reference views slice exactly the suffix out of their buffer.
365            let needle_len = needle.len();
366            BitBuffer::collect_bool_in(
367                len,
368                |i| {
369                    // SAFETY: `i` is below the array length, and the suffix length is only read
370                    // once the view is known to be at least `needle_len` long.
371                    let matched = unsafe {
372                        let view = haystack.views().get_unchecked(i);
373                        view.len() as usize >= needle_len
374                            && bytes_eq(suffix_bytes_unchecked(haystack, view, needle_len), needle)
375                    };
376                    matched != negated
377                },
378                allocator.clone(),
379            )
380        }
381        LikePattern::IEqAscii(needle) => BitBuffer::collect_bool_in(
382            len,
383            |i| {
384                let view = &haystack.views()[i];
385                let matched = view.len() as usize == needle.len()
386                    && haystack.bytes(i).eq_ignore_ascii_case(needle);
387                matched != negated
388            },
389            allocator.clone(),
390        ),
391        LikePattern::Contains(finder, needle_len) => BitBuffer::collect_bool_in(
392            len,
393            |i| {
394                let view = &haystack.views()[i];
395                let matched =
396                    view.len() as usize >= *needle_len && finder.find(haystack.bytes(i)).is_some();
397                matched != negated
398            },
399            allocator.clone(),
400        ),
401        _ => BitBuffer::collect_bool_in(
402            len,
403            |i| pattern.matches(haystack.bytes(i)) != negated,
404            allocator.clone(),
405        ),
406    }
407}
408
409/// Whether every value in `haystack` is ASCII. Validity is not consulted.
410fn is_ascii(haystack: &ResolvedViews<'_>) -> bool {
411    haystack
412        .views()
413        .iter()
414        .all(|view| haystack.view_bytes(view).is_ascii())
415}
416
417/// The last `suffix_len` bytes of `view`, which must belong to `haystack`.
418///
419/// # Safety
420///
421/// `suffix_len` must be at most `view.len()`.
422#[inline]
423unsafe fn suffix_bytes_unchecked<'a>(
424    haystack: &ResolvedViews<'a>,
425    view: &'a BinaryView,
426    suffix_len: usize,
427) -> &'a [u8] {
428    let len = view.len() as usize;
429    if view.is_inlined() {
430        // SAFETY: caller guarantees suffix_len <= len.
431        unsafe { view.as_inlined().value().get_unchecked(len - suffix_len..) }
432    } else {
433        let view = view.as_view();
434        let end = view.offset as usize + len;
435        // SAFETY: the array validated this view's buffer index and range on construction.
436        unsafe {
437            haystack
438                .buffers()
439                .get_unchecked(view.buffer_index as usize)
440                .get_unchecked(end - suffix_len..end)
441        }
442    }
443}
444
445/// Byte equality as an inlined loop with early exit.
446///
447/// Faster than slice `==` for the short, unpredictable-length comparisons in this module,
448/// which otherwise lower to a `memcmp` libcall per element.
449#[inline]
450fn bytes_eq(lhs: &[u8], rhs: &[u8]) -> bool {
451    lhs.len() == rhs.len() && std::iter::zip(lhs, rhs).all(|(l, r)| l == r)
452}
453
454#[cfg(test)]
455mod tests {
456    use std::sync::LazyLock;
457
458    use rstest::rstest;
459    use vortex_array::IntoArray;
460    use vortex_array::VortexSessionExecute;
461    use vortex_array::arrays::BoolArray;
462    use vortex_array::arrays::ConstantArray;
463    use vortex_array::arrays::VarBinArray;
464    use vortex_array::arrays::VarBinViewArray;
465    use vortex_array::assert_arrays_eq;
466    use vortex_array::dtype::DType;
467    use vortex_array::dtype::Nullability;
468    use vortex_array::scalar::Scalar;
469    use vortex_expr::get_item;
470    use vortex_expr::lit;
471    use vortex_expr::root;
472    use vortex_session::VortexSession;
473
474    use crate::expr::like;
475    use crate::expr::not_ilike;
476    use crate::like::Like;
477    use crate::like::LikeOptions;
478    use crate::like::is_ascii;
479    use crate::like::suffix_bytes_unchecked;
480
481    static SESSION: LazyLock<VortexSession> = LazyLock::new(|| {
482        let session = VortexSession::empty();
483
484        vortex_array::initialize(&session);
485
486        crate::initialize(&session);
487
488        session
489    });
490
491    const LONG: &str = "a value far too long to live inside its own view";
492
493    fn run_like(
494        array: vortex_array::ArrayRef,
495        pattern: vortex_array::ArrayRef,
496        options: LikeOptions,
497    ) -> vortex_array::ArrayRef {
498        Like::try_new(array, pattern, options).unwrap().into_array()
499    }
500
501    #[rstest]
502    // Exact, prefix, suffix, contains fast paths.
503    #[case("hello", [true, false, false, false])]
504    #[case("he%", [true, false, true, false])]
505    #[case("%llo", [true, false, false, true])]
506    #[case("%ell%", [true, false, false, true])]
507    // Wildcards that require the regex path.
508    #[case("h_llo", [true, false, false, false])]
509    #[case("h%o", [true, false, false, false])]
510    #[case("%", [true, true, true, true])]
511    #[case("_____", [true, true, false, true])]
512    fn test_like_patterns(#[case] pattern: &str, #[case] expected: [bool; 4]) {
513        let mut ctx = SESSION.create_execution_ctx();
514        let array =
515            VarBinViewArray::from_iter_str(["hello", "world", "help", "jello"]).into_array();
516        let result = run_like(
517            array,
518            ConstantArray::new(pattern, 4).into_array(),
519            LikeOptions::default(),
520        );
521        assert_arrays_eq!(result, BoolArray::from_iter(expected), &mut ctx);
522    }
523
524    #[test]
525    fn test_like_escapes() {
526        let mut ctx = SESSION.create_execution_ctx();
527        let array = VarBinViewArray::from_iter_str(["100%", "100x", "a_b", "axb"]).into_array();
528
529        let result = run_like(
530            array.clone(),
531            ConstantArray::new(r"100\%", 4).into_array(),
532            LikeOptions::default(),
533        );
534        assert_arrays_eq!(
535            result,
536            BoolArray::from_iter([true, false, false, false]),
537            &mut ctx
538        );
539
540        let result = run_like(
541            array,
542            ConstantArray::new(r"a\_b", 4).into_array(),
543            LikeOptions::default(),
544        );
545        assert_arrays_eq!(
546            result,
547            BoolArray::from_iter([false, false, true, false]),
548            &mut ctx
549        );
550    }
551
552    #[test]
553    fn test_like_regex_meta_characters_are_literal() {
554        let mut ctx = SESSION.create_execution_ctx();
555        let array = VarBinViewArray::from_iter_str(["a.c", "abc", "a$c"]).into_array();
556        let result = run_like(
557            array,
558            ConstantArray::new("a.%", 3).into_array(),
559            LikeOptions::default(),
560        );
561        assert_arrays_eq!(result, BoolArray::from_iter([true, false, false]), &mut ctx);
562    }
563
564    #[test]
565    fn test_like_unicode() {
566        let mut ctx = SESSION.create_execution_ctx();
567        let array =
568            VarBinViewArray::from_iter_str(["h\u{00a3}llo", "hxllo", "h\u{00a3}xllo"]).into_array();
569        // `_` matches exactly one character of any byte width.
570        let result = run_like(
571            array,
572            ConstantArray::new("h_llo", 3).into_array(),
573            LikeOptions::default(),
574        );
575        assert_arrays_eq!(result, BoolArray::from_iter([true, true, false]), &mut ctx);
576    }
577
578    #[test]
579    fn test_nlike() {
580        let mut ctx = SESSION.create_execution_ctx();
581        let array = VarBinViewArray::from_iter_str(["hello", "world"]).into_array();
582        let result = run_like(
583            array,
584            ConstantArray::new("he%", 2).into_array(),
585            LikeOptions {
586                negated: true,
587                case_insensitive: false,
588            },
589        );
590        assert_arrays_eq!(result, BoolArray::from_iter([false, true]), &mut ctx);
591    }
592
593    #[test]
594    fn test_ilike() {
595        let mut ctx = SESSION.create_execution_ctx();
596        let ilike = LikeOptions {
597            negated: false,
598            case_insensitive: true,
599        };
600
601        // Pure-ASCII data takes the ASCII fast paths.
602        let array = VarBinViewArray::from_iter_str(["HELLO", "world", "Help"]).into_array();
603        let result = run_like(array, ConstantArray::new("he%", 3).into_array(), ilike);
604        assert_arrays_eq!(result, BoolArray::from_iter([true, false, true]), &mut ctx);
605
606        // Non-ASCII data requires full case folding: `k` matches U+212A KELVIN SIGN.
607        let array = VarBinViewArray::from_iter_str(["\u{212a}", "k", "x"]).into_array();
608        let result = run_like(array, ConstantArray::new("k", 3).into_array(), ilike);
609        assert_arrays_eq!(result, BoolArray::from_iter([true, true, false]), &mut ctx);
610    }
611
612    #[test]
613    fn test_nilike() {
614        let mut ctx = SESSION.create_execution_ctx();
615        let array = VarBinViewArray::from_iter_str(["HELLO", "world"]).into_array();
616        let result = run_like(
617            array,
618            ConstantArray::new("he%", 2).into_array(),
619            LikeOptions {
620                negated: true,
621                case_insensitive: true,
622            },
623        );
624        assert_arrays_eq!(result, BoolArray::from_iter([false, true]), &mut ctx);
625    }
626
627    #[test]
628    fn test_like_nullable_input() {
629        let mut ctx = SESSION.create_execution_ctx();
630        let array = VarBinViewArray::from_iter_nullable_str([Some("hello"), None, Some("help")])
631            .into_array();
632        let result = run_like(
633            array,
634            ConstantArray::new("he%", 3).into_array(),
635            LikeOptions::default(),
636        );
637        assert_arrays_eq!(
638            result,
639            BoolArray::from_iter([Some(true), None, Some(true)]),
640            &mut ctx
641        );
642    }
643
644    #[test]
645    fn test_like_null_pattern() {
646        let mut ctx = SESSION.create_execution_ctx();
647        let array = VarBinViewArray::from_iter_str(["hello", "world"]).into_array();
648        let result = run_like(
649            array,
650            ConstantArray::new(Scalar::null(DType::Utf8(Nullability::Nullable)), 2).into_array(),
651            LikeOptions::default(),
652        );
653        assert_arrays_eq!(result, BoolArray::from_iter([None, None]), &mut ctx);
654    }
655
656    #[test]
657    fn test_like_per_row_patterns() {
658        let mut ctx = SESSION.create_execution_ctx();
659        let array = VarBinViewArray::from_iter_str(["hello", "hello", "hello"]).into_array();
660        let patterns = VarBinViewArray::from_iter_str(["he%", "%world", "h_llo"]).into_array();
661        let result = run_like(array, patterns, LikeOptions::default());
662        assert_arrays_eq!(result, BoolArray::from_iter([true, false, true]), &mut ctx);
663    }
664
665    #[test]
666    fn test_like_non_canonical_input() {
667        let mut ctx = SESSION.create_execution_ctx();
668        // VarBin (not the canonical VarBinView) is canonicalized before evaluation.
669        let array = VarBinArray::from_iter(
670            [Some("hello"), Some("world")],
671            DType::Utf8(Nullability::Nullable),
672        )
673        .into_array();
674        let result = run_like(
675            array,
676            ConstantArray::new("he%", 2).into_array(),
677            LikeOptions::default(),
678        );
679        assert_arrays_eq!(
680            result,
681            BoolArray::from_iter([Some(true), Some(false)]),
682            &mut ctx
683        );
684    }
685
686    #[test]
687    fn dtype() {
688        let dtype = DType::Utf8(Nullability::NonNullable);
689        let like_expr = like(root(), lit("%test%"));
690        assert_eq!(
691            like_expr.return_dtype(&dtype).unwrap(),
692            DType::Bool(Nullability::NonNullable)
693        );
694    }
695
696    #[test]
697    fn signature() {
698        let like_expr = like(root(), lit("%test%"));
699        assert!(
700            like_expr
701                .as_scalar()
702                .is_some_and(|f| f.signature().is_strict())
703        );
704        assert!(
705            like_expr
706                .as_scalar()
707                .is_some_and(|f| f.signature().is_infallible())
708        );
709    }
710
711    #[test]
712    fn test_display() {
713        let expr = like(get_item("name", root()), lit("%john%"));
714        assert_eq!(expr.to_string(), "$.name like \"%john%\"");
715
716        let expr2 = not_ilike(root(), lit("test*"));
717        assert_eq!(expr2.to_string(), "$ not ilike \"test*\"");
718    }
719
720    #[test]
721    fn suffix_bytes_are_value_suffixes() {
722        let array = VarBinViewArray::from_iter_str(["short", LONG, "another long value here"]);
723        let haystack = array.resolved_views();
724        for (index, view) in haystack.views().iter().enumerate() {
725            let value = haystack.bytes(index);
726            for suffix_len in 0..=value.len() {
727                // SAFETY: suffix_len <= value.len(), which is view.len().
728                let suffix = unsafe { suffix_bytes_unchecked(&haystack, view, suffix_len) };
729                assert_eq!(suffix, &value[value.len() - suffix_len..]);
730            }
731        }
732    }
733
734    #[rstest]
735    #[case::inlined(["short", "tiny"], true)]
736    #[case::referenced([LONG, "another long value here"], true)]
737    #[case::inlined_non_ascii(["short", "é"], false)]
738    #[case::referenced_non_ascii([LONG, "a long value ending in é"], false)]
739    fn detects_ascii(#[case] values: [&str; 2], #[case] expected: bool) {
740        let array = VarBinViewArray::from_iter_str(values);
741        assert_eq!(is_ascii(&array.resolved_views()), expected);
742    }
743
744    /// A non-columnar input is executed through the executor before the pattern is matched.
745    #[test]
746    fn executes_non_columnar_input_iteratively() -> vortex_error::VortexResult<()> {
747        let mut ctx = SESSION.create_execution_ctx();
748        let chunks = vec![
749            VarBinViewArray::from_iter_str(["alpha", "beta"]).into_array(),
750            VarBinViewArray::from_iter_str(["alphabet"]).into_array(),
751        ];
752        let dtype = chunks[0].dtype().clone();
753        let chunked = vortex_array::arrays::ChunkedArray::try_new(chunks, dtype)?.into_array();
754        let result = Like::try_new(
755            chunked,
756            ConstantArray::new("alpha%", 3).into_array(),
757            LikeOptions::default(),
758        )?
759        .into_array();
760
761        assert_arrays_eq!(result, BoolArray::from_iter([true, false, true]), &mut ctx);
762        Ok(())
763    }
764}