Skip to main content

quack_rs/datetime/
checks.rs

1// SPDX-License-Identifier: MIT
2// Copyright 2026 Tom F. <https://github.com/tomtom215/>
3// My way of giving something small back to the open source community
4// and encouraging more Rust development!
5
6//! Pure-Rust mirrors of the checks `DuckDB` makes before it throws.
7//!
8//! Several of the C API conversions call `DuckDB` routines that throw a C++
9//! `ConversionException` on bad input, with no `try`/`catch` in the C API
10//! wrapper. A C++ exception that reaches Rust aborts the process, so the
11//! wrappers in [`super`] run these checks first and return `None` instead.
12//! Each one mirrors the `DuckDB` 1.5 source it cites exactly, so a value that
13//! passes is one `DuckDB` accepts.
14
15use super::{Date, Time, TIMESTAMP_INFINITY_MICROS, TIMESTAMP_NEGATIVE_INFINITY_MICROS};
16
17/// Microseconds in a day (`Interval::MICROS_PER_DAY`).
18pub const MICROS_PER_DAY: i64 = 86_400_000_000;
19
20/// The largest `TIME WITH TIME ZONE` offset `DuckDB` can encode, in seconds:
21/// `+15:59:59` (`dtime_tz_t::MAX_OFFSET = 16 * 60 * 60 - 1`). The smallest is
22/// its negation.
23pub const TIME_TZ_MAX_OFFSET_SECONDS: i32 = 16 * 60 * 60 - 1;
24
25/// The widest `DECIMAL` `DuckDB` supports (`Decimal::MAX_WIDTH_INT128`).
26pub const DECIMAL_MAX_WIDTH: u8 = 38;
27
28// `Date::DATE_MIN_*` / `DATE_MAX_*` in `duckdb/common/types/date.hpp`: the
29// earliest date is 5877642-06-25 BC (year -5877641) and the latest is
30// 5881580-07-10, days -(2^31 - 2) and 2^31 - 2.
31const DATE_MIN: (i32, i32, i32) = (-5_877_641, 6, 25);
32const DATE_MAX: (i32, i32, i32) = (5_881_580, 7, 10);
33
34/// `Date::NORMAL_DAYS` / `Date::LEAP_DAYS`, indexed by month (1–12).
35const NORMAL_DAYS: [i32; 13] = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
36const LEAP_DAYS: [i32; 13] = [0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
37
38/// `Date::IsLeapYear`: the proleptic Gregorian rule.
39const fn is_leap_year(year: i32) -> bool {
40    year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)
41}
42
43/// Returns `true` if `DuckDB` can represent `date` as a `DATE`.
44///
45/// This is `DuckDB`'s own `Date::IsValid`: the month is 1–12, the day exists in
46/// that month of that (proleptic Gregorian) year, and the date lies between
47/// 5877642-06-25 BC and 5881580-07-10. [`date_to_days`][super::date_to_days]
48/// returns `None` exactly when this returns `false`.
49#[must_use]
50pub const fn is_valid_date(date: Date) -> bool {
51    let (year, month, day) = (date.year, date.month as i32, date.day as i32);
52    if month < 1 || month > 12 || day < 1 {
53        return false;
54    }
55    if year < DATE_MIN.0
56        || (year == DATE_MIN.0 && (month < DATE_MIN.1 || (month == DATE_MIN.1 && day < DATE_MIN.2)))
57    {
58        return false;
59    }
60    if year > DATE_MAX.0
61        || (year == DATE_MAX.0 && (month > DATE_MAX.1 || (month == DATE_MAX.1 && day > DATE_MAX.2)))
62    {
63        return false;
64    }
65    #[allow(clippy::cast_sign_loss, reason = "month is 1..=12 here")]
66    let month = month as usize;
67    if is_leap_year(year) {
68        day <= LEAP_DAYS[month]
69    } else {
70        day <= NORMAL_DAYS[month]
71    }
72}
73
74/// `Time::FromTime`: the time of day in microseconds, with no range check.
75///
76/// `DuckDB` accepts any field values here (it never throws), so this does too;
77/// with `i8` / `i32` fields the arithmetic cannot overflow an `i64`.
78pub(super) const fn time_micros(time: Time) -> i64 {
79    let mut micros = time.hour as i64;
80    micros = micros * 60 + time.min as i64;
81    micros = micros * 60 + time.sec as i64;
82    micros * 1_000_000 + time.micros as i64
83}
84
85/// Returns `true` if `Time::Convert` accepts `micros`: `DuckDB`'s `TIME` range,
86/// `00:00:00`–`24:00:00` inclusive.
87///
88/// `Time::Convert` does no range check, but it ends in
89/// `D_ASSERT(Time::IsValidTime(..))`, which a `DuckDB` built with assertions
90/// (a debug build) turns into a process abort for every other value.
91pub(super) const fn time_decomposes(micros: i64) -> bool {
92    micros >= 0 && micros <= MICROS_PER_DAY
93}
94
95/// The day `Timestamp::GetDate` assigns a finite timestamp to (floor division).
96const fn timestamp_days(micros: i64) -> i64 {
97    let negative = (micros < 0) as i64;
98    (micros + negative) / MICROS_PER_DAY - negative
99}
100
101/// Returns `true` if `Timestamp::Convert` decomposes `micros` without throwing.
102///
103/// It throws for the two infinity sentinels (whose day, `±i32::MAX`, times
104/// [`MICROS_PER_DAY`] overflows) and for every finite value below
105/// `-106_751_991 * MICROS_PER_DAY` — the first ~4 hours of the `i64` range,
106/// down to `i64::MIN` — whose floor-divided day likewise overflows when
107/// multiplied back.
108pub(super) const fn timestamp_decomposes(micros: i64) -> bool {
109    micros != TIMESTAMP_INFINITY_MICROS
110        && micros != TIMESTAMP_NEGATIVE_INFINITY_MICROS
111        && timestamp_days(micros).checked_mul(MICROS_PER_DAY).is_some()
112}
113
114/// `Timestamp::TryFromDatetime`: `days * MICROS_PER_DAY + time_micros`,
115/// or `None` where `DuckDB`'s `FromDatetime` would throw — on overflow, or when
116/// the result is one of the infinity sentinels.
117pub(super) const fn timestamp_from_parts(days: i32, time_micros: i64) -> Option<i64> {
118    let Some(day_micros) = (days as i64).checked_mul(MICROS_PER_DAY) else {
119        return None;
120    };
121    let Some(micros) = day_micros.checked_add(time_micros) else {
122        return None;
123    };
124    if micros == TIMESTAMP_INFINITY_MICROS || micros == TIMESTAMP_NEGATIVE_INFINITY_MICROS {
125        return None;
126    }
127    Some(micros)
128}
129
130/// Returns `true` if `dtime_tz_t` can encode this time and offset.
131///
132/// `duckdb_create_time_tz` never throws, but it packs the time into the high
133/// 40 bits and `MAX_OFFSET - offset` into the low 24 with no checks: an
134/// offset beyond ±[`TIME_TZ_MAX_OFFSET_SECONDS`] or a negative time corrupts
135/// the other field. `DuckDB`'s own `TIME` range is `00:00:00`–`24:00:00`.
136pub(super) const fn time_tz_encodable(micros: i64, offset_seconds: i32) -> bool {
137    time_decomposes(micros)
138        && offset_seconds >= -TIME_TZ_MAX_OFFSET_SECONDS
139        && offset_seconds <= TIME_TZ_MAX_OFFSET_SECONDS
140}
141
142/// Returns `true` if `duckdb_decimal_to_double` can convert this width and
143/// scale: it indexes `NumericHelper::DOUBLE_POWERS_OF_TEN` (40 entries) and
144/// `Hugeint::POWERS_OF_TEN` (39) by `scale` with no bounds check. This is the
145/// same rule `duckdb_double_to_decimal` enforces in the other direction.
146pub(super) const fn decimal_is_valid(width: u8, scale: u8) -> bool {
147    // DECIMAL(0, 0) is not a type: `LogicalType::try_decimal` and
148    // `validate_decimal` refuse width 0 too.
149    width >= 1 && width <= DECIMAL_MAX_WIDTH && scale <= width
150}
151
152#[cfg(test)]
153mod tests {
154    use super::*;
155
156    const fn date(year: i32, month: i8, day: i8) -> Date {
157        Date { year, month, day }
158    }
159
160    #[test]
161    fn months_and_days_out_of_range_are_invalid() {
162        assert!(is_valid_date(date(2026, 1, 31)));
163        assert!(!is_valid_date(date(2026, 13, 1)));
164        assert!(!is_valid_date(date(2026, 0, 1)));
165        assert!(!is_valid_date(date(2026, -1, 1)));
166        assert!(!is_valid_date(date(2026, 4, 31)));
167        assert!(!is_valid_date(date(2026, 1, 0)));
168        assert!(!is_valid_date(date(2026, 1, 32)));
169        assert!(!is_valid_date(date(2026, 1, -5)));
170        // The inclusive ends of each field range: December and the 1st exist.
171        assert!(is_valid_date(date(2026, 12, 1)));
172        assert!(is_valid_date(date(2026, 12, 31)));
173        assert!(is_valid_date(date(2026, 1, 1)));
174    }
175
176    #[test]
177    fn february_follows_the_gregorian_leap_rule() {
178        assert!(is_valid_date(date(2024, 2, 29)));
179        assert!(!is_valid_date(date(2026, 2, 29)));
180        assert!(is_valid_date(date(2000, 2, 29)));
181        assert!(!is_valid_date(date(1900, 2, 29)));
182        // Proleptic and BCE years follow the same rule.
183        assert!(is_valid_date(date(-400, 2, 29)));
184        assert!(!is_valid_date(date(-100, 2, 29)));
185    }
186
187    #[test]
188    fn the_representable_range_ends_exactly_where_duckdb_says() {
189        assert!(is_valid_date(date(-5_877_641, 6, 25)));
190        assert!(!is_valid_date(date(-5_877_641, 6, 24)));
191        assert!(!is_valid_date(date(-5_877_641, 5, 30)));
192        assert!(!is_valid_date(date(-5_877_642, 12, 31)));
193        assert!(!is_valid_date(date(i32::MIN, 1, 1)));
194        assert!(is_valid_date(date(5_881_580, 7, 10)));
195        assert!(!is_valid_date(date(5_881_580, 7, 11)));
196        assert!(!is_valid_date(date(5_881_580, 8, 1)));
197        assert!(!is_valid_date(date(5_881_581, 1, 1)));
198        assert!(!is_valid_date(date(i32::MAX, 1, 1)));
199    }
200
201    #[test]
202    fn timestamp_days_floors_toward_negative_infinity() {
203        assert_eq!(timestamp_days(0), 0);
204        assert_eq!(timestamp_days(1), 0);
205        assert_eq!(timestamp_days(MICROS_PER_DAY - 1), 0);
206        assert_eq!(timestamp_days(MICROS_PER_DAY), 1);
207        assert_eq!(timestamp_days(-1), -1);
208        assert_eq!(timestamp_days(-MICROS_PER_DAY), -1);
209        assert_eq!(timestamp_days(-MICROS_PER_DAY - 1), -2);
210    }
211
212    #[test]
213    fn timestamps_that_duckdb_cannot_decompose_are_caught() {
214        assert!(timestamp_decomposes(0));
215        assert!(timestamp_decomposes(-1));
216        assert!(timestamp_decomposes(i64::MAX - 1));
217        // The earliest instant whose day survives the multiply-back; one
218        // microsecond earlier (and everything down to `i64::MIN`, ~4 hours of
219        // the range) floors to a day whose micros overflow.
220        assert!(timestamp_decomposes(-106_751_991 * MICROS_PER_DAY));
221        assert!(!timestamp_decomposes(-106_751_991 * MICROS_PER_DAY - 1));
222        assert!(!timestamp_decomposes(-i64::MAX + 1));
223        assert!(!timestamp_decomposes(TIMESTAMP_INFINITY_MICROS));
224        assert!(!timestamp_decomposes(TIMESTAMP_NEGATIVE_INFINITY_MICROS));
225        // Finite, but its floor-divided day overflows when multiplied back.
226        assert!(!timestamp_decomposes(i64::MIN));
227    }
228
229    #[test]
230    fn timestamp_composition_rejects_overflow_and_the_sentinels() {
231        assert_eq!(timestamp_from_parts(1, 5), Some(MICROS_PER_DAY + 5));
232        assert_eq!(timestamp_from_parts(-1, 0), Some(-MICROS_PER_DAY));
233        assert_eq!(timestamp_from_parts(i32::MAX, 0), None);
234        assert_eq!(timestamp_from_parts(i32::MIN, 0), None);
235        // The last day that fits, pushed over the edge by its time.
236        let last_day = i32::try_from(i64::MAX / MICROS_PER_DAY).unwrap();
237        assert!(timestamp_from_parts(last_day, 0).is_some());
238        assert_eq!(
239            timestamp_from_parts(last_day, i64::MAX % MICROS_PER_DAY + 1),
240            None
241        );
242        // Landing exactly on infinity is refused too.
243        assert_eq!(
244            timestamp_from_parts(last_day, i64::MAX % MICROS_PER_DAY),
245            None
246        );
247    }
248
249    #[test]
250    fn time_micros_matches_duckdb_from_time() {
251        let t = Time {
252            hour: 23,
253            min: 59,
254            sec: 59,
255            micros: 999_999,
256        };
257        assert_eq!(time_micros(t), MICROS_PER_DAY - 1);
258    }
259
260    /// `Time::Convert` followed by `Time::IsValidTime`, transcribed from
261    /// `DuckDB` v1.5.5 (`src/common/types/time.cpp`). C++ integer division
262    /// truncates toward zero, as Rust's does.
263    fn duckdb_convert_is_valid(micros: i64) -> bool {
264        let mut time = micros;
265        let hour = time / 3_600_000_000;
266        time -= hour * 3_600_000_000;
267        let min = time / 60_000_000;
268        time -= min * 60_000_000;
269        let sec = time / 1_000_000;
270        time -= sec * 1_000_000;
271        let micros = time;
272        if !(0..24).contains(&hour) {
273            return hour == 24 && min == 0 && sec == 0 && micros == 0;
274        }
275        (0..60).contains(&min) && (0..=60).contains(&sec) && (0..=1_000_000).contains(&micros)
276    }
277
278    #[test]
279    fn time_decomposes_is_exactly_what_duckdb_asserts() {
280        let mut probes = vec![i64::MIN, i64::MIN + 1, i64::MAX, i64::MAX - 1];
281        for edge in [0, MICROS_PER_DAY, 3_600_000_000, 60_000_000, 1_000_000] {
282            for delta in -2..=2 {
283                probes.push(edge + delta);
284                probes.push(-edge + delta);
285            }
286        }
287        // Every hour boundary of the day and the one after it.
288        for hour in -1..=26 {
289            probes.push(hour * 3_600_000_000);
290            probes.push(hour * 3_600_000_000 - 1);
291        }
292        for micros in probes {
293            assert_eq!(
294                time_decomposes(micros),
295                duckdb_convert_is_valid(micros),
296                "{micros}"
297            );
298        }
299        assert!(time_decomposes(0));
300        assert!(time_decomposes(MICROS_PER_DAY));
301        assert!(!time_decomposes(-1));
302        assert!(!time_decomposes(MICROS_PER_DAY + 1));
303    }
304
305    #[test]
306    fn time_tz_max_offset_is_duckdbs_plus_15_59_59() {
307        // `dtime_tz_t::MAX_OFFSET` in DuckDB 1.5: 15h 59m 59s, in seconds.
308        assert_eq!(TIME_TZ_MAX_OFFSET_SECONDS, 57_599);
309        assert_eq!(TIME_TZ_MAX_OFFSET_SECONDS, 15 * 3_600 + 59 * 60 + 59);
310    }
311
312    #[test]
313    fn time_tz_bounds() {
314        assert!(time_tz_encodable(0, 0));
315        assert!(time_tz_encodable(
316            MICROS_PER_DAY,
317            TIME_TZ_MAX_OFFSET_SECONDS
318        ));
319        assert!(time_tz_encodable(0, -TIME_TZ_MAX_OFFSET_SECONDS));
320        assert!(!time_tz_encodable(0, TIME_TZ_MAX_OFFSET_SECONDS + 1));
321        assert!(!time_tz_encodable(0, -TIME_TZ_MAX_OFFSET_SECONDS - 1));
322        assert!(!time_tz_encodable(-1, 0));
323        assert!(!time_tz_encodable(MICROS_PER_DAY + 1, 0));
324    }
325
326    #[test]
327    fn decimal_bounds() {
328        assert!(decimal_is_valid(38, 38));
329        assert!(decimal_is_valid(18, 3));
330        assert!(!decimal_is_valid(39, 0));
331        assert!(!decimal_is_valid(10, 11));
332        assert!(!decimal_is_valid(38, 40));
333        assert!(!decimal_is_valid(0, 0));
334        assert!(decimal_is_valid(1, 0));
335    }
336}