Omega359 commented on code in PR #14282: URL: https://github.com/apache/datafusion/pull/14282#discussion_r1929809676
########## datafusion/functions/src/regex/regexpextract.rs: ########## @@ -0,0 +1,289 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +use std::sync::Arc; + +use arrow::array::builder::GenericStringBuilder; +use arrow::array::{Array, ArrayRef, AsArray, OffsetSizeTrait}; +use arrow::datatypes::{DataType, Int64Type}; +use datafusion_common::{ + cast::as_generic_string_array, exec_err, internal_err, plan_err, DataFusionError, + Result, +}; +use datafusion_expr::{ + ColumnarValue, Documentation, ScalarFunctionArgs, ScalarUDFImpl, Signature, + TypeSignature, Volatility, +}; +use datafusion_macros::user_doc; +use regex::Regex; + +#[user_doc( + doc_section(label = "Regular Expression Functions"), + description = "Extract a specific group matched by [regular expression](https://docs.rs/regex/latest/regex/#syntax). If the regex did not match, or the specified group did not match, an empty string is returned..", + syntax_example = "regexp_extract(str, regexp, idx)", + sql_example = r#"```sql + > select regexp_extract('100-200', '(\d+)-(\d+)', 1); + +---------------------------------------------------------------+ + | regexp_extract(Utf8("100-200"),Utf8("(\d+)-(\d+)"), Int64(1)) | + +---------------------------------------------------------------+ + | [100] | + +---------------------------------------------------------------+ +``` +"#, + standard_argument(name = "str", prefix = "String"), + standard_argument(name = "regexp", prefix = "Regular"), + standard_argument(name = "idx", prefix = "Integer") +)] +#[derive(Debug)] +pub struct RegexpExtractFunc { + signature: Signature, +} + +impl Default for RegexpExtractFunc { + fn default() -> Self { + Self::new() + } +} + +impl RegexpExtractFunc { + pub fn new() -> Self { + Self { + signature: Signature::one_of( + vec![ + TypeSignature::Exact(vec![ + DataType::Utf8, + DataType::Utf8, + DataType::Int64, + ]), + TypeSignature::Exact(vec![ + DataType::LargeUtf8, + DataType::LargeUtf8, + DataType::Int64, + ]), + TypeSignature::Exact(vec![ + DataType::Utf8View, + DataType::Utf8View, + DataType::Int64, + ]), + ], + Volatility::Immutable, + ), + } + } +} + +impl ScalarUDFImpl for RegexpExtractFunc { + fn as_any(&self) -> &dyn std::any::Any { + self + } + + fn name(&self) -> &str { + "regexp_extract" + } + + fn signature(&self) -> &Signature { + &self.signature + } + + fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> { + use DataType::*; + Ok(match &arg_types[0] { + LargeUtf8 => LargeUtf8, + Utf8 => Utf8, + Utf8View => Utf8View, + Null => Null, + other => { + return plan_err!( + "The regexp_extract function can only accept strings. Got {other}" + ); + } + }) + } + + fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> { + let args_len = args.args.len(); + if args_len != 3 { + return exec_err!("regexp_extract was called with {args_len} arguments, but it can accept only 3."); + } + + let target = args.args[0].to_array(args.number_rows)?; + let pattern = args.args[1].to_array(args.number_rows)?; + let idx = args.args[2].to_array(args.number_rows)?; + + let res = regexp_extract_func(&[target, pattern, idx])?; + Ok(ColumnarValue::Array(res)) + } + + fn documentation(&self) -> Option<&Documentation> { + self.doc() + } +} + +fn regexp_extract_func(args: &[ArrayRef; 3]) -> Result<ArrayRef> { + match args[0].data_type() { + DataType::Utf8 | DataType::Utf8View => regexp_extract::<i32>(args), + DataType::LargeUtf8 => regexp_extract::<i64>(args), + other => { + internal_err!("Unsupported data type {other:?} for function regexp_extract") + } + } +} + +fn regexp_extract<T: OffsetSizeTrait>(args: &[ArrayRef]) -> Result<ArrayRef> { + let target = as_generic_string_array::<T>(&args[0])?; + let pattern = as_generic_string_array::<T>(&args[1])?; Review Comment: Given how expensive compiling a pattern is we likely will want to handle the case where the regex column is a scalar value (the most likely case generally). In the case where it's an array we likely would want to have a cache. This could be done as a followup PR. One could look at the regexpcount.rs as an example of how that was handled. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: github-unsubscr...@datafusion.apache.org For queries about this service, please contact Infrastructure at: us...@infra.apache.org --------------------------------------------------------------------- To unsubscribe, e-mail: github-unsubscr...@datafusion.apache.org For additional commands, e-mail: github-h...@datafusion.apache.org