Skip to main content

datafusion_physical_expr/expressions/
like.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5use crate::PhysicalExpr;
6use arrow::datatypes::{DataType, Schema};
7use arrow::record_batch::RecordBatch;
8use datafusion_common::{Result, assert_or_internal_err};
9use datafusion_expr::{ColumnarValue, Operator};
10use datafusion_physical_expr_common::datum::apply_cmp;
11use std::hash::Hash;
12use std::sync::Arc;
13
14// Like expression
15#[derive(Debug, Eq)]
16pub struct LikeExpr {
17    negated: bool,
18    case_insensitive: bool,
19    expr: Arc<dyn PhysicalExpr>,
20    pattern: Arc<dyn PhysicalExpr>,
21}
22
23// Manually derive PartialEq and Hash to work around https://github.com/rust-lang/rust/issues/78808
24impl PartialEq for LikeExpr {
25    fn eq(&self, other: &Self) -> bool {
26        self.negated == other.negated
27            && self.case_insensitive == other.case_insensitive
28            && self.expr.eq(&other.expr)
29            && self.pattern.eq(&other.pattern)
30    }
31}
32
33impl Hash for LikeExpr {
34    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
35        self.negated.hash(state);
36        self.case_insensitive.hash(state);
37        self.expr.hash(state);
38        self.pattern.hash(state);
39    }
40}
41
42impl LikeExpr {
43    pub fn new(
44        negated: bool,
45        case_insensitive: bool,
46        expr: Arc<dyn PhysicalExpr>,
47        pattern: Arc<dyn PhysicalExpr>,
48    ) -> Self {
49        Self {
50            negated,
51            case_insensitive,
52            expr,
53            pattern,
54        }
55    }
56
57    /// Is negated
58    pub fn negated(&self) -> bool {
59        self.negated
60    }
61
62    /// Is case insensitive
63    pub fn case_insensitive(&self) -> bool {
64        self.case_insensitive
65    }
66
67    /// Input expression
68    pub fn expr(&self) -> &Arc<dyn PhysicalExpr> {
69        &self.expr
70    }
71
72    /// Pattern expression
73    pub fn pattern(&self) -> &Arc<dyn PhysicalExpr> {
74        &self.pattern
75    }
76
77    /// Operator name
78    fn op_name(&self) -> &str {
79        match (self.negated, self.case_insensitive) {
80            (false, false) => "LIKE",
81            (true, false) => "NOT LIKE",
82            (false, true) => "ILIKE",
83            (true, true) => "NOT ILIKE",
84        }
85    }
86}
87
88impl std::fmt::Display for LikeExpr {
89    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
90        write!(f, "{} {} {}", self.expr, self.op_name(), self.pattern)
91    }
92}
93
94impl PhysicalExpr for LikeExpr {
95    fn data_type(&self, _input_schema: &Schema) -> Result<DataType> {
96        Ok(DataType::Boolean)
97    }
98
99    fn nullable(&self, input_schema: &Schema) -> Result<bool> {
100        Ok(self.expr.nullable(input_schema)? || self.pattern.nullable(input_schema)?)
101    }
102
103    fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> {
104        let lhs = self.expr.evaluate(batch)?;
105        let rhs = self.pattern.evaluate(batch)?;
106        match (self.negated, self.case_insensitive) {
107            (false, false) => apply_cmp(Operator::LikeMatch, &lhs, &rhs),
108            (false, true) => apply_cmp(Operator::ILikeMatch, &lhs, &rhs),
109            (true, false) => apply_cmp(Operator::NotLikeMatch, &lhs, &rhs),
110            (true, true) => apply_cmp(Operator::NotILikeMatch, &lhs, &rhs),
111        }
112    }
113
114    fn children(&self) -> Vec<&Arc<dyn PhysicalExpr>> {
115        vec![&self.expr, &self.pattern]
116    }
117
118    fn with_new_children(
119        self: Arc<Self>,
120        children: Vec<Arc<dyn PhysicalExpr>>,
121    ) -> Result<Arc<dyn PhysicalExpr>> {
122        Ok(Arc::new(LikeExpr::new(
123            self.negated,
124            self.case_insensitive,
125            Arc::clone(&children[0]),
126            Arc::clone(&children[1]),
127        )))
128    }
129
130    fn fmt_sql(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
131        self.expr.fmt_sql(f)?;
132        write!(f, " {} ", self.op_name())?;
133        self.pattern.fmt_sql(f)
134    }
135
136    #[cfg(feature = "proto")]
137    fn try_to_proto(
138        &self,
139        ctx: &datafusion_physical_expr_common::physical_expr::proto_encode::PhysicalExprEncodeCtx<'_>,
140    ) -> Result<Option<datafusion_proto_models::protobuf::PhysicalExprNode>> {
141        use datafusion_proto_models::protobuf;
142
143        let Self {
144            negated,
145            case_insensitive,
146            expr,
147            pattern,
148        } = self;
149
150        Ok(Some(protobuf::PhysicalExprNode {
151            expr_id: None,
152            expr_type: Some(protobuf::physical_expr_node::ExprType::LikeExpr(Box::new(
153                protobuf::PhysicalLikeExprNode {
154                    negated: *negated,
155                    case_insensitive: *case_insensitive,
156                    expr: Some(Box::new(ctx.encode_child(expr)?)),
157                    pattern: Some(Box::new(ctx.encode_child(pattern)?)),
158                },
159            ))),
160        }))
161    }
162}
163
164#[cfg(feature = "proto")]
165impl LikeExpr {
166    /// Reconstruct a [`LikeExpr`] from its protobuf representation.
167    ///
168    /// Takes the whole [`PhysicalExprNode`] so the decode signature matches
169    /// other migrated expressions and can inspect outer-node metadata if
170    /// needed in the future.
171    ///
172    /// [`PhysicalExprNode`]: datafusion_proto_models::protobuf::PhysicalExprNode
173    pub fn try_from_proto(
174        node: &datafusion_proto_models::protobuf::PhysicalExprNode,
175        ctx: &datafusion_physical_expr_common::physical_expr::proto_decode::PhysicalExprDecodeCtx<'_>,
176    ) -> Result<Arc<dyn PhysicalExpr>> {
177        use datafusion_physical_expr_common::expect_expr_variant;
178        use datafusion_proto_models::protobuf;
179
180        let like_expr = expect_expr_variant!(
181            node,
182            protobuf::physical_expr_node::ExprType::LikeExpr,
183            "LikeExpr",
184        );
185
186        let protobuf::PhysicalLikeExprNode {
187            negated,
188            case_insensitive,
189            expr,
190            pattern,
191        } = like_expr.as_ref();
192
193        Ok(Arc::new(LikeExpr::new(
194            *negated,
195            *case_insensitive,
196            ctx.decode_required_expression(expr.as_deref(), "LikeExpr", "expr")?,
197            ctx.decode_required_expression(pattern.as_deref(), "LikeExpr", "pattern")?,
198        )))
199    }
200}
201
202/// used for optimize Dictionary like
203fn can_like_type(from_type: &DataType) -> bool {
204    match from_type {
205        DataType::Dictionary(_, inner_type_from) => **inner_type_from == DataType::Utf8,
206        _ => false,
207    }
208}
209
210/// Create a like expression, erroring if the argument types are not compatible.
211pub fn like(
212    negated: bool,
213    case_insensitive: bool,
214    expr: Arc<dyn PhysicalExpr>,
215    pattern: Arc<dyn PhysicalExpr>,
216    input_schema: &Schema,
217) -> Result<Arc<dyn PhysicalExpr>> {
218    let expr_type = &expr.data_type(input_schema)?;
219    let pattern_type = &pattern.data_type(input_schema)?;
220    assert_or_internal_err!(
221        expr_type.eq(pattern_type) || can_like_type(expr_type),
222        "The type of {expr_type} AND {pattern_type} of like physical should be same"
223    );
224    Ok(Arc::new(LikeExpr::new(
225        negated,
226        case_insensitive,
227        expr,
228        pattern,
229    )))
230}
231
232#[cfg(test)]
233mod test {
234    use super::*;
235    use crate::expressions::col;
236    use arrow::array::*;
237    use arrow::datatypes::Field;
238    use datafusion_common::cast::as_boolean_array;
239    use datafusion_physical_expr_common::physical_expr::fmt_sql;
240
241    macro_rules! test_like {
242        ($A_VEC:expr, $B_VEC:expr, $VEC:expr, $NULLABLE: expr, $NEGATED:expr, $CASE_INSENSITIVE:expr,) => {{
243            let schema = Schema::new(vec![
244                Field::new("a", DataType::Utf8, $NULLABLE),
245                Field::new("b", DataType::Utf8, $NULLABLE),
246            ]);
247            let a = StringArray::from($A_VEC);
248            let b = StringArray::from($B_VEC);
249
250            let expression = like(
251                $NEGATED,
252                $CASE_INSENSITIVE,
253                col("a", &schema)?,
254                col("b", &schema)?,
255                &schema,
256            )?;
257            let batch = RecordBatch::try_new(
258                Arc::new(schema.clone()),
259                vec![Arc::new(a), Arc::new(b)],
260            )?;
261
262            // compute
263            let result = expression
264                .evaluate(&batch)?
265                .into_array(batch.num_rows())
266                .expect("Failed to convert to array");
267            let result =
268                as_boolean_array(&result).expect("failed to downcast to BooleanArray");
269            let expected = &BooleanArray::from($VEC);
270            assert_eq!(expected, result);
271        }};
272    }
273
274    #[test]
275    fn like_op() -> Result<()> {
276        test_like!(
277            vec!["hello world", "world"],
278            vec!["%hello%", "%hello%"],
279            vec![true, false],
280            false,
281            false,
282            false,
283        ); // like
284        test_like!(
285            vec![Some("hello world"), None, Some("world")],
286            vec![Some("%hello%"), None, Some("%hello%")],
287            vec![Some(false), None, Some(true)],
288            true,
289            true,
290            false,
291        ); // not like
292        test_like!(
293            vec!["hello world", "world"],
294            vec!["%helLo%", "%helLo%"],
295            vec![true, false],
296            false,
297            false,
298            true,
299        ); // ilike
300        test_like!(
301            vec![Some("hello world"), None, Some("world")],
302            vec![Some("%helLo%"), None, Some("%helLo%")],
303            vec![Some(false), None, Some(true)],
304            true,
305            true,
306            true,
307        ); // not ilike
308
309        Ok(())
310    }
311
312    #[test]
313    fn test_fmt_sql() -> Result<()> {
314        let schema = Schema::new(vec![
315            Field::new("a", DataType::Utf8, false),
316            Field::new("b", DataType::Utf8, false),
317        ]);
318
319        let expr = like(
320            false,
321            false,
322            col("a", &schema)?,
323            col("b", &schema)?,
324            &schema,
325        )?;
326
327        // Display format
328        let display_string = expr.to_string();
329        assert_eq!(display_string, "a@0 LIKE b@1");
330
331        // fmt_sql format
332        let sql_string = fmt_sql(expr.as_ref()).to_string();
333        assert_eq!(sql_string, "a LIKE b");
334
335        Ok(())
336    }
337}
338
339/// Tests for the `try_to_proto` / `try_from_proto` hooks.
340#[cfg(all(test, feature = "proto"))]
341mod proto_tests {
342    use super::*;
343    use crate::expressions::{Column, col};
344    use crate::proto_test_util::{
345        StubDecoder, StubEncoder, UnreachableDecoder, column_node,
346    };
347    use arrow::datatypes::Field;
348    use datafusion_common::DataFusionError;
349    use datafusion_physical_expr_common::physical_expr::proto_decode::PhysicalExprDecodeCtx;
350    use datafusion_physical_expr_common::physical_expr::proto_encode::PhysicalExprEncodeCtx;
351    use datafusion_proto_models::protobuf::{
352        PhysicalExprNode, PhysicalLikeExprNode, physical_expr_node,
353    };
354
355    /// Build a `LikeExpr` proto node with the given children.
356    fn like_node(
357        negated: bool,
358        case_insensitive: bool,
359        expr: Option<Box<PhysicalExprNode>>,
360        pattern: Option<Box<PhysicalExprNode>>,
361    ) -> PhysicalExprNode {
362        PhysicalExprNode {
363            expr_id: None,
364            expr_type: Some(physical_expr_node::ExprType::LikeExpr(Box::new(
365                PhysicalLikeExprNode {
366                    negated,
367                    case_insensitive,
368                    expr,
369                    pattern,
370                },
371            ))),
372        }
373    }
374
375    /// A `LikeExpr` over two `Utf8` columns with both flags set, so the
376    /// `negated` / `case_insensitive` wiring is actually exercised.
377    fn like_fixture() -> LikeExpr {
378        let schema = Schema::new(vec![
379            Field::new("a", DataType::Utf8, false),
380            Field::new("b", DataType::Utf8, false),
381        ]);
382        LikeExpr::new(
383            true,
384            true,
385            col("a", &schema).unwrap(),
386            col("b", &schema).unwrap(),
387        )
388    }
389
390    #[test]
391    fn try_to_proto_encodes_like_expr() {
392        let like = like_fixture();
393        let encoder = StubEncoder::ok();
394        let ctx = PhysicalExprEncodeCtx::new(&encoder);
395
396        let node = like
397            .try_to_proto(&ctx)
398            .unwrap()
399            .expect("LikeExpr should encode to Some(node)");
400
401        // Built-in exprs never set expr_id; only dynamic filters do.
402        assert!(node.expr_id.is_none());
403        let like_node = match node.expr_type {
404            Some(physical_expr_node::ExprType::LikeExpr(boxed)) => *boxed,
405            other => panic!("expected a LikeExpr node, got {other:?}"),
406        };
407        assert!(like_node.negated);
408        assert!(like_node.case_insensitive);
409        assert!(like_node.expr.is_some());
410        assert!(like_node.pattern.is_some());
411    }
412
413    #[test]
414    fn try_to_proto_propagates_expr_encode_error() {
415        let like = like_fixture();
416        let encoder = StubEncoder::failing_on(1);
417        let ctx = PhysicalExprEncodeCtx::new(&encoder);
418        let err = like.try_to_proto(&ctx).unwrap_err();
419        assert!(matches!(err, DataFusionError::Internal(msg) if msg.contains("call 1")));
420    }
421
422    #[test]
423    fn try_to_proto_propagates_pattern_encode_error() {
424        let like = like_fixture();
425        let encoder = StubEncoder::failing_on(2);
426        let ctx = PhysicalExprEncodeCtx::new(&encoder);
427        let err = like.try_to_proto(&ctx).unwrap_err();
428        assert!(matches!(err, DataFusionError::Internal(msg) if msg.contains("call 2")));
429    }
430
431    #[test]
432    fn try_from_proto_decodes_like_expr() {
433        let node = like_node(
434            true,
435            true,
436            Some(Box::new(column_node("a"))),
437            Some(Box::new(column_node("b"))),
438        );
439        let schema = Schema::empty();
440        let decoder = StubDecoder::ok();
441        let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
442
443        let decoded = LikeExpr::try_from_proto(&node, &ctx).unwrap();
444        let like = decoded
445            .downcast_ref::<LikeExpr>()
446            .expect("decoded expr should be a LikeExpr");
447        assert!(like.negated());
448        assert!(like.case_insensitive());
449        assert!(like.expr().downcast_ref::<Column>().is_some());
450        assert!(like.pattern().downcast_ref::<Column>().is_some());
451    }
452
453    #[test]
454    fn try_from_proto_rejects_non_like_node() {
455        let node = column_node("a");
456        let schema = Schema::empty();
457        let decoder = UnreachableDecoder;
458        let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
459        let err = LikeExpr::try_from_proto(&node, &ctx).unwrap_err();
460        assert!(matches!(
461            err,
462            DataFusionError::Internal(msg) if msg.contains("PhysicalExprNode is not a LikeExpr")
463        ));
464    }
465
466    #[test]
467    fn try_from_proto_rejects_missing_expr() {
468        let node = like_node(false, false, None, Some(Box::new(column_node("b"))));
469        let schema = Schema::empty();
470        let decoder = UnreachableDecoder;
471        let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
472        let err = LikeExpr::try_from_proto(&node, &ctx).unwrap_err();
473        assert!(matches!(
474            err,
475            DataFusionError::Internal(msg) if msg.contains("LikeExpr is missing required field 'expr'")
476        ));
477    }
478
479    #[test]
480    fn try_from_proto_rejects_missing_pattern() {
481        let node = like_node(false, false, Some(Box::new(column_node("a"))), None);
482        let schema = Schema::empty();
483        // `expr` is present, so it is decoded before the missing-`pattern`
484        // check fires; use a decoder that succeeds for that first child.
485        let decoder = StubDecoder::ok();
486        let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
487        let err = LikeExpr::try_from_proto(&node, &ctx).unwrap_err();
488        assert!(matches!(
489            err,
490            DataFusionError::Internal(msg) if msg.contains("LikeExpr is missing required field 'pattern'")
491        ));
492    }
493
494    #[test]
495    fn try_from_proto_propagates_expr_decode_error() {
496        let node = like_node(
497            false,
498            false,
499            Some(Box::new(column_node("a"))),
500            Some(Box::new(column_node("b"))),
501        );
502        let schema = Schema::empty();
503        let decoder = StubDecoder::failing_on(1);
504        let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
505        let err = LikeExpr::try_from_proto(&node, &ctx).unwrap_err();
506        assert!(matches!(err, DataFusionError::Internal(msg) if msg.contains("call 1")));
507    }
508
509    #[test]
510    fn try_from_proto_propagates_pattern_decode_error() {
511        let node = like_node(
512            false,
513            false,
514            Some(Box::new(column_node("a"))),
515            Some(Box::new(column_node("b"))),
516        );
517        let schema = Schema::empty();
518        let decoder = StubDecoder::failing_on(2);
519        let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
520        let err = LikeExpr::try_from_proto(&node, &ctx).unwrap_err();
521        assert!(matches!(err, DataFusionError::Internal(msg) if msg.contains("call 2")));
522    }
523}