Skip to content

Commit 05f5458

Browse files
authored
feat(pg-functions): add justify_hours, justify_days and justify_interval (#435)
Implement the PostgreSQL interval justification functions in the datetime category, ported from interval_justify_{hours,days,interval} in PostgreSQL's timestamp.c. - Accept Interval(MonthDayNano), Interval(DayTime) and Interval(YearMonth) and always return Interval(MonthDayNano). - Raise "interval out of range" on month/day overflow, as PostgreSQL does. - Keep Arrow's nanosecond precision and justify it exactly. - Register the UDFs under the `datetime` feature, mark them implemented in functions.md, and add datetime.slt (`datetime` is now a required feature of the sqllogictest target). Refs #434
1 parent 4776015 commit 05f5458

8 files changed

Lines changed: 1579 additions & 11 deletions

File tree

‎datafusion-pg-functions/Cargo.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -107,4 +107,4 @@ tokio = { workspace = true, features = ["macros", "rt", "fs"] }
107107
[[test]]
108108
name = "sqllogictest"
109109
path = "tests/sqllogictest.rs"
110-
required-features = ["math", "string"]
110+
required-features = ["math", "string", "datetime"]

‎datafusion-pg-functions/functions.md‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ implementation strategy in DataFusion.
6565
| [Bit String](#functions-bitstring) | 9 | 6 | 0 | 0 | 0 | 0 | 0+3 | 3 |
6666
| [Pattern Matching](#functions-matching) | 15 | 7 | 2 | 0 | 2 | 0 | 3+2 | 0 |
6767
| [Data Type Formatting](#functions-formatting) | 10 | 3 | 0 | 0 | 7 | 0 | 0+0 | 0 |
68-
| [Date/Time](#functions-datetime) | 33 | 11 | 0 | 0 | 21 | 0 | 0+1 | 0 |
68+
| [Date/Time](#functions-datetime) | 33 | 11 | 3 | 0 | 18 | 0 | 0+1 | 0 |
6969
| [Enum Support](#functions-enum) | 3 | 0 | 0 | 0 | 0 | 0 | 0+0 | 3 |
7070
| [Geometric](#functions-geometry) | 23 | 1 | 0 | 0 | 0 | 0 | 0+0 | 22 |
7171
| [Network Address](#functions-net) | 14 | 1 | 0 | 0 | 0 | 0 | 0+0 | 13 |
@@ -85,7 +85,7 @@ implementation strategy in DataFusion.
8585
| [System Administration](#functions-admin) | 105 | 0 | 2 | 0 | 5 | 0 | 0+0 | 98 |
8686
| [Trigger](#functions-trigger) | 3 | 0 | 0 | 0 | 0 | 0 | 0+0 | 3 |
8787
| [Event Trigger](#functions-event-triggers) | 5 | 0 | 0 | 0 | 0 | 0 | 0+0 | 5 |
88-
| **TOTAL** | **768** | **198** | **54** | **4** | **71** | **65** | **21** | **371** |
88+
| **TOTAL** | **768** | **198** | **57** | **4** | **68** | **65** | **21** | **371** |
8989

9090
---
9191

@@ -386,9 +386,9 @@ implementation strategy in DataFusion.
386386
| `date_trunc` | fn | ✅ | — | 4 | truncate timestamp with time zone to specified units in specified time zone | Native DataFusion |
387387
| `extract` | both | 🚧 | P2 | 6 | extract field from timestamp with time zone | |
388388
| `isfinite` | fn | 🚧 | P2 | 4 | finite timestamp? | |
389-
| `justify_days` | fn | 🚧 | P2 | 1 | promote groups of 30 days to numbers of months | |
390-
| `justify_hours` | fn | 🚧 | P2 | 1 | promote groups of 24 hours to numbers of days | |
391-
| `justify_interval` | fn | 🚧 | P2 | 1 | promote groups of 24 hours to numbers of days and promote groups of 30 days to numbers of months | |
389+
| `justify_days` | fn | 🔧 | — | 1 | promote groups of 30 days to numbers of months | Accepts any Arrow interval unit; returns `Interval(MonthDayNano)`. Time field passed through unchanged. |
390+
| `justify_hours` | fn | 🔧 | — | 1 | promote groups of 24 hours to numbers of days | Accepts any Arrow interval unit; returns `Interval(MonthDayNano)`. Keeps sub-microsecond nanoseconds (PG stores microseconds). |
391+
| `justify_interval` | fn | 🔧 | — | 1 | promote groups of 24 hours to numbers of days and promote groups of 30 days to numbers of months | Accepts any Arrow interval unit; returns `Interval(MonthDayNano)`. Keeps sub-microsecond nanoseconds (PG stores microseconds). |
392392
| `localtime` | fn | 🚧 | P2 | 0 | Current date and time, no time zone | |
393393
| `localtimestamp` | fn | 🚧 | P2 | 0 | Current timestamp, no time zone | |
394394
| `make_date` | fn | ✅ | — | 1 | construct date | Native DataFusion |
Lines changed: 29 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,41 @@
1-
//! datetime functions.
1+
//! PostgreSQL date/time functions.
2+
//!
3+
//! This module hosts the UDFs listed in the "Date/Time Functions and
4+
//! Operators" section of [`functions.md`](../functions.md), one file per
5+
//! function:
6+
//!
7+
//! - [`justify_days`] — promote 30-day periods of an interval to months.
8+
//! - [`justify_hours`] — promote 24-hour periods of an interval to days.
9+
//! - [`justify_interval`] — normalize days and time, with sign adjustment.
10+
//!
11+
//! Shared interval input handling lives in the private `interval` module.
212
//!
313
//! See the corresponding section of `functions.md` for the catalog of
414
//! PostgreSQL built-ins in this category and their implementation status.
515
616
use datafusion::execution::FunctionRegistry;
717
use datafusion::logical_expr::ScalarUDF;
818

19+
mod interval;
20+
pub mod justify_days;
21+
pub mod justify_hours;
22+
pub mod justify_interval;
23+
924
/// Register every PostgreSQL built-in UDF in the datetime category against
1025
/// `registry`.
1126
///
1227
/// Returns the number of UDFs that were registered.
13-
pub fn register(_registry: &mut dyn FunctionRegistry) -> usize {
14-
let _udfs: Vec<ScalarUDF> = vec![];
15-
// registry.register_udf(...);
16-
0
28+
pub fn register(registry: &mut dyn FunctionRegistry) -> usize {
29+
let udfs: Vec<ScalarUDF> = vec![
30+
justify_days::create_justify_days_udf(),
31+
justify_hours::create_justify_hours_udf(),
32+
justify_interval::create_justify_interval_udf(),
33+
];
34+
35+
let mut count = 0;
36+
for udf in udfs {
37+
let _ = registry.register_udf(udf.into());
38+
count += 1;
39+
}
40+
count
1741
}
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
//! Shared helpers for the PostgreSQL `interval` UDFs in this module.
2+
//!
3+
//! PostgreSQL has a single `interval` type made of a month, a day and a time
4+
//! field. Arrow has three interval units; these helpers accept all of them,
5+
//! convert each value losslessly to `(months, days, nanoseconds)`, and always
6+
//! produce `Interval(MonthDayNano)`, matching PostgreSQL's one result type.
7+
8+
use std::sync::Arc;
9+
10+
use datafusion::arrow::array::{Array, ArrayRef, AsArray, PrimitiveBuilder, new_null_array};
11+
use datafusion::arrow::datatypes::{
12+
DataType, IntervalDayTimeType, IntervalMonthDayNano, IntervalMonthDayNanoType, IntervalUnit,
13+
IntervalYearMonthType,
14+
};
15+
use datafusion::common::{Result, exec_err};
16+
use datafusion::logical_expr::{Signature, TypeSignature, Volatility};
17+
18+
/// Nanoseconds in one 24-hour day (PostgreSQL `USECS_PER_DAY`, in nanoseconds).
19+
pub(crate) const NANOS_PER_DAY: i64 = 86_400 * 1_000_000_000;
20+
21+
/// Days in one month, as assumed by PostgreSQL (`DAYS_PER_MONTH`).
22+
pub(crate) const DAYS_PER_MONTH: i32 = 30;
23+
24+
/// Nanoseconds in one millisecond, for `Interval(DayTime)` input.
25+
const NANOS_PER_MILLI: i64 = 1_000_000;
26+
27+
/// The error PostgreSQL raises when an interval field overflows.
28+
pub(crate) const OUT_OF_RANGE: &str = "interval out of range";
29+
30+
/// Signature for a function taking one interval of any Arrow unit, or a NULL
31+
/// literal.
32+
pub(crate) fn single_interval_signature() -> Signature {
33+
Signature::one_of(
34+
vec![
35+
TypeSignature::Exact(vec![DataType::Interval(IntervalUnit::MonthDayNano)]),
36+
TypeSignature::Exact(vec![DataType::Interval(IntervalUnit::DayTime)]),
37+
TypeSignature::Exact(vec![DataType::Interval(IntervalUnit::YearMonth)]),
38+
TypeSignature::Exact(vec![DataType::Null]),
39+
],
40+
Volatility::Immutable,
41+
)
42+
}
43+
44+
/// Apply `f(months, days, nanoseconds)` to every non-null element of an
45+
/// interval array, producing an `Interval(MonthDayNano)` array. NULLs stay
46+
/// NULL; an error from `f` fails the whole call.
47+
pub(crate) fn map_interval_array<F>(name: &str, input: &ArrayRef, f: F) -> Result<ArrayRef>
48+
where
49+
F: Fn(i32, i32, i64) -> Result<IntervalMonthDayNano>,
50+
{
51+
let len = input.len();
52+
let mut out = PrimitiveBuilder::<IntervalMonthDayNanoType>::with_capacity(len);
53+
match input.data_type() {
54+
DataType::Null => {
55+
return Ok(new_null_array(
56+
&DataType::Interval(IntervalUnit::MonthDayNano),
57+
len,
58+
));
59+
}
60+
DataType::Interval(IntervalUnit::MonthDayNano) => {
61+
for v in input.as_primitive::<IntervalMonthDayNanoType>().iter() {
62+
match v {
63+
Some(v) => out.append_value(f(v.months, v.days, v.nanoseconds)?),
64+
None => out.append_null(),
65+
}
66+
}
67+
}
68+
DataType::Interval(IntervalUnit::DayTime) => {
69+
for v in input.as_primitive::<IntervalDayTimeType>().iter() {
70+
match v {
71+
Some(v) => {
72+
out.append_value(f(0, v.days, v.milliseconds as i64 * NANOS_PER_MILLI)?)
73+
}
74+
None => out.append_null(),
75+
}
76+
}
77+
}
78+
DataType::Interval(IntervalUnit::YearMonth) => {
79+
for v in input.as_primitive::<IntervalYearMonthType>().iter() {
80+
match v {
81+
Some(months) => out.append_value(f(months, 0, 0)?),
82+
None => out.append_null(),
83+
}
84+
}
85+
}
86+
other => return exec_err!("{name} expects an interval argument, got {other:?}"),
87+
}
88+
Ok(Arc::new(out.finish()))
89+
}

0 commit comments

Comments
 (0)