Skip to main content

datafusion_physical_expr/expressions/
like.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18use crate::PhysicalExpr;
19use arrow::datatypes::{DataType, Schema};
20use arrow::record_batch::RecordBatch;
21use datafusion_common::{Result, assert_or_internal_err};
22use datafusion_expr::{ColumnarValue, Operator};
23use datafusion_physical_expr_common::datum::apply_cmp;
24use std::hash::Hash;
25use std::sync::Arc;
26
27// Like expression
28#[derive(Debug, Eq)]
29pub struct LikeExpr {
30    negated: bool,
31    case_insensitive: bool,
32    expr: Arc<dyn PhysicalExpr>,
33    pattern: Arc<dyn PhysicalExpr>,
34}
35
36// Manually derive PartialEq and Hash to work around https://github.com/rust-lang/rust/issues/78808
37impl PartialEq for LikeExpr {
38    fn eq(&self, other: &Self) -> bool {
39        self.negated == other.negated
40            && self.case_insensitive == other.case_insensitive
41            && self.expr.eq(&other.expr)
42            && self.pattern.eq(&other.pattern)
43    }
44}
45
46impl Hash for LikeExpr {
47    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
48        self.negated.hash(state);
49        self.case_insensitive.hash(state);
50        self.expr.hash(state);
51        self.pattern.hash(state);
52    }
53}
54
55impl LikeExpr {
56    pub fn new(
57        negated: bool,
58        case_insensitive: bool,
59        expr: Arc<dyn PhysicalExpr>,
60        pattern: Arc<dyn PhysicalExpr>,
61    ) -> Self {
62        Self {
63            negated,
64            case_insensitive,
65            expr,
66            pattern,
67        }
68    }
69
70    /// Is negated
71    pub fn negated(&self) -> bool {
72        self.negated
73    }
74
75    /// Is case insensitive
76    pub fn case_insensitive(&self) -> bool {
77        self.case_insensitive
78    }
79
80    /// Input expression
81    pub fn expr(&self) -> &Arc<dyn PhysicalExpr> {
82        &self.expr
83    }
84
85    /// Pattern expression
86    pub fn pattern(&self) -> &Arc<dyn PhysicalExpr> {
87        &self.pattern
88    }
89
90    /// Operator name
91    fn op_name(&self) -> &str {
92        match (self.negated, self.case_insensitive) {
93            (false, false) => "LIKE",
94            (true, false) => "NOT LIKE",
95            (false, true) => "ILIKE",
96            (true, true) => "NOT ILIKE",
97        }
98    }
99}
100
101impl std::fmt::Display for LikeExpr {
102    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
103        write!(f, "{} {} {}", self.expr, self.op_name(), self.pattern)
104    }
105}
106
107impl PhysicalExpr for LikeExpr {
108    fn data_type(&self, _input_schema: &Schema) -> Result<DataType> {
109        Ok(DataType::Boolean)
110    }
111
112    fn nullable(&self, input_schema: &Schema) -> Result<bool> {
113        Ok(self.expr.nullable(input_schema)? || self.pattern.nullable(input_schema)?)
114    }
115
116    fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> {
117        let lhs = self.expr.evaluate(batch)?;
118        let rhs = self.pattern.evaluate(batch)?;
119        match (self.negated, self.case_insensitive) {
120            (false, false) => apply_cmp(Operator::LikeMatch, &lhs, &rhs),
121            (false, true) => apply_cmp(Operator::ILikeMatch, &lhs, &rhs),
122            (true, false) => apply_cmp(Operator::NotLikeMatch, &lhs, &rhs),
123            (true, true) => apply_cmp(Operator::NotILikeMatch, &lhs, &rhs),
124        }
125    }
126
127    fn children(&self) -> Vec<&Arc<dyn PhysicalExpr>> {
128        vec![&self.expr, &self.pattern]
129    }
130
131    fn with_new_children(
132        self: Arc<Self>,
133        children: Vec<Arc<dyn PhysicalExpr>>,
134    ) -> Result<Arc<dyn PhysicalExpr>> {
135        Ok(Arc::new(LikeExpr::new(
136            self.negated,
137            self.case_insensitive,
138            Arc::clone(&children[0]),
139            Arc::clone(&children[1]),
140        )))
141    }
142
143    fn fmt_sql(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
144        self.expr.fmt_sql(f)?;
145        write!(f, " {} ", self.op_name())?;
146        self.pattern.fmt_sql(f)
147    }
148}
149
150/// used for optimize Dictionary like
151fn can_like_type(from_type: &DataType) -> bool {
152    match from_type {
153        DataType::Dictionary(_, inner_type_from) => **inner_type_from == DataType::Utf8,
154        _ => false,
155    }
156}
157
158/// Create a like expression, erroring if the argument types are not compatible.
159pub fn like(
160    negated: bool,
161    case_insensitive: bool,
162    expr: Arc<dyn PhysicalExpr>,
163    pattern: Arc<dyn PhysicalExpr>,
164    input_schema: &Schema,
165) -> Result<Arc<dyn PhysicalExpr>> {
166    let expr_type = &expr.data_type(input_schema)?;
167    let pattern_type = &pattern.data_type(input_schema)?;
168    assert_or_internal_err!(
169        expr_type.eq(pattern_type) || can_like_type(expr_type),
170        "The type of {expr_type} AND {pattern_type} of like physical should be same"
171    );
172    Ok(Arc::new(LikeExpr::new(
173        negated,
174        case_insensitive,
175        expr,
176        pattern,
177    )))
178}
179
180#[cfg(test)]
181mod test {
182    use super::*;
183    use crate::expressions::col;
184    use arrow::array::*;
185    use arrow::datatypes::Field;
186    use datafusion_common::cast::as_boolean_array;
187    use datafusion_physical_expr_common::physical_expr::fmt_sql;
188
189    macro_rules! test_like {
190        ($A_VEC:expr, $B_VEC:expr, $VEC:expr, $NULLABLE: expr, $NEGATED:expr, $CASE_INSENSITIVE:expr,) => {{
191            let schema = Schema::new(vec![
192                Field::new("a", DataType::Utf8, $NULLABLE),
193                Field::new("b", DataType::Utf8, $NULLABLE),
194            ]);
195            let a = StringArray::from($A_VEC);
196            let b = StringArray::from($B_VEC);
197
198            let expression = like(
199                $NEGATED,
200                $CASE_INSENSITIVE,
201                col("a", &schema)?,
202                col("b", &schema)?,
203                &schema,
204            )?;
205            let batch = RecordBatch::try_new(
206                Arc::new(schema.clone()),
207                vec![Arc::new(a), Arc::new(b)],
208            )?;
209
210            // compute
211            let result = expression
212                .evaluate(&batch)?
213                .into_array(batch.num_rows())
214                .expect("Failed to convert to array");
215            let result =
216                as_boolean_array(&result).expect("failed to downcast to BooleanArray");
217            let expected = &BooleanArray::from($VEC);
218            assert_eq!(expected, result);
219        }};
220    }
221
222    #[test]
223    fn like_op() -> Result<()> {
224        test_like!(
225            vec!["hello world", "world"],
226            vec!["%hello%", "%hello%"],
227            vec![true, false],
228            false,
229            false,
230            false,
231        ); // like
232        test_like!(
233            vec![Some("hello world"), None, Some("world")],
234            vec![Some("%hello%"), None, Some("%hello%")],
235            vec![Some(false), None, Some(true)],
236            true,
237            true,
238            false,
239        ); // not like
240        test_like!(
241            vec!["hello world", "world"],
242            vec!["%helLo%", "%helLo%"],
243            vec![true, false],
244            false,
245            false,
246            true,
247        ); // ilike
248        test_like!(
249            vec![Some("hello world"), None, Some("world")],
250            vec![Some("%helLo%"), None, Some("%helLo%")],
251            vec![Some(false), None, Some(true)],
252            true,
253            true,
254            true,
255        ); // not ilike
256
257        Ok(())
258    }
259
260    #[test]
261    fn test_fmt_sql() -> Result<()> {
262        let schema = Schema::new(vec![
263            Field::new("a", DataType::Utf8, false),
264            Field::new("b", DataType::Utf8, false),
265        ]);
266
267        let expr = like(
268            false,
269            false,
270            col("a", &schema)?,
271            col("b", &schema)?,
272            &schema,
273        )?;
274
275        // Display format
276        let display_string = expr.to_string();
277        assert_eq!(display_string, "a@0 LIKE b@1");
278
279        // fmt_sql format
280        let sql_string = fmt_sql(expr.as_ref()).to_string();
281        assert_eq!(sql_string, "a LIKE b");
282
283        Ok(())
284    }
285}