datafusion_physical_expr/expressions/
like.rs1use crate::PhysicalExpr;
19use arrow::datatypes::{DataType, Schema};
20use arrow::record_batch::RecordBatch;
21use datafusion_common::{internal_err, Result};
22use datafusion_expr::ColumnarValue;
23use datafusion_physical_expr_common::datum::apply_cmp;
24use std::hash::Hash;
25use std::{any::Any, sync::Arc};
26
27#[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
36impl 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 pub fn negated(&self) -> bool {
72 self.negated
73 }
74
75 pub fn case_insensitive(&self) -> bool {
77 self.case_insensitive
78 }
79
80 pub fn expr(&self) -> &Arc<dyn PhysicalExpr> {
82 &self.expr
83 }
84
85 pub fn pattern(&self) -> &Arc<dyn PhysicalExpr> {
87 &self.pattern
88 }
89
90 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 as_any(&self) -> &dyn Any {
109 self
110 }
111
112 fn data_type(&self, _input_schema: &Schema) -> Result<DataType> {
113 Ok(DataType::Boolean)
114 }
115
116 fn nullable(&self, input_schema: &Schema) -> Result<bool> {
117 Ok(self.expr.nullable(input_schema)? || self.pattern.nullable(input_schema)?)
118 }
119
120 fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> {
121 use arrow::compute::*;
122 let lhs = self.expr.evaluate(batch)?;
123 let rhs = self.pattern.evaluate(batch)?;
124 match (self.negated, self.case_insensitive) {
125 (false, false) => apply_cmp(&lhs, &rhs, like),
126 (false, true) => apply_cmp(&lhs, &rhs, ilike),
127 (true, false) => apply_cmp(&lhs, &rhs, nlike),
128 (true, true) => apply_cmp(&lhs, &rhs, nilike),
129 }
130 }
131
132 fn children(&self) -> Vec<&Arc<dyn PhysicalExpr>> {
133 vec![&self.expr, &self.pattern]
134 }
135
136 fn with_new_children(
137 self: Arc<Self>,
138 children: Vec<Arc<dyn PhysicalExpr>>,
139 ) -> Result<Arc<dyn PhysicalExpr>> {
140 Ok(Arc::new(LikeExpr::new(
141 self.negated,
142 self.case_insensitive,
143 Arc::clone(&children[0]),
144 Arc::clone(&children[1]),
145 )))
146 }
147
148 fn fmt_sql(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
149 self.expr.fmt_sql(f)?;
150 write!(f, " {} ", self.op_name())?;
151 self.pattern.fmt_sql(f)
152 }
153}
154
155fn can_like_type(from_type: &DataType) -> bool {
157 match from_type {
158 DataType::Dictionary(_, inner_type_from) => **inner_type_from == DataType::Utf8,
159 _ => false,
160 }
161}
162
163pub fn like(
165 negated: bool,
166 case_insensitive: bool,
167 expr: Arc<dyn PhysicalExpr>,
168 pattern: Arc<dyn PhysicalExpr>,
169 input_schema: &Schema,
170) -> Result<Arc<dyn PhysicalExpr>> {
171 let expr_type = &expr.data_type(input_schema)?;
172 let pattern_type = &pattern.data_type(input_schema)?;
173 if !expr_type.eq(pattern_type) && !can_like_type(expr_type) {
174 return internal_err!(
175 "The type of {expr_type} AND {pattern_type} of like physical should be same"
176 );
177 }
178 Ok(Arc::new(LikeExpr::new(
179 negated,
180 case_insensitive,
181 expr,
182 pattern,
183 )))
184}
185
186#[cfg(test)]
187mod test {
188 use super::*;
189 use crate::expressions::col;
190 use arrow::array::*;
191 use arrow::datatypes::Field;
192 use datafusion_common::cast::as_boolean_array;
193 use datafusion_physical_expr_common::physical_expr::fmt_sql;
194
195 macro_rules! test_like {
196 ($A_VEC:expr, $B_VEC:expr, $VEC:expr, $NULLABLE: expr, $NEGATED:expr, $CASE_INSENSITIVE:expr,) => {{
197 let schema = Schema::new(vec![
198 Field::new("a", DataType::Utf8, $NULLABLE),
199 Field::new("b", DataType::Utf8, $NULLABLE),
200 ]);
201 let a = StringArray::from($A_VEC);
202 let b = StringArray::from($B_VEC);
203
204 let expression = like(
205 $NEGATED,
206 $CASE_INSENSITIVE,
207 col("a", &schema)?,
208 col("b", &schema)?,
209 &schema,
210 )?;
211 let batch = RecordBatch::try_new(
212 Arc::new(schema.clone()),
213 vec![Arc::new(a), Arc::new(b)],
214 )?;
215
216 let result = expression
218 .evaluate(&batch)?
219 .into_array(batch.num_rows())
220 .expect("Failed to convert to array");
221 let result =
222 as_boolean_array(&result).expect("failed to downcast to BooleanArray");
223 let expected = &BooleanArray::from($VEC);
224 assert_eq!(expected, result);
225 }};
226 }
227
228 #[test]
229 fn like_op() -> Result<()> {
230 test_like!(
231 vec!["hello world", "world"],
232 vec!["%hello%", "%hello%"],
233 vec![true, false],
234 false,
235 false,
236 false,
237 ); test_like!(
239 vec![Some("hello world"), None, Some("world")],
240 vec![Some("%hello%"), None, Some("%hello%")],
241 vec![Some(false), None, Some(true)],
242 true,
243 true,
244 false,
245 ); test_like!(
247 vec!["hello world", "world"],
248 vec!["%helLo%", "%helLo%"],
249 vec![true, false],
250 false,
251 false,
252 true,
253 ); test_like!(
255 vec![Some("hello world"), None, Some("world")],
256 vec![Some("%helLo%"), None, Some("%helLo%")],
257 vec![Some(false), None, Some(true)],
258 true,
259 true,
260 true,
261 ); Ok(())
264 }
265
266 #[test]
267 fn test_fmt_sql() -> Result<()> {
268 let schema = Schema::new(vec![
269 Field::new("a", DataType::Utf8, false),
270 Field::new("b", DataType::Utf8, false),
271 ]);
272
273 let expr = like(
274 false,
275 false,
276 col("a", &schema)?,
277 col("b", &schema)?,
278 &schema,
279 )?;
280
281 let display_string = expr.to_string();
283 assert_eq!(display_string, "a@0 LIKE b@1");
284
285 let sql_string = fmt_sql(expr.as_ref()).to_string();
287 assert_eq!(sql_string, "a LIKE b");
288
289 Ok(())
290 }
291}