Skip to main content

datafusion_physical_expr/expressions/
similar_to_pattern.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 std::fmt;
6use std::hash::Hash;
7use std::sync::Arc;
8
9use crate::PhysicalExpr;
10
11use arrow::array::{ArrayRef, LargeStringArray, StringArray, StringViewArray};
12use arrow::datatypes::{DataType, FieldRef};
13use arrow::record_batch::RecordBatch;
14use datafusion_common::{Result, ScalarValue, exec_err};
15use datafusion_expr::ColumnarValue;
16use datafusion_physical_expr_common::physical_expr::fmt_sql;
17
18pub fn sql_similar_to_regex(pattern: &str) -> String {
19    let mut result = String::with_capacity(pattern.len() + 10);
20    result.push_str("^(?:");
21    let mut in_bracket = false;
22    for ch in pattern.chars() {
23        match (ch, in_bracket) {
24            ('%', false) => result.push_str("(?s:.*)"),
25            ('_', false) => result.push_str("(?s:.)"),
26            ('[', false) => {
27                result.push('[');
28                in_bracket = true;
29            }
30            (']', true) => {
31                result.push(']');
32                in_bracket = false;
33            }
34            // `. ^ $` are SQL literals but regex metachars when not inside a
35            // bracket expression; `\` is a regex escape character in all
36            // positions, so it always needs escaping.
37            ('.' | '^' | '$', false) | ('\\', _) => {
38                result.push('\\');
39                result.push(ch);
40            }
41            (c, _) => result.push(c),
42        }
43    }
44    result.push_str(")$");
45    result
46}
47
48#[derive(Debug, Eq)]
49pub struct SqlSimilarToPattern {
50    expr: Arc<dyn PhysicalExpr>,
51}
52
53// Manually derive PartialEq and Hash to work around https://github.com/rust-lang/rust/issues/78808
54impl PartialEq for SqlSimilarToPattern {
55    fn eq(&self, other: &Self) -> bool {
56        self.expr.eq(&other.expr)
57    }
58}
59
60impl Hash for SqlSimilarToPattern {
61    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
62        self.expr.hash(state);
63    }
64}
65
66impl SqlSimilarToPattern {
67    pub fn new(expr: Arc<dyn PhysicalExpr>) -> Self {
68        Self { expr }
69    }
70
71    pub fn expr(&self) -> &Arc<dyn PhysicalExpr> {
72        &self.expr
73    }
74}
75
76impl fmt::Display for SqlSimilarToPattern {
77    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
78        write!(f, "sql_similar_to_regex({})", self.expr)
79    }
80}
81
82impl PhysicalExpr for SqlSimilarToPattern {
83    fn data_type(&self, input_schema: &arrow::datatypes::Schema) -> Result<DataType> {
84        self.expr.data_type(input_schema)
85    }
86
87    fn nullable(&self, input_schema: &arrow::datatypes::Schema) -> Result<bool> {
88        self.expr.nullable(input_schema)
89    }
90
91    fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> {
92        match self.expr.evaluate(batch)? {
93            ColumnarValue::Array(array) => translate_array(&array),
94            ColumnarValue::Scalar(scalar) => {
95                Ok(ColumnarValue::Scalar(translate_scalar(&scalar)?))
96            }
97        }
98    }
99
100    fn return_field(&self, input_schema: &arrow::datatypes::Schema) -> Result<FieldRef> {
101        self.expr.return_field(input_schema)
102    }
103
104    fn children(&self) -> Vec<&Arc<dyn PhysicalExpr>> {
105        vec![&self.expr]
106    }
107
108    fn with_new_children(
109        self: Arc<Self>,
110        children: Vec<Arc<dyn PhysicalExpr>>,
111    ) -> Result<Arc<dyn PhysicalExpr>> {
112        Ok(Arc::new(SqlSimilarToPattern::new(Arc::clone(&children[0]))))
113    }
114
115    fn fmt_sql(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
116        write!(f, "sql_similar_to_regex({})", fmt_sql(self.expr.as_ref()))
117    }
118
119    #[cfg(feature = "proto")]
120    fn try_to_proto(
121        &self,
122        ctx: &datafusion_physical_expr_common::physical_expr::proto_encode::PhysicalExprEncodeCtx<'_>,
123    ) -> Result<Option<datafusion_proto_models::protobuf::PhysicalExprNode>> {
124        use datafusion_proto_models::protobuf;
125
126        let Self { expr } = self;
127
128        Ok(Some(protobuf::PhysicalExprNode {
129            expr_id: None,
130            expr_type: Some(protobuf::physical_expr_node::ExprType::SqlSimilarToPattern(
131                Box::new(protobuf::PhysicalSqlSimilarToPatternNode {
132                    expr: Some(Box::new(ctx.encode_child(expr)?)),
133                }),
134            )),
135        }))
136    }
137}
138
139#[cfg(feature = "proto")]
140impl SqlSimilarToPattern {
141    /// Reconstruct a [`SqlSimilarToPattern`] from its protobuf representation.
142    ///
143    /// Takes the whole [`PhysicalExprNode`] so the decode signature matches
144    /// other migrated expressions and can inspect outer-node metadata if
145    /// needed in the future.
146    ///
147    /// [`PhysicalExprNode`]: datafusion_proto_models::protobuf::PhysicalExprNode
148    pub fn try_from_proto(
149        node: &datafusion_proto_models::protobuf::PhysicalExprNode,
150        ctx: &datafusion_physical_expr_common::physical_expr::proto_decode::PhysicalExprDecodeCtx<'_>,
151    ) -> Result<Arc<dyn PhysicalExpr>> {
152        use datafusion_physical_expr_common::expect_expr_variant;
153        use datafusion_proto_models::protobuf;
154
155        let pattern = expect_expr_variant!(
156            node,
157            protobuf::physical_expr_node::ExprType::SqlSimilarToPattern,
158            "SqlSimilarToPattern",
159        );
160
161        let protobuf::PhysicalSqlSimilarToPatternNode { expr } = pattern.as_ref();
162
163        Ok(Arc::new(SqlSimilarToPattern::new(
164            ctx.decode_required_expression(
165                expr.as_deref(),
166                "SqlSimilarToPattern",
167                "expr",
168            )?,
169        )))
170    }
171}
172
173pub(crate) fn translate_scalar(scalar: &ScalarValue) -> Result<ScalarValue> {
174    match scalar {
175        ScalarValue::Utf8(Some(s)) => {
176            Ok(ScalarValue::Utf8(Some(sql_similar_to_regex(s))))
177        }
178        ScalarValue::LargeUtf8(Some(s)) => {
179            Ok(ScalarValue::LargeUtf8(Some(sql_similar_to_regex(s))))
180        }
181        ScalarValue::Utf8View(Some(s)) => {
182            Ok(ScalarValue::Utf8View(Some(sql_similar_to_regex(s))))
183        }
184        // A NULL pattern makes the whole predicate NULL, but the string variant
185        // still has to survive the translation: the regex kernel dispatches on
186        // the left-hand type and downcasts the pattern to the same array type.
187        ScalarValue::Utf8(None) => Ok(ScalarValue::Utf8(None)),
188        ScalarValue::LargeUtf8(None) => Ok(ScalarValue::LargeUtf8(None)),
189        ScalarValue::Utf8View(None) => Ok(ScalarValue::Utf8View(None)),
190        ScalarValue::Null => Ok(ScalarValue::Utf8(None)),
191        other => exec_err!("SIMILAR TO pattern must be a string type, got {other:?}"),
192    }
193}
194
195fn translate_array(array: &ArrayRef) -> Result<ColumnarValue> {
196    match array.data_type() {
197        DataType::Utf8 => {
198            let arr = array.as_any().downcast_ref::<StringArray>().unwrap();
199            let translated: StringArray = arr
200                .iter()
201                .map(|opt| opt.map(sql_similar_to_regex))
202                .collect();
203            Ok(ColumnarValue::Array(Arc::new(translated)))
204        }
205        DataType::LargeUtf8 => {
206            let arr = array.as_any().downcast_ref::<LargeStringArray>().unwrap();
207            let translated: LargeStringArray = arr
208                .iter()
209                .map(|opt| opt.map(sql_similar_to_regex))
210                .collect();
211            Ok(ColumnarValue::Array(Arc::new(translated)))
212        }
213        DataType::Utf8View => {
214            let arr = array.as_any().downcast_ref::<StringViewArray>().unwrap();
215            let translated: StringViewArray = arr
216                .iter()
217                .map(|opt| opt.map(sql_similar_to_regex))
218                .collect();
219            Ok(ColumnarValue::Array(Arc::new(translated)))
220        }
221        other => exec_err!("SIMILAR TO pattern must be a string type, got {other:?}"),
222    }
223}
224
225#[cfg(test)]
226mod tests {
227    use super::*;
228    use crate::expressions::{col, lit};
229    use arrow::array::StringArray;
230    use arrow::datatypes::{DataType, Field, Schema};
231    use datafusion_common::cast::as_string_array;
232
233    #[test]
234    fn test_translate_scalar() -> Result<()> {
235        assert_eq!(
236            translate_scalar(&ScalarValue::Utf8(Some("a%".to_string())))?,
237            ScalarValue::Utf8(Some(r"^(?:a(?s:.*))$".to_string()))
238        );
239        assert_eq!(
240            translate_scalar(&ScalarValue::Utf8(Some("a.b".to_string())))?,
241            ScalarValue::Utf8(Some(r"^(?:a\.b)$".to_string()))
242        );
243        assert!(
244            translate_scalar(&ScalarValue::Null).is_ok(),
245            "NULL pattern should pass through"
246        );
247        assert_eq!(
248            translate_scalar(&ScalarValue::Null).unwrap(),
249            ScalarValue::Utf8(None)
250        );
251        // A NULL pattern keeps its string variant: the regex kernel dispatches
252        // on the left-hand type and downcasts the pattern to the same type.
253        assert_eq!(
254            translate_scalar(&ScalarValue::LargeUtf8(None))?,
255            ScalarValue::LargeUtf8(None)
256        );
257        assert_eq!(
258            translate_scalar(&ScalarValue::Utf8View(None))?,
259            ScalarValue::Utf8View(None)
260        );
261        // Non-`Utf8` patterns keep their variant when translated too.
262        assert_eq!(
263            translate_scalar(&ScalarValue::LargeUtf8(Some("a%".to_string())))?,
264            ScalarValue::LargeUtf8(Some(r"^(?:a(?s:.*))$".to_string()))
265        );
266        assert_eq!(
267            translate_scalar(&ScalarValue::Utf8View(Some("a%".to_string())))?,
268            ScalarValue::Utf8View(Some(r"^(?:a(?s:.*))$".to_string()))
269        );
270        assert!(translate_scalar(&ScalarValue::Int32(Some(1))).is_err());
271        Ok(())
272    }
273
274    #[test]
275    fn test_translate_array() -> Result<()> {
276        let schema = Schema::new(vec![Field::new("a", DataType::Utf8, false)]);
277        let input = StringArray::from(vec!["a%", "a.b", "a_b"]);
278        let expr = SqlSimilarToPattern::new(col("a", &schema)?);
279        let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(input)])?;
280        let result = expr.evaluate(&batch)?.into_array(batch.num_rows())?;
281        let result = as_string_array(&result)?;
282        assert_eq!(result.value(0), r"^(?:a(?s:.*))$");
283        assert_eq!(result.value(1), r"^(?:a\.b)$");
284        assert_eq!(result.value(2), r"^(?:a(?s:.)b)$");
285        Ok(())
286    }
287
288    #[test]
289    fn test_display_and_sql() -> Result<()> {
290        let expr = SqlSimilarToPattern::new(lit("a%"));
291        assert_eq!("sql_similar_to_regex(a%)", format!("{expr}"));
292        Ok(())
293    }
294}
295
296/// Tests for the `try_to_proto` / `try_from_proto` hooks.
297#[cfg(all(test, feature = "proto"))]
298mod proto_tests {
299    use super::*;
300    use crate::expressions::{Column, col};
301    use crate::proto_test_util::{
302        StubDecoder, StubEncoder, UnreachableDecoder, column_node,
303    };
304    use arrow::datatypes::{DataType, Field, Schema};
305    use datafusion_common::DataFusionError;
306    use datafusion_physical_expr_common::physical_expr::proto_decode::PhysicalExprDecodeCtx;
307    use datafusion_physical_expr_common::physical_expr::proto_encode::PhysicalExprEncodeCtx;
308    use datafusion_proto_models::protobuf::{
309        PhysicalExprNode, PhysicalSqlSimilarToPatternNode, physical_expr_node,
310    };
311
312    /// Build a `SqlSimilarToPattern` proto node with the given child.
313    fn pattern_node(expr: Option<Box<PhysicalExprNode>>) -> PhysicalExprNode {
314        PhysicalExprNode {
315            expr_id: None,
316            expr_type: Some(physical_expr_node::ExprType::SqlSimilarToPattern(Box::new(
317                PhysicalSqlSimilarToPatternNode { expr },
318            ))),
319        }
320    }
321
322    /// A `SqlSimilarToPattern` over a `Utf8` column.
323    fn pattern_fixture() -> SqlSimilarToPattern {
324        let schema = Schema::new(vec![Field::new("a", DataType::Utf8, false)]);
325        SqlSimilarToPattern::new(col("a", &schema).unwrap())
326    }
327
328    #[test]
329    fn try_to_proto_encodes_sql_similar_to_pattern() {
330        let pattern = pattern_fixture();
331        let encoder = StubEncoder::ok();
332        let ctx = PhysicalExprEncodeCtx::new(&encoder);
333
334        let node = pattern
335            .try_to_proto(&ctx)
336            .unwrap()
337            .expect("SqlSimilarToPattern should encode to Some(node)");
338
339        // Built-in exprs never set expr_id; only dynamic filters do.
340        assert!(node.expr_id.is_none());
341        let pattern_node = match node.expr_type {
342            Some(physical_expr_node::ExprType::SqlSimilarToPattern(boxed)) => *boxed,
343            other => panic!("expected a SqlSimilarToPattern node, got {other:?}"),
344        };
345        assert!(pattern_node.expr.is_some());
346    }
347
348    #[test]
349    fn try_to_proto_propagates_expr_encode_error() {
350        let pattern = pattern_fixture();
351        let encoder = StubEncoder::failing_on(1);
352        let ctx = PhysicalExprEncodeCtx::new(&encoder);
353        let err = pattern.try_to_proto(&ctx).unwrap_err();
354        assert!(matches!(err, DataFusionError::Internal(msg) if msg.contains("call 1")));
355    }
356
357    #[test]
358    fn try_from_proto_decodes_sql_similar_to_pattern() {
359        let node = pattern_node(Some(Box::new(column_node("a"))));
360        let schema = Schema::empty();
361        let decoder = StubDecoder::ok();
362        let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
363
364        let decoded = SqlSimilarToPattern::try_from_proto(&node, &ctx).unwrap();
365        let pattern = decoded
366            .downcast_ref::<SqlSimilarToPattern>()
367            .expect("decoded expr should be a SqlSimilarToPattern");
368        assert!(pattern.expr().downcast_ref::<Column>().is_some());
369    }
370
371    #[test]
372    fn try_from_proto_rejects_non_sql_similar_to_pattern_node() {
373        let node = column_node("a");
374        let schema = Schema::empty();
375        let decoder = UnreachableDecoder;
376        let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
377        let err = SqlSimilarToPattern::try_from_proto(&node, &ctx).unwrap_err();
378        assert!(matches!(
379            err,
380            DataFusionError::Internal(msg)
381                if msg.contains("PhysicalExprNode is not a SqlSimilarToPattern")
382        ));
383    }
384
385    #[test]
386    fn try_from_proto_rejects_missing_expr() {
387        let node = pattern_node(None);
388        let schema = Schema::empty();
389        let decoder = UnreachableDecoder;
390        let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
391        let err = SqlSimilarToPattern::try_from_proto(&node, &ctx).unwrap_err();
392        assert!(matches!(
393            err,
394            DataFusionError::Internal(msg)
395                if msg.contains("SqlSimilarToPattern is missing required field 'expr'")
396        ));
397    }
398
399    #[test]
400    fn try_from_proto_propagates_expr_decode_error() {
401        let node = pattern_node(Some(Box::new(column_node("a"))));
402        let schema = Schema::empty();
403        let decoder = StubDecoder::failing_on(1);
404        let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
405        let err = SqlSimilarToPattern::try_from_proto(&node, &ctx).unwrap_err();
406        assert!(matches!(err, DataFusionError::Internal(msg) if msg.contains("call 1")));
407    }
408}