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 std::hash::Hash;
19use std::{any::Any, sync::Arc};
20
21use crate::PhysicalExpr;
22use arrow::datatypes::{DataType, Schema};
23use arrow::record_batch::RecordBatch;
24use datafusion_common::{internal_err, Result};
25use datafusion_expr::ColumnarValue;
26use datafusion_physical_expr_common::datum::apply_cmp;
27
28// Like expression
29#[derive(Debug, Eq)]
30pub struct LikeExpr {
31    negated: bool,
32    case_insensitive: bool,
33    expr: Arc<dyn PhysicalExpr>,
34    pattern: Arc<dyn PhysicalExpr>,
35}
36
37// Manually derive PartialEq and Hash to work around https://github.com/rust-lang/rust/issues/78808
38impl PartialEq for LikeExpr {
39    fn eq(&self, other: &Self) -> bool {
40        self.negated == other.negated
41            && self.case_insensitive == other.case_insensitive
42            && self.expr.eq(&other.expr)
43            && self.pattern.eq(&other.pattern)
44    }
45}
46
47impl Hash for LikeExpr {
48    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
49        self.negated.hash(state);
50        self.case_insensitive.hash(state);
51        self.expr.hash(state);
52        self.pattern.hash(state);
53    }
54}
55
56impl LikeExpr {
57    pub fn new(
58        negated: bool,
59        case_insensitive: bool,
60        expr: Arc<dyn PhysicalExpr>,
61        pattern: Arc<dyn PhysicalExpr>,
62    ) -> Self {
63        Self {
64            negated,
65            case_insensitive,
66            expr,
67            pattern,
68        }
69    }
70
71    /// Is negated
72    pub fn negated(&self) -> bool {
73        self.negated
74    }
75
76    /// Is case insensitive
77    pub fn case_insensitive(&self) -> bool {
78        self.case_insensitive
79    }
80
81    /// Input expression
82    pub fn expr(&self) -> &Arc<dyn PhysicalExpr> {
83        &self.expr
84    }
85
86    /// Pattern expression
87    pub fn pattern(&self) -> &Arc<dyn PhysicalExpr> {
88        &self.pattern
89    }
90
91    /// Operator name
92    fn op_name(&self) -> &str {
93        match (self.negated, self.case_insensitive) {
94            (false, false) => "LIKE",
95            (true, false) => "NOT LIKE",
96            (false, true) => "ILIKE",
97            (true, true) => "NOT ILIKE",
98        }
99    }
100}
101
102impl std::fmt::Display for LikeExpr {
103    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
104        write!(f, "{} {} {}", self.expr, self.op_name(), self.pattern)
105    }
106}
107
108impl PhysicalExpr for LikeExpr {
109    fn as_any(&self) -> &dyn Any {
110        self
111    }
112
113    fn data_type(&self, _input_schema: &Schema) -> Result<DataType> {
114        Ok(DataType::Boolean)
115    }
116
117    fn nullable(&self, input_schema: &Schema) -> Result<bool> {
118        Ok(self.expr.nullable(input_schema)? || self.pattern.nullable(input_schema)?)
119    }
120
121    fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> {
122        use arrow::compute::*;
123        let lhs = self.expr.evaluate(batch)?;
124        let rhs = self.pattern.evaluate(batch)?;
125        match (self.negated, self.case_insensitive) {
126            (false, false) => apply_cmp(&lhs, &rhs, like),
127            (false, true) => apply_cmp(&lhs, &rhs, ilike),
128            (true, false) => apply_cmp(&lhs, &rhs, nlike),
129            (true, true) => apply_cmp(&lhs, &rhs, nilike),
130        }
131    }
132
133    fn children(&self) -> Vec<&Arc<dyn PhysicalExpr>> {
134        vec![&self.expr, &self.pattern]
135    }
136
137    fn with_new_children(
138        self: Arc<Self>,
139        children: Vec<Arc<dyn PhysicalExpr>>,
140    ) -> Result<Arc<dyn PhysicalExpr>> {
141        Ok(Arc::new(LikeExpr::new(
142            self.negated,
143            self.case_insensitive,
144            Arc::clone(&children[0]),
145            Arc::clone(&children[1]),
146        )))
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    if !expr_type.eq(pattern_type) && !can_like_type(expr_type) {
169        return internal_err!(
170            "The type of {expr_type} AND {pattern_type} of like physical should be same"
171        );
172    }
173    Ok(Arc::new(LikeExpr::new(
174        negated,
175        case_insensitive,
176        expr,
177        pattern,
178    )))
179}
180
181#[cfg(test)]
182mod test {
183    use super::*;
184    use crate::expressions::col;
185    use arrow::array::*;
186    use arrow::datatypes::Field;
187    use datafusion_common::cast::as_boolean_array;
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}