|
| 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 | + |
| 18 | +use crate::utils::down_cast_any_ref; |
| 19 | +use crate::SparkError; |
| 20 | +use arrow::compute::take; |
| 21 | +use arrow_array::builder::BooleanBuilder; |
| 22 | +use arrow_array::types::Int32Type; |
| 23 | +use arrow_array::{Array, BooleanArray, DictionaryArray, RecordBatch, StringArray}; |
| 24 | +use arrow_schema::{DataType, Schema}; |
| 25 | +use datafusion_common::{internal_err, Result}; |
| 26 | +use datafusion_expr::ColumnarValue; |
| 27 | +use datafusion_physical_expr_common::physical_expr::PhysicalExpr; |
| 28 | +use regex::Regex; |
| 29 | +use std::any::Any; |
| 30 | +use std::fmt::{Display, Formatter}; |
| 31 | +use std::hash::{Hash, Hasher}; |
| 32 | +use std::sync::Arc; |
| 33 | + |
| 34 | +/// Implementation of RLIKE operator. |
| 35 | +/// |
| 36 | +/// Note that this implementation is not yet Spark-compatible and simply delegates to |
| 37 | +/// the Rust regexp crate. It will match Spark behavior for some simple cases but has |
| 38 | +/// differences in whitespace handling and does not support all the features of Java's |
| 39 | +/// regular expression engine, which are documented at: |
| 40 | +/// |
| 41 | +/// https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html |
| 42 | +#[derive(Debug)] |
| 43 | +pub struct RLike { |
| 44 | + child: Arc<dyn PhysicalExpr>, |
| 45 | + // Only scalar patterns are supported |
| 46 | + pattern_str: String, |
| 47 | + pattern: Regex, |
| 48 | +} |
| 49 | + |
| 50 | +impl Hash for RLike { |
| 51 | + fn hash<H: Hasher>(&self, state: &mut H) { |
| 52 | + state.write(self.pattern_str.as_bytes()); |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +impl RLike { |
| 57 | + pub fn try_new(child: Arc<dyn PhysicalExpr>, pattern: &str) -> Result<Self> { |
| 58 | + Ok(Self { |
| 59 | + child, |
| 60 | + pattern_str: pattern.to_string(), |
| 61 | + pattern: Regex::new(pattern).map_err(|e| { |
| 62 | + SparkError::Internal(format!("Failed to compile pattern {}: {}", pattern, e)) |
| 63 | + })?, |
| 64 | + }) |
| 65 | + } |
| 66 | + |
| 67 | + fn is_match(&self, inputs: &StringArray) -> BooleanArray { |
| 68 | + let mut builder = BooleanBuilder::with_capacity(inputs.len()); |
| 69 | + if inputs.is_nullable() { |
| 70 | + for i in 0..inputs.len() { |
| 71 | + if inputs.is_null(i) { |
| 72 | + builder.append_null(); |
| 73 | + } else { |
| 74 | + builder.append_value(self.pattern.is_match(inputs.value(i))); |
| 75 | + } |
| 76 | + } |
| 77 | + } else { |
| 78 | + for i in 0..inputs.len() { |
| 79 | + builder.append_value(self.pattern.is_match(inputs.value(i))); |
| 80 | + } |
| 81 | + } |
| 82 | + builder.finish() |
| 83 | + } |
| 84 | +} |
| 85 | + |
| 86 | +impl Display for RLike { |
| 87 | + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { |
| 88 | + write!( |
| 89 | + f, |
| 90 | + "RLike [child: {}, pattern: {}] ", |
| 91 | + self.child, self.pattern_str |
| 92 | + ) |
| 93 | + } |
| 94 | +} |
| 95 | + |
| 96 | +impl PartialEq<dyn Any> for RLike { |
| 97 | + fn eq(&self, other: &dyn Any) -> bool { |
| 98 | + down_cast_any_ref(other) |
| 99 | + .downcast_ref::<Self>() |
| 100 | + .map(|x| self.child.eq(&x.child) && self.pattern_str.eq(&x.pattern_str)) |
| 101 | + .unwrap_or(false) |
| 102 | + } |
| 103 | +} |
| 104 | + |
| 105 | +impl PhysicalExpr for RLike { |
| 106 | + fn as_any(&self) -> &dyn Any { |
| 107 | + self |
| 108 | + } |
| 109 | + |
| 110 | + fn data_type(&self, _input_schema: &Schema) -> Result<DataType> { |
| 111 | + Ok(DataType::Boolean) |
| 112 | + } |
| 113 | + |
| 114 | + fn nullable(&self, input_schema: &Schema) -> Result<bool> { |
| 115 | + self.child.nullable(input_schema) |
| 116 | + } |
| 117 | + |
| 118 | + fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> { |
| 119 | + match self.child.evaluate(batch)? { |
| 120 | + ColumnarValue::Array(array) if array.as_any().is::<DictionaryArray<Int32Type>>() => { |
| 121 | + let dict_array = array |
| 122 | + .as_any() |
| 123 | + .downcast_ref::<DictionaryArray<Int32Type>>() |
| 124 | + .expect("dict array"); |
| 125 | + let dict_values = dict_array |
| 126 | + .values() |
| 127 | + .as_any() |
| 128 | + .downcast_ref::<StringArray>() |
| 129 | + .expect("strings"); |
| 130 | + // evaluate the regexp pattern against the dictionary values |
| 131 | + let new_values = self.is_match(dict_values); |
| 132 | + // convert to conventional (not dictionary-encoded) array |
| 133 | + let result = take(&new_values, dict_array.keys(), None)?; |
| 134 | + Ok(ColumnarValue::Array(result)) |
| 135 | + } |
| 136 | + ColumnarValue::Array(array) => { |
| 137 | + let inputs = array |
| 138 | + .as_any() |
| 139 | + .downcast_ref::<StringArray>() |
| 140 | + .expect("string array"); |
| 141 | + let array = self.is_match(inputs); |
| 142 | + Ok(ColumnarValue::Array(Arc::new(array))) |
| 143 | + } |
| 144 | + ColumnarValue::Scalar(_) => { |
| 145 | + internal_err!("non scalar regexp patterns are not supported") |
| 146 | + } |
| 147 | + } |
| 148 | + } |
| 149 | + |
| 150 | + fn children(&self) -> Vec<&Arc<dyn PhysicalExpr>> { |
| 151 | + vec![&self.child] |
| 152 | + } |
| 153 | + |
| 154 | + fn with_new_children( |
| 155 | + self: Arc<Self>, |
| 156 | + children: Vec<Arc<dyn PhysicalExpr>>, |
| 157 | + ) -> Result<Arc<dyn PhysicalExpr>> { |
| 158 | + assert!(children.len() == 1); |
| 159 | + Ok(Arc::new(RLike::try_new( |
| 160 | + children[0].clone(), |
| 161 | + &self.pattern_str, |
| 162 | + )?)) |
| 163 | + } |
| 164 | + |
| 165 | + fn dyn_hash(&self, state: &mut dyn Hasher) { |
| 166 | + use std::hash::Hash; |
| 167 | + let mut s = state; |
| 168 | + self.hash(&mut s); |
| 169 | + } |
| 170 | +} |
0 commit comments