datafusion-functions 53.1.0

Function packages for the DataFusion query engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
// 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 crate::utils::utf8_to_str_type;
use arrow::array::{
    ArrayRef, GenericStringArray, Int64Array, OffsetSizeTrait, StringArrayType,
    StringViewArray,
};
use arrow::array::{AsArray, GenericStringBuilder};
use arrow::datatypes::DataType;
use datafusion_common::ScalarValue;
use datafusion_common::cast::as_int64_array;
use datafusion_common::types::{NativeType, logical_int64, logical_string};
use datafusion_common::{DataFusionError, Result, exec_datafusion_err, exec_err};
use datafusion_expr::{
    Coercion, ColumnarValue, Documentation, TypeSignatureClass, Volatility,
};
use datafusion_expr::{ScalarFunctionArgs, ScalarUDFImpl, Signature};
use datafusion_macros::user_doc;
use std::any::Any;
use std::sync::Arc;

#[user_doc(
    doc_section(label = "String Functions"),
    description = "Splits a string based on a specified delimiter and returns the substring in the specified position.",
    syntax_example = "split_part(str, delimiter, pos)",
    sql_example = r#"```sql
> select split_part('1.2.3.4.5', '.', 3);
+--------------------------------------------------+
| split_part(Utf8("1.2.3.4.5"),Utf8("."),Int64(3)) |
+--------------------------------------------------+
| 3                                                |
+--------------------------------------------------+
```"#,
    standard_argument(name = "str", prefix = "String"),
    argument(name = "delimiter", description = "String or character to split on."),
    argument(
        name = "pos",
        description = "Position of the part to return (counting from 1). Negative values count backward from the end of the string."
    )
)]
#[derive(Debug, PartialEq, Eq, Hash)]
pub struct SplitPartFunc {
    signature: Signature,
}

impl Default for SplitPartFunc {
    fn default() -> Self {
        Self::new()
    }
}

impl SplitPartFunc {
    pub fn new() -> Self {
        Self {
            signature: Signature::coercible(
                vec![
                    Coercion::new_exact(TypeSignatureClass::Native(logical_string())),
                    Coercion::new_exact(TypeSignatureClass::Native(logical_string())),
                    Coercion::new_implicit(
                        TypeSignatureClass::Native(logical_int64()),
                        vec![TypeSignatureClass::Integer],
                        NativeType::Int64,
                    ),
                ],
                Volatility::Immutable,
            ),
        }
    }
}

impl ScalarUDFImpl for SplitPartFunc {
    fn as_any(&self) -> &dyn Any {
        self
    }

    fn name(&self) -> &str {
        "split_part"
    }

    fn signature(&self) -> &Signature {
        &self.signature
    }

    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
        utf8_to_str_type(&arg_types[0], "split_part")
    }

    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
        let ScalarFunctionArgs { args, .. } = args;

        // First, determine if any of the arguments is an Array
        let len = args.iter().find_map(|arg| match arg {
            ColumnarValue::Array(a) => Some(a.len()),
            _ => None,
        });

        let inferred_length = len.unwrap_or(1);
        let is_scalar = len.is_none();

        // Convert all ColumnarValues to ArrayRefs
        let args = args
            .iter()
            .map(|arg| match arg {
                ColumnarValue::Scalar(scalar) => scalar.to_array_of_size(inferred_length),
                ColumnarValue::Array(array) => Ok(Arc::clone(array)),
            })
            .collect::<Result<Vec<_>>>()?;

        // Unpack the ArrayRefs from the arguments
        let n_array = as_int64_array(&args[2])?;
        let result = match (args[0].data_type(), args[1].data_type()) {
            (DataType::Utf8View, DataType::Utf8View) => {
                split_part_impl::<&StringViewArray, &StringViewArray, i32>(
                    &args[0].as_string_view(),
                    &args[1].as_string_view(),
                    n_array,
                )
            }
            (DataType::Utf8View, DataType::Utf8) => {
                split_part_impl::<&StringViewArray, &GenericStringArray<i32>, i32>(
                    &args[0].as_string_view(),
                    &args[1].as_string::<i32>(),
                    n_array,
                )
            }
            (DataType::Utf8View, DataType::LargeUtf8) => {
                split_part_impl::<&StringViewArray, &GenericStringArray<i64>, i32>(
                    &args[0].as_string_view(),
                    &args[1].as_string::<i64>(),
                    n_array,
                )
            }
            (DataType::Utf8, DataType::Utf8View) => {
                split_part_impl::<&GenericStringArray<i32>, &StringViewArray, i32>(
                    &args[0].as_string::<i32>(),
                    &args[1].as_string_view(),
                    n_array,
                )
            }
            (DataType::LargeUtf8, DataType::Utf8View) => {
                split_part_impl::<&GenericStringArray<i64>, &StringViewArray, i64>(
                    &args[0].as_string::<i64>(),
                    &args[1].as_string_view(),
                    n_array,
                )
            }
            (DataType::Utf8, DataType::Utf8) => {
                split_part_impl::<&GenericStringArray<i32>, &GenericStringArray<i32>, i32>(
                    &args[0].as_string::<i32>(),
                    &args[1].as_string::<i32>(),
                    n_array,
                )
            }
            (DataType::LargeUtf8, DataType::LargeUtf8) => {
                split_part_impl::<&GenericStringArray<i64>, &GenericStringArray<i64>, i64>(
                    &args[0].as_string::<i64>(),
                    &args[1].as_string::<i64>(),
                    n_array,
                )
            }
            (DataType::Utf8, DataType::LargeUtf8) => {
                split_part_impl::<&GenericStringArray<i32>, &GenericStringArray<i64>, i32>(
                    &args[0].as_string::<i32>(),
                    &args[1].as_string::<i64>(),
                    n_array,
                )
            }
            (DataType::LargeUtf8, DataType::Utf8) => {
                split_part_impl::<&GenericStringArray<i64>, &GenericStringArray<i32>, i64>(
                    &args[0].as_string::<i64>(),
                    &args[1].as_string::<i32>(),
                    n_array,
                )
            }
            _ => exec_err!("Unsupported combination of argument types for split_part"),
        };
        if is_scalar {
            // If all inputs are scalar, keep the output as scalar
            let result = result.and_then(|arr| ScalarValue::try_from_array(&arr, 0));
            result.map(ColumnarValue::Scalar)
        } else {
            result.map(ColumnarValue::Array)
        }
    }

    fn documentation(&self) -> Option<&Documentation> {
        self.doc()
    }
}

fn split_part_impl<'a, StringArrType, DelimiterArrType, StringArrayLen>(
    string_array: &StringArrType,
    delimiter_array: &DelimiterArrType,
    n_array: &Int64Array,
) -> Result<ArrayRef>
where
    StringArrType: StringArrayType<'a>,
    DelimiterArrType: StringArrayType<'a>,
    StringArrayLen: OffsetSizeTrait,
{
    let mut builder: GenericStringBuilder<StringArrayLen> = GenericStringBuilder::new();

    string_array
        .iter()
        .zip(delimiter_array.iter())
        .zip(n_array.iter())
        .try_for_each(|((string, delimiter), n)| -> Result<(), DataFusionError> {
            match (string, delimiter, n) {
                (Some(string), Some(delimiter), Some(n)) => {
                    let result = match n.cmp(&0) {
                        std::cmp::Ordering::Greater => {
                            // Positive index: use nth() to avoid collecting all parts
                            // This stops iteration as soon as we find the nth element
                            let idx: usize = (n - 1).try_into().map_err(|_| {
                                exec_datafusion_err!(
                                    "split_part index {n} exceeds maximum supported value"
                                )
                            })?;

                            if delimiter.is_empty() {
                                // Match PostgreSQL split_part behavior for empty delimiter:
                                // treat the input as a single field ("ab" -> ["ab"]),
                                // rather than Rust's split("") result (["", "a", "b", ""]).
                                (n == 1).then_some(string)
                            } else {
                                string.split(delimiter).nth(idx)
                            }
                        }
                        std::cmp::Ordering::Less => {
                            // Negative index: use rsplit().nth() to efficiently get from the end
                            // rsplit iterates in reverse, so -1 means first from rsplit (index 0)
                            let idx: usize = (n.unsigned_abs() - 1).try_into().map_err(|_| {
                                exec_datafusion_err!(
                                    "split_part index {n} exceeds minimum supported value"
                                )
                            })?;
                            if delimiter.is_empty() {
                                // Match PostgreSQL split_part behavior for empty delimiter:
                                // treat the input as a single field ("ab" -> ["ab"]),
                                // rather than Rust's split("") result (["", "a", "b", ""]).
                                (n == -1).then_some(string)
                            } else {
                                string.rsplit(delimiter).nth(idx)
                            }
                        }
                        std::cmp::Ordering::Equal => {
                            return exec_err!("field position must not be zero");
                        }
                    };
                    builder.append_value(result.unwrap_or(""));
                }
                _ => builder.append_null(),
            }
            Ok(())
        })?;

    Ok(Arc::new(builder.finish()) as ArrayRef)
}

#[cfg(test)]
mod tests {
    use arrow::array::{Array, StringArray};
    use arrow::datatypes::DataType::Utf8;

    use datafusion_common::ScalarValue;
    use datafusion_common::{Result, exec_err};
    use datafusion_expr::{ColumnarValue, ScalarUDFImpl};

    use crate::string::split_part::SplitPartFunc;
    use crate::utils::test::test_function;

    #[test]
    fn test_functions() -> Result<()> {
        test_function!(
            SplitPartFunc::new(),
            vec![
                ColumnarValue::Scalar(ScalarValue::Utf8(Some(String::from(
                    "abc~@~def~@~ghi"
                )))),
                ColumnarValue::Scalar(ScalarValue::Utf8(Some(String::from("~@~")))),
                ColumnarValue::Scalar(ScalarValue::Int64(Some(2))),
            ],
            Ok(Some("def")),
            &str,
            Utf8,
            StringArray
        );
        test_function!(
            SplitPartFunc::new(),
            vec![
                ColumnarValue::Scalar(ScalarValue::Utf8(Some(String::from(
                    "abc~@~def~@~ghi"
                )))),
                ColumnarValue::Scalar(ScalarValue::Utf8(Some(String::from("~@~")))),
                ColumnarValue::Scalar(ScalarValue::Int64(Some(20))),
            ],
            Ok(Some("")),
            &str,
            Utf8,
            StringArray
        );
        test_function!(
            SplitPartFunc::new(),
            vec![
                ColumnarValue::Scalar(ScalarValue::Utf8(Some(String::from(
                    "abc~@~def~@~ghi"
                )))),
                ColumnarValue::Scalar(ScalarValue::Utf8(Some(String::from("~@~")))),
                ColumnarValue::Scalar(ScalarValue::Int64(Some(-1))),
            ],
            Ok(Some("ghi")),
            &str,
            Utf8,
            StringArray
        );
        test_function!(
            SplitPartFunc::new(),
            vec![
                ColumnarValue::Scalar(ScalarValue::Utf8(Some(String::from(
                    "abc~@~def~@~ghi"
                )))),
                ColumnarValue::Scalar(ScalarValue::Utf8(Some(String::from("~@~")))),
                ColumnarValue::Scalar(ScalarValue::Int64(Some(0))),
            ],
            exec_err!("field position must not be zero"),
            &str,
            Utf8,
            StringArray
        );
        test_function!(
            SplitPartFunc::new(),
            vec![
                ColumnarValue::Scalar(ScalarValue::Utf8(Some(String::from(
                    "abc~@~def~@~ghi"
                )))),
                ColumnarValue::Scalar(ScalarValue::Utf8(Some(String::from("~@~")))),
                ColumnarValue::Scalar(ScalarValue::Int64(Some(i64::MIN))),
            ],
            Ok(Some("")),
            &str,
            Utf8,
            StringArray
        );
        // Edge cases with delimiters
        test_function!(
            SplitPartFunc::new(),
            vec![
                ColumnarValue::Scalar(ScalarValue::Utf8(Some(String::from("a,b")))),
                ColumnarValue::Scalar(ScalarValue::Utf8(Some(String::from(",")))),
                ColumnarValue::Scalar(ScalarValue::Int64(Some(1))),
            ],
            Ok(Some("a")),
            &str,
            Utf8,
            StringArray
        );
        test_function!(
            SplitPartFunc::new(),
            vec![
                ColumnarValue::Scalar(ScalarValue::Utf8(Some(String::from("a,b")))),
                ColumnarValue::Scalar(ScalarValue::Utf8(Some(String::from(",")))),
                ColumnarValue::Scalar(ScalarValue::Int64(Some(3))),
            ],
            Ok(Some("")),
            &str,
            Utf8,
            StringArray
        );
        test_function!(
            SplitPartFunc::new(),
            vec![
                ColumnarValue::Scalar(ScalarValue::Utf8(Some(String::from("a,b")))),
                ColumnarValue::Scalar(ScalarValue::Utf8(Some(String::from("")))),
                ColumnarValue::Scalar(ScalarValue::Int64(Some(1))),
            ],
            Ok(Some("a,b")),
            &str,
            Utf8,
            StringArray
        );
        test_function!(
            SplitPartFunc::new(),
            vec![
                ColumnarValue::Scalar(ScalarValue::Utf8(Some(String::from("a,b")))),
                ColumnarValue::Scalar(ScalarValue::Utf8(Some(String::from("")))),
                ColumnarValue::Scalar(ScalarValue::Int64(Some(2))),
            ],
            Ok(Some("")),
            &str,
            Utf8,
            StringArray
        );
        test_function!(
            SplitPartFunc::new(),
            vec![
                ColumnarValue::Scalar(ScalarValue::Utf8(Some(String::from("a,b")))),
                ColumnarValue::Scalar(ScalarValue::Utf8(Some(String::from(" ")))),
                ColumnarValue::Scalar(ScalarValue::Int64(Some(1))),
            ],
            Ok(Some("a,b")),
            &str,
            Utf8,
            StringArray
        );
        test_function!(
            SplitPartFunc::new(),
            vec![
                ColumnarValue::Scalar(ScalarValue::Utf8(Some(String::from("a,b")))),
                ColumnarValue::Scalar(ScalarValue::Utf8(Some(String::from(" ")))),
                ColumnarValue::Scalar(ScalarValue::Int64(Some(2))),
            ],
            Ok(Some("")),
            &str,
            Utf8,
            StringArray
        );

        // Edge cases with delimiters with negative n
        test_function!(
            SplitPartFunc::new(),
            vec![
                ColumnarValue::Scalar(ScalarValue::Utf8(Some(String::from("a,b")))),
                ColumnarValue::Scalar(ScalarValue::Utf8(Some(String::from("")))),
                ColumnarValue::Scalar(ScalarValue::Int64(Some(-1))),
            ],
            Ok(Some("a,b")),
            &str,
            Utf8,
            StringArray
        );
        test_function!(
            SplitPartFunc::new(),
            vec![
                ColumnarValue::Scalar(ScalarValue::Utf8(Some(String::from("a,b")))),
                ColumnarValue::Scalar(ScalarValue::Utf8(Some(String::from(" ")))),
                ColumnarValue::Scalar(ScalarValue::Int64(Some(-1))),
            ],
            Ok(Some("a,b")),
            &str,
            Utf8,
            StringArray
        );
        test_function!(
            SplitPartFunc::new(),
            vec![
                ColumnarValue::Scalar(ScalarValue::Utf8(Some(String::from("a,b")))),
                ColumnarValue::Scalar(ScalarValue::Utf8(Some(String::from("")))),
                ColumnarValue::Scalar(ScalarValue::Int64(Some(-2))),
            ],
            Ok(Some("")),
            &str,
            Utf8,
            StringArray
        );

        Ok(())
    }
}