Skip to main content

datafusion_functions_nested/
range.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
5//! [`ScalarUDFImpl`] definitions for range and gen_series functions.
6
7use crate::utils::make_scalar_function;
8use arrow::buffer::OffsetBuffer;
9use arrow::datatypes::TimeUnit;
10use arrow::datatypes::{DataType, Field, IntervalUnit::MonthDayNano};
11use arrow::{
12    array::{
13        Array, ArrayRef, Int64Array, ListArray, ListBuilder, NullBufferBuilder,
14        builder::{Date32Builder, TimestampNanosecondBuilder},
15        temporal_conversions::as_datetime_with_timezone,
16        timezone::Tz,
17        types::{Date32Type, IntervalMonthDayNanoType, TimestampNanosecondType},
18    },
19    compute::cast,
20};
21use datafusion_common::internal_err;
22use datafusion_common::{
23    Result, exec_datafusion_err, exec_err, utils::take_function_args,
24};
25use datafusion_common::{
26    ScalarValue,
27    cast::{
28        as_date32_array, as_int64_array, as_interval_mdn_array,
29        as_timestamp_nanosecond_array,
30    },
31    types::{
32        NativeType, logical_date, logical_int64, logical_interval_mdn, logical_string,
33    },
34};
35use datafusion_expr::{
36    Coercion, ColumnarValue, Documentation, ScalarFunctionArgs, ScalarUDFImpl, Signature,
37    TypeSignature, TypeSignatureClass, Volatility,
38};
39use datafusion_macros::user_doc;
40use std::iter::from_fn;
41use std::str::FromStr;
42use std::sync::Arc;
43
44make_udf_expr_and_func!(
45    Range,
46    range,
47    start stop step,
48    "create a list of values in the range between start and stop",
49    range_udf,
50    Range::new
51);
52
53fn interval_step_is_negative(
54    name: &str,
55    months: i32,
56    days: i32,
57    nanoseconds: i64,
58) -> Result<bool> {
59    let has_positive_component = months > 0 || days > 0 || nanoseconds > 0;
60    let has_negative_component = months < 0 || days < 0 || nanoseconds < 0;
61
62    if has_positive_component && has_negative_component {
63        return exec_err!("Interval argument to {name} must not have mixed signs");
64    }
65
66    Ok(has_negative_component)
67}
68
69make_udf_expr_and_func!(
70    GenSeries,
71    gen_series,
72    start stop step,
73    "create a list of values in the range between start and stop, include upper bound",
74    gen_series_udf,
75    Range::generate_series
76);
77
78#[user_doc(
79    doc_section(label = "Array Functions"),
80    description = "Returns an Arrow array between start and stop with step. The range start..end contains all values with start <= x < end. It is empty if start >= end. Step cannot be 0.",
81    syntax_example = "range(stop)
82range(start, stop[, step])",
83    sql_example = r#"```sql
84> select range(2, 10, 3);
85+------------------------------------+
86| range(Int64(2),Int64(10),Int64(3)) |
87+------------------------------------+
88| [2, 5, 8]                          |
89+------------------------------------+
90
91> select range(DATE '1992-09-01', DATE '1993-03-01', INTERVAL '1' MONTH);
92+--------------------------------------------------------------------------+
93| range(DATE '1992-09-01', DATE '1993-03-01', INTERVAL '1' MONTH)          |
94+--------------------------------------------------------------------------+
95| [1992-09-01, 1992-10-01, 1992-11-01, 1992-12-01, 1993-01-01, 1993-02-01] |
96+--------------------------------------------------------------------------+
97```"#,
98    argument(
99        name = "start",
100        description = "Start of the range. Ints, timestamps, dates or string types that can be coerced to Date32 are supported."
101    ),
102    argument(
103        name = "end",
104        description = "End of the range (not included). Type must be the same as start."
105    ),
106    argument(
107        name = "step",
108        description = "Increase by step (cannot be 0). Steps less than a day are supported only for timestamp ranges."
109    )
110)]
111struct RangeDoc {}
112
113#[user_doc(
114    doc_section(label = "Array Functions"),
115    description = "Similar to the range function, but it includes the upper bound.",
116    syntax_example = "generate_series(stop)
117generate_series(start, stop[, step])",
118    sql_example = r#"```sql
119> select generate_series(1,3);
120+------------------------------------+
121| generate_series(Int64(1),Int64(3)) |
122+------------------------------------+
123| [1, 2, 3]                          |
124+------------------------------------+
125```"#,
126    argument(
127        name = "start",
128        description = "Start of the series. Ints, timestamps, dates or string types that can be coerced to Date32 are supported."
129    ),
130    argument(
131        name = "end",
132        description = "End of the series (included). Type must be the same as start."
133    ),
134    argument(
135        name = "step",
136        description = "Increase by step (can not be 0). Steps less than a day are supported only for timestamp ranges."
137    )
138)]
139struct GenerateSeriesDoc {}
140
141#[derive(Debug, PartialEq, Eq, Hash)]
142pub struct Range {
143    signature: Signature,
144    /// `false` for range, `true` for generate_series
145    include_upper_bound: bool,
146}
147
148impl Default for Range {
149    fn default() -> Self {
150        Self::new()
151    }
152}
153
154impl Range {
155    fn defined_signature() -> Signature {
156        // We natively only support i64 in our implementation; so ensure we cast other integer
157        // types to it.
158        let integer = Coercion::new_implicit(
159            TypeSignatureClass::Native(logical_int64()),
160            vec![TypeSignatureClass::Integer],
161            NativeType::Int64,
162        );
163        // We natively only support mdn in our implementation; so ensure we cast other interval
164        // types to it.
165        let interval = Coercion::new_implicit(
166            TypeSignatureClass::Native(logical_interval_mdn()),
167            vec![TypeSignatureClass::Interval],
168            NativeType::Interval(MonthDayNano),
169        );
170        // Ideally we'd limit to only Date32 & Timestamp(Nanoseconds) as those are the implementations
171        // we have but that is difficult to do with this current API; we'll cast later on to
172        // handle such types.
173        let date = Coercion::new_implicit(
174            TypeSignatureClass::Native(logical_date()),
175            vec![TypeSignatureClass::Native(logical_string())],
176            NativeType::Date,
177        );
178        let timestamp = Coercion::new_exact(TypeSignatureClass::Timestamp);
179        Signature::one_of(
180            vec![
181                // Integer ranges
182                // Stop
183                TypeSignature::Coercible(vec![integer.clone()]),
184                // Start & stop
185                TypeSignature::Coercible(vec![integer.clone(), integer.clone()]),
186                // Start, stop & step
187                TypeSignature::Coercible(vec![integer.clone(), integer.clone(), integer]),
188                // Date range
189                TypeSignature::Coercible(vec![date.clone(), date, interval.clone()]),
190                // Timestamp range
191                TypeSignature::Coercible(vec![timestamp.clone(), timestamp, interval]),
192            ],
193            Volatility::Immutable,
194        )
195    }
196
197    /// Generate `range()` function which excludes upper bound.
198    pub fn new() -> Self {
199        Self {
200            signature: Self::defined_signature(),
201            include_upper_bound: false,
202        }
203    }
204
205    /// Generate `generate_series()` function which includes upper bound.
206    fn generate_series() -> Self {
207        Self {
208            signature: Self::defined_signature(),
209            include_upper_bound: true,
210        }
211    }
212}
213
214impl ScalarUDFImpl for Range {
215    fn name(&self) -> &str {
216        if self.include_upper_bound {
217            "generate_series"
218        } else {
219            "range"
220        }
221    }
222
223    fn signature(&self) -> &Signature {
224        &self.signature
225    }
226
227    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
228        if arg_types.iter().any(|t| t.is_null()) {
229            return Ok(DataType::Null);
230        }
231
232        match (&arg_types[0], arg_types.get(1)) {
233            // In implementation we downcast to Date32 so ensure reflect that here
234            (_, Some(DataType::Date64)) | (DataType::Date64, _) => Ok(DataType::List(
235                Arc::new(Field::new_list_field(DataType::Date32, true)),
236            )),
237            // Ensure we preserve timezone
238            (DataType::Timestamp(_, tz), _) => {
239                Ok(DataType::List(Arc::new(Field::new_list_field(
240                    DataType::Timestamp(TimeUnit::Nanosecond, tz.to_owned()),
241                    true,
242                ))))
243            }
244            _ => Ok(DataType::List(Arc::new(Field::new_list_field(
245                arg_types[0].clone(),
246                true,
247            )))),
248        }
249    }
250
251    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
252        let args = &args.args;
253
254        if args.iter().any(|arg| arg.data_type().is_null()) {
255            return Ok(ColumnarValue::Scalar(ScalarValue::Null));
256        }
257        match args[0].data_type() {
258            DataType::Int64 => {
259                make_scalar_function(|args| self.gen_range_inner(args))(args)
260            }
261            DataType::Date32 | DataType::Date64 => {
262                make_scalar_function(|args| self.gen_range_date(args))(args)
263            }
264            DataType::Timestamp(_, _) => {
265                make_scalar_function(|args| self.gen_range_timestamp(args))(args)
266            }
267            dt => {
268                internal_err!(
269                    "Signature failed to guard unknown input type for {}: {dt}",
270                    self.name()
271                )
272            }
273        }
274    }
275
276    fn documentation(&self) -> Option<&Documentation> {
277        if self.include_upper_bound {
278            GenerateSeriesDoc {}.doc()
279        } else {
280            RangeDoc {}.doc()
281        }
282    }
283}
284
285impl Range {
286    /// Generates an array of integers from start to stop with a given step.
287    ///
288    /// This function takes 1 to 3 ArrayRefs as arguments, representing start, stop, and step values.
289    /// It returns a `Result<ArrayRef>` representing the resulting ListArray after the operation.
290    ///
291    /// # Arguments
292    ///
293    /// * `args` - An array of 1 to 3 ArrayRefs representing start, stop, and step (step value can not be zero) values.
294    ///
295    /// # Examples
296    ///
297    /// gen_range(3) => [0, 1, 2]
298    /// gen_range(1, 4) => [1, 2, 3]
299    /// gen_range(1, 7, 2) => [1, 3, 5]
300    fn gen_range_inner(&self, args: &[ArrayRef]) -> Result<ArrayRef> {
301        let (start_array, stop_array, step_array) = match args {
302            [stop_array] => (None, as_int64_array(stop_array)?, None),
303            [start_array, stop_array] => (
304                Some(as_int64_array(start_array)?),
305                as_int64_array(stop_array)?,
306                None,
307            ),
308            [start_array, stop_array, step_array] => (
309                Some(as_int64_array(start_array)?),
310                as_int64_array(stop_array)?,
311                Some(as_int64_array(step_array)?),
312            ),
313            _ => return internal_err!("{} expects 1 to 3 arguments", self.name()),
314        };
315
316        let mut values = vec![];
317        let mut offsets = Vec::with_capacity(stop_array.len() + 1);
318        offsets.push(0);
319        let mut valid = NullBufferBuilder::new(stop_array.len());
320        for (idx, stop) in stop_array.iter().enumerate() {
321            match retrieve_range_args(start_array, stop, step_array, idx) {
322                Some((_, _, 0)) => {
323                    return exec_err!(
324                        "step can't be 0 for function {}(start [, stop, step])",
325                        self.name()
326                    );
327                }
328                Some((start, stop, step)) => {
329                    generate_range_values(
330                        start,
331                        stop,
332                        step,
333                        self.include_upper_bound,
334                        &mut values,
335                    )?;
336                    offsets.push(values.len() as i32);
337                    valid.append_non_null();
338                }
339                // If any of the arguments is NULL, append a NULL value to the result.
340                None => {
341                    offsets.push(values.len() as i32);
342                    valid.append_null();
343                }
344            }
345        }
346        let arr = Arc::new(ListArray::try_new(
347            Arc::new(Field::new_list_field(DataType::Int64, true)),
348            OffsetBuffer::new(offsets.into()),
349            Arc::new(Int64Array::from(values)),
350            valid.finish(),
351        )?);
352        Ok(arr)
353    }
354
355    fn gen_range_date(&self, args: &[ArrayRef]) -> Result<ArrayRef> {
356        let [start, stop, step] = take_function_args(self.name(), args)?;
357        let step = as_interval_mdn_array(step)?;
358
359        // Signature can only guarantee we get a date type, not specifically
360        // date32 so handle potential cast from date64 here.
361        let start = cast(start, &DataType::Date32)?;
362        let start = as_date32_array(&start)?;
363        let stop = cast(stop, &DataType::Date32)?;
364        let stop = as_date32_array(&stop)?;
365
366        // values are date32s
367        let values_builder = Date32Builder::new();
368        let mut list_builder = ListBuilder::new(values_builder);
369
370        for idx in 0..stop.len() {
371            if start.is_null(idx) || stop.is_null(idx) || step.is_null(idx) {
372                list_builder.append_null();
373                continue;
374            }
375
376            let start = start.value(idx);
377            let stop = stop.value(idx);
378            let step = step.value(idx);
379
380            let (months, days, nanoseconds) = IntervalMonthDayNanoType::to_parts(step);
381            if months == 0 && days == 0 {
382                return exec_err!("Cannot generate date range less than 1 day.");
383            }
384            let neg = interval_step_is_negative(self.name(), months, days, nanoseconds)?;
385
386            let stop = if !self.include_upper_bound {
387                Date32Type::subtract_month_day_nano_opt(stop, step).ok_or_else(|| {
388                    exec_datafusion_err!(
389                        "Cannot generate date range where stop {} - {step:?}) overflows",
390                        date32_to_string(stop)
391                    )
392                })?
393            } else {
394                stop
395            };
396
397            let mut new_date = Some(start);
398
399            let values = from_fn(|| {
400                let Some(current_date) = new_date else {
401                    return None; // previous overflow
402                };
403                if (neg && current_date < stop) || (!neg && current_date > stop) {
404                    None
405                } else {
406                    new_date = Date32Type::add_month_day_nano_opt(current_date, step);
407                    Some(Some(current_date))
408                }
409            });
410
411            list_builder.append_value(values);
412        }
413
414        let arr = Arc::new(list_builder.finish());
415
416        Ok(arr)
417    }
418
419    fn gen_range_timestamp(&self, args: &[ArrayRef]) -> Result<ArrayRef> {
420        let [start, stop, step] = take_function_args(self.name(), args)?;
421        let step = as_interval_mdn_array(step)?;
422
423        // Signature can only guarantee we get a timestamp type, not specifically
424        // timestamp(ns) so handle potential cast from other timestamps here.
425        fn cast_to_ns(arr: &ArrayRef) -> Result<ArrayRef> {
426            match arr.data_type() {
427                DataType::Timestamp(TimeUnit::Nanosecond, _) => Ok(Arc::clone(arr)),
428                DataType::Timestamp(_, tz) => Ok(cast(
429                    arr,
430                    &DataType::Timestamp(TimeUnit::Nanosecond, tz.to_owned()),
431                )?),
432                _ => unreachable!(),
433            }
434        }
435        let start = cast_to_ns(start)?;
436        let start = as_timestamp_nanosecond_array(&start)?;
437        let stop = cast_to_ns(stop)?;
438        let stop = as_timestamp_nanosecond_array(&stop)?;
439
440        let start_tz = parse_tz(start.timezone())?;
441        let stop_tz = parse_tz(stop.timezone())?;
442
443        // values are timestamps
444        let values_builder = start
445            .timezone()
446            .map_or_else(TimestampNanosecondBuilder::new, |start_tz_str| {
447                TimestampNanosecondBuilder::new().with_timezone(start_tz_str)
448            });
449        let mut list_builder = ListBuilder::new(values_builder);
450
451        for idx in 0..start.len() {
452            if start.is_null(idx) || stop.is_null(idx) || step.is_null(idx) {
453                list_builder.append_null();
454                continue;
455            }
456
457            let start = start.value(idx);
458            let stop = stop.value(idx);
459            let step = step.value(idx);
460
461            let (months, days, ns) = IntervalMonthDayNanoType::to_parts(step);
462            if months == 0 && days == 0 && ns == 0 {
463                return exec_err!("Interval argument to {} must not be 0", self.name());
464            }
465            let neg = interval_step_is_negative(self.name(), months, days, ns)?;
466
467            let stop_dt =
468                as_datetime_with_timezone::<TimestampNanosecondType>(stop, stop_tz)
469                    .ok_or_else(|| {
470                        exec_datafusion_err!(
471                            "Cannot generate timestamp for stop: {}: {:?}",
472                            stop,
473                            stop_tz
474                        )
475                    })?;
476
477            let mut current = start;
478            let mut current_dt =
479                as_datetime_with_timezone::<TimestampNanosecondType>(current, start_tz)
480                    .ok_or_else(|| {
481                    exec_datafusion_err!(
482                        "Cannot generate timestamp for start: {}: {:?}",
483                        current,
484                        start_tz
485                    )
486                })?;
487
488            let values = from_fn(|| {
489                let generate_series_should_end = self.include_upper_bound
490                    && ((neg && current_dt < stop_dt) || (!neg && current_dt > stop_dt));
491                let range_should_end = !self.include_upper_bound
492                    && ((neg && current_dt <= stop_dt)
493                        || (!neg && current_dt >= stop_dt));
494                if generate_series_should_end || range_should_end {
495                    return None;
496                }
497
498                let prev_current = current;
499
500                if let Some(ts) =
501                    TimestampNanosecondType::add_month_day_nano(current, step, start_tz)
502                {
503                    current = ts;
504                    current_dt = as_datetime_with_timezone::<TimestampNanosecondType>(
505                        current, start_tz,
506                    )?;
507
508                    Some(Some(prev_current))
509                } else {
510                    // we failed to parse the timestamp here so terminate the series
511                    None
512                }
513            });
514
515            list_builder.append_value(values);
516        }
517
518        let arr = Arc::new(list_builder.finish());
519
520        Ok(arr)
521    }
522}
523
524/// Get the (start, stop, step) args for the range and generate_series function.
525/// If any of the arguments is NULL, returns None.
526fn retrieve_range_args(
527    start_array: Option<&Int64Array>,
528    stop: Option<i64>,
529    step_array: Option<&Int64Array>,
530    idx: usize,
531) -> Option<(i64, i64, i64)> {
532    // Default start value is 0 if not provided
533    let start =
534        start_array.map_or(Some(0), |arr| arr.is_valid(idx).then(|| arr.value(idx)))?;
535    let stop = stop?;
536    // Default step value is 1 if not provided
537    let step =
538        step_array.map_or(Some(1), |arr| arr.is_valid(idx).then(|| arr.value(idx)))?;
539    Some((start, stop, step))
540}
541
542/// Reserve space for `count` more elements, returning an error when the
543/// allocation would overflow `Vec`'s capacity limit or the allocator
544/// rejects it, rather than panicking on user-supplied SQL.
545fn reserve_range_capacity(values: &mut Vec<i64>, count: u64) -> Result<()> {
546    let count_usize = usize::try_from(count).map_err(|_| {
547        exec_datafusion_err!(
548            "Range too large to materialize: would produce {count} elements"
549        )
550    })?;
551    values.try_reserve(count_usize).map_err(|e| {
552        exec_datafusion_err!(
553            "Range too large to materialize: failed to allocate {count} elements: {e}"
554        )
555    })
556}
557
558/// Generate integer range values directly into the provided buffer.
559#[inline]
560fn generate_range_values(
561    start: i64,
562    stop: i64,
563    step: i64,
564    include_upper: bool,
565    values: &mut Vec<i64>,
566) -> Result<()> {
567    if !include_upper && start == stop {
568        return Ok(());
569    }
570
571    if step > 0 {
572        let limit = if include_upper {
573            stop
574        } else {
575            stop.saturating_sub(1)
576        };
577        if start > limit {
578            return Ok(());
579        }
580        let count = (start.abs_diff(limit) / step.unsigned_abs()).saturating_add(1);
581        reserve_range_capacity(values, count)?;
582        let mut current = start;
583        while current <= limit {
584            values.push(current);
585            match current.checked_add(step) {
586                Some(next) => current = next,
587                None => break,
588            }
589        }
590    } else if step < 0 {
591        let limit = if include_upper {
592            stop
593        } else {
594            stop.saturating_add(1)
595        };
596        if start < limit {
597            return Ok(());
598        }
599        let count = (start.abs_diff(limit) / step.unsigned_abs()).saturating_add(1);
600        reserve_range_capacity(values, count)?;
601        let mut current = start;
602        while current >= limit {
603            values.push(current);
604            match current.checked_add(step) {
605                Some(next) => current = next,
606                None => break,
607            }
608        }
609    }
610    Ok(())
611}
612
613fn parse_tz(tz: Option<&str>) -> Result<Tz> {
614    let tz = tz.unwrap_or("+00");
615
616    Tz::from_str(tz)
617        .map_err(|op| exec_datafusion_err!("failed to parse timezone {tz}: {:?}", op))
618}
619
620fn date32_to_string(value: i32) -> String {
621    if let Some(d) = Date32Type::to_naive_date_opt(value) {
622        format!("{value} ({d})")
623    } else {
624        format!("{value} (unknown date)")
625    }
626}