quack_rs/value/temporal.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//! Temporal constructors — `Value::date`, `time`, `timestamp_s`, …
7//!
8//! # Why most of them return `Result`
9//!
10//! `DuckDB`'s `duckdb_create_time`, `_time_tz_value`, `_time_ns`,
11//! `_timestamp`, `_timestamp_tz`, `_timestamp_s`, `_timestamp_ms` and
12//! `_timestamp_ns` store any 64-bit payload without a check. Everything done
13//! with an out-of-range one afterwards goes wrong: rendering it
14//! ([`as_str`][Value::as_str], `Debug`, `display_string`) or casting it runs
15//! `DuckDB` code that throws a C++ exception through the C API (a process
16//! abort from Rust), reads out of bounds (`Value::time_ns(i64::MAX)` crashed
17//! `StringAsTime` with `SIGSEGV`) or prints garbage (`Value::time(-1)` rendered
18//! `00:00:00.00000/`). These constructors accept exactly the range `DuckDB`'s
19//! own SQL produces (see `checks::temporal_in_range`) and return an error for
20//! anything else.
21//!
22//! `DATE` and `INTERVAL` stay infallible: `DuckDB` renders and converts every
23//! `i32` day count and every interval without throwing.
24
25use libduckdb_sys::{
26 duckdb_create_date, duckdb_create_interval, duckdb_create_time, duckdb_create_time_tz_value,
27 duckdb_create_timestamp, duckdb_create_timestamp_ms, duckdb_create_timestamp_ns,
28 duckdb_create_timestamp_s, duckdb_create_timestamp_tz, duckdb_date, duckdb_interval,
29 duckdb_time, duckdb_time_tz, duckdb_timestamp, duckdb_timestamp_ms, duckdb_timestamp_ns,
30 duckdb_timestamp_s,
31};
32#[cfg(feature = "duckdb-1-5")]
33use libduckdb_sys::{duckdb_create_time_ns, duckdb_time_ns};
34
35use super::temporal_checks::{temporal_in_range, time_tz_in_range};
36use super::Value;
37use crate::error::ExtensionError;
38use crate::types::TypeId;
39
40/// The error for an out-of-range payload: names the constructor, the value,
41/// the SQL type and its range.
42fn out_of_range(method: &str, value: impl std::fmt::Display, range: &str) -> ExtensionError {
43 ExtensionError::new(format!(
44 "Value::{method}({value}) is outside DuckDB's range for the type: {range}. DuckDB \
45 would store it unchecked and then fail, crash or print garbage rendering or casting it"
46 ))
47}
48
49/// `Ok(v)` if `v` is in range for `type_id`, else the error for `method`.
50fn check(type_id: TypeId, v: i64, method: &str, range: &str) -> Result<i64, ExtensionError> {
51 if temporal_in_range(type_id, v) {
52 Ok(v)
53 } else {
54 Err(out_of_range(method, v, range))
55 }
56}
57
58/// The range text for the microsecond-based `TIMESTAMP` types: the finite
59/// span `DuckDB` can render and convert, and the two infinities.
60const TIMESTAMP_RANGE: &str = "TIMESTAMP 290309-12-22 (BC) 00:00:00 to \
61 294247-01-10 04:00:54.775806, or ±infinity (±i64::MAX)";
62
63impl Value {
64 /// Creates a `DATE` value from days since 1970-01-01.
65 ///
66 /// Infallible: `DuckDB` renders and converts every `i32`. `i32::MAX` and
67 /// `-i32::MAX` are `infinity` and `-infinity`
68 /// ([`datetime::DATE_INFINITY_DAYS`][crate::datetime::DATE_INFINITY_DAYS]).
69 #[inline]
70 #[must_use]
71 pub fn date(days: i32) -> Self {
72 Self {
73 // SAFETY: a plain by-value struct DuckDB accepts unconditionally;
74 // the returned handle is owned by this `Value`.
75 raw: unsafe { duckdb_create_date(duckdb_date { days }) },
76 }
77 }
78
79 /// Creates a `TIME` value from microseconds since midnight.
80 ///
81 /// # Errors
82 ///
83 /// `micros_since_midnight` is outside `0..=86_400_000_000`
84 /// (`00:00:00`–`24:00:00`, `DuckDB`'s `TIME` range).
85 pub fn time(micros_since_midnight: i64) -> Result<Self, ExtensionError> {
86 let micros = check(
87 TypeId::Time,
88 micros_since_midnight,
89 "time",
90 "TIME 0..=86_400_000_000 microseconds, 00:00:00 to 24:00:00",
91 )?;
92 Ok(Self {
93 // SAFETY: a plain by-value struct, range-checked above; the
94 // returned handle is owned by this `Value`.
95 raw: unsafe { duckdb_create_time(duckdb_time { micros }) },
96 })
97 }
98
99 /// Creates a `TIME WITH TIME ZONE` value from its packed 64-bit encoding.
100 ///
101 /// `DuckDB` packs `TIME_TZ` as 40 bits of microseconds and 24 bits of UTC
102 /// offset. Build the encoding with
103 /// [`time_tz_bits`][crate::datetime::time_tz_bits] rather than assembling it
104 /// by hand; every encoding it returns is accepted here.
105 ///
106 /// # Errors
107 ///
108 /// The time field exceeds `24:00:00` or the offset field encodes an
109 /// offset beyond `±15:59:59`.
110 pub fn time_tz(bits: u64) -> Result<Self, ExtensionError> {
111 if !time_tz_in_range(bits) {
112 return Err(out_of_range(
113 "time_tz",
114 format_args!("{bits:#x}"),
115 "TIMETZ time 00:00:00 to 24:00:00 in the high 40 bits, offset ±15:59:59 in the low 24",
116 ));
117 }
118 Ok(Self {
119 // SAFETY: a plain by-value struct, range-checked above.
120 raw: unsafe { duckdb_create_time_tz_value(duckdb_time_tz { bits }) },
121 })
122 }
123
124 /// Creates a `TIME_NS` value (time of day with nanosecond precision) from a
125 /// raw nanosecond count (`DuckDB` 1.5.0+).
126 ///
127 /// Pairs with [`as_time_ns`][Value::as_time_ns] and the
128 /// [`TypeId::TimeNs`] column type.
129 ///
130 /// # Errors
131 ///
132 /// `nanos` is outside `0..=86_400_000_000_000` (`00:00:00`–`24:00:00`).
133 #[cfg(feature = "duckdb-1-5")]
134 pub fn time_ns(nanos: i64) -> Result<Self, ExtensionError> {
135 let nanos = check(
136 TypeId::TimeNs,
137 nanos,
138 "time_ns",
139 "TIME_NS 0..=86_400_000_000_000 nanoseconds, 00:00:00 to 24:00:00",
140 )?;
141 // SAFETY: a plain by-value struct, range-checked above.
142 let raw = unsafe { duckdb_create_time_ns(duckdb_time_ns { nanos }) };
143 Ok(Self { raw })
144 }
145
146 /// Creates a `TIMESTAMP` value from microseconds since the epoch.
147 ///
148 /// # Errors
149 ///
150 /// `micros` is below `-9_223_372_022_400_000_000`
151 /// (`290309-12-22 (BC) 00:00:00`) and is not `-i64::MAX` (`-infinity`).
152 /// Every larger value is valid; `i64::MAX` is `infinity`.
153 pub fn timestamp(micros: i64) -> Result<Self, ExtensionError> {
154 let micros = check(TypeId::Timestamp, micros, "timestamp", TIMESTAMP_RANGE)?;
155 Ok(Self {
156 // SAFETY: a plain by-value struct, range-checked above.
157 raw: unsafe { duckdb_create_timestamp(duckdb_timestamp { micros }) },
158 })
159 }
160
161 /// Creates a `TIMESTAMP WITH TIME ZONE` value from microseconds since the
162 /// epoch.
163 ///
164 /// # Errors
165 ///
166 /// As [`timestamp`][Self::timestamp].
167 pub fn timestamp_tz(micros: i64) -> Result<Self, ExtensionError> {
168 let micros = check(TypeId::TimestampTz, micros, "timestamp_tz", TIMESTAMP_RANGE)?;
169 Ok(Self {
170 // SAFETY: a plain by-value struct, range-checked above.
171 raw: unsafe { duckdb_create_timestamp_tz(duckdb_timestamp { micros }) },
172 })
173 }
174
175 /// Creates a `TIMESTAMP_S` value from seconds since the epoch.
176 ///
177 /// # Errors
178 ///
179 /// `seconds` is outside `-9_223_372_022_400..=9_223_372_036_854` and is
180 /// not `±i64::MAX` (`±infinity`): `DuckDB` converts a `TIMESTAMP_S` to
181 /// microseconds to render or cast it, and throws when that overflows.
182 pub fn timestamp_s(seconds: i64) -> Result<Self, ExtensionError> {
183 let seconds = check(TypeId::TimestampS, seconds, "timestamp_s", TIMESTAMP_RANGE)?;
184 // SAFETY: a plain by-value struct, range-checked above.
185 let raw = unsafe { duckdb_create_timestamp_s(duckdb_timestamp_s { seconds }) };
186 Ok(Self { raw })
187 }
188
189 /// Creates a `TIMESTAMP_MS` value from milliseconds since the epoch.
190 ///
191 /// # Errors
192 ///
193 /// `millis` is outside
194 /// `-9_223_372_022_400_000..=9_223_372_036_854_775` and is not
195 /// `±i64::MAX` (`±infinity`), for the reason given on
196 /// [`timestamp_s`][Self::timestamp_s].
197 pub fn timestamp_ms(millis: i64) -> Result<Self, ExtensionError> {
198 let millis = check(TypeId::TimestampMs, millis, "timestamp_ms", TIMESTAMP_RANGE)?;
199 // SAFETY: a plain by-value struct, range-checked above.
200 let raw = unsafe { duckdb_create_timestamp_ms(duckdb_timestamp_ms { millis }) };
201 Ok(Self { raw })
202 }
203
204 /// Creates a `TIMESTAMP_NS` value from nanoseconds since the epoch.
205 ///
206 /// # Errors
207 ///
208 /// `nanos` is below `-9_223_286_400_000_000_000` (`1677-09-22 00:00:00`)
209 /// and is not `-i64::MAX` (`-infinity`). Every larger value is valid;
210 /// `i64::MAX` is `infinity`.
211 pub fn timestamp_ns(nanos: i64) -> Result<Self, ExtensionError> {
212 let nanos = check(
213 TypeId::TimestampNs,
214 nanos,
215 "timestamp_ns",
216 "TIMESTAMP_NS 1677-09-22 00:00:00 to 2262-04-11 23:47:16.854775806, or ±infinity (±i64::MAX)",
217 )?;
218 // SAFETY: a plain by-value struct, range-checked above.
219 let raw = unsafe { duckdb_create_timestamp_ns(duckdb_timestamp_ns { nanos }) };
220 Ok(Self { raw })
221 }
222
223 /// Creates a `TIMESTAMPTZ_NS` value (a timestamp with time zone at
224 /// nanosecond precision) from nanoseconds since the epoch (`DuckDB`
225 /// 2.0.0+).
226 ///
227 /// Pairs with [`as_timestamp_tz_ns`][Value::as_timestamp_tz_ns] and the
228 /// [`TypeId::TimestampTzNs`] column type.
229 ///
230 /// `DuckDB` 2.0.0 added `duckdb_create_timestamp_tz_ns` for this, but the
231 /// function sits in the two slots 2.0.0 appended to the C API struct, past
232 /// the 546 an extension built against the 1.5.2 - 1.5.6 bindings (and
233 /// every engine before 2.0.0) has. So this does not call it. It renders the
234 /// `TIMESTAMP_NS` for `nanos` as text and casts the text to
235 /// `TIMESTAMPTZ_NS`, which works on any bindings; no cast reaches
236 /// `TIMESTAMPTZ_NS` from `TIMESTAMP_NS` directly in `DuckDB`'s default
237 /// cast set (`DefaultCasts::TimestampNsCastSwitch`), and the text form
238 /// carries all nine fractional digits.
239 ///
240 /// # Errors
241 ///
242 /// - `nanos` is below `-9_223_286_400_000_000_000` (`1677-09-22
243 /// 00:00:00`) and is not `-i64::MAX` (`-infinity`), as for
244 /// [`timestamp_ns`][Self::timestamp_ns]. Every larger value is valid;
245 /// `i64::MAX` is `infinity`.
246 /// - The engine is older than 2.0.0 and has no `TIMESTAMPTZ_NS` type.
247 pub fn timestamp_tz_ns(nanos: i64) -> Result<Self, ExtensionError> {
248 let nanos = check(
249 TypeId::TimestampTzNs,
250 nanos,
251 "timestamp_tz_ns",
252 "TIMESTAMPTZ_NS 1677-09-22 00:00:00 to 2262-04-11 23:47:16.854775806, or ±infinity (±i64::MAX)",
253 )?;
254 let text = utc_text(Self::timestamp_ns(nanos)?.as_str()?, nanos);
255 Self::varchar(&text)
256 .cast_copy(TypeId::TimestampTzNs)
257 .ok_or_else(|| {
258 ExtensionError::new(
259 "Value::timestamp_tz_ns: this DuckDB has no TIMESTAMPTZ_NS type \
260 (it was added in DuckDB 2.0.0)",
261 )
262 })
263 }
264
265 /// Creates an `INTERVAL` value.
266 ///
267 /// `DuckDB` intervals are `{ months, days, micros }` and deliberately do not
268 /// collapse into a single duration — see
269 /// [`DuckInterval`][crate::interval::DuckInterval] (pitfall P8).
270 /// Infallible: every combination renders.
271 ///
272 /// Note that the derived `PartialEq` on `DuckInterval` compares the three
273 /// fields, while `DuckDB`'s SQL `=` compares normalized intervals:
274 /// `INTERVAL '1 month' = INTERVAL '30 days'` and
275 /// `INTERVAL '1 day' = INTERVAL '24 hours'` are both `true` in SQL, but the
276 /// corresponding `DuckInterval`s are not equal.
277 #[inline]
278 #[must_use]
279 pub fn interval(value: crate::interval::DuckInterval) -> Self {
280 Self {
281 // SAFETY: a plain by-value struct DuckDB accepts unconditionally.
282 raw: unsafe {
283 duckdb_create_interval(duckdb_interval {
284 months: value.months,
285 days: value.days,
286 micros: value.micros,
287 })
288 },
289 }
290 }
291}
292
293/// The text [`Value::timestamp_tz_ns`] casts to `TIMESTAMPTZ_NS`: `rendered`
294/// (the `TIMESTAMP_NS` for `nanos`) with the UTC offset a finite instant needs.
295/// A finite instant renders without an offset; say it is UTC, which is what the
296/// value means. The infinities render as words and take none.
297fn utc_text(rendered: String, nanos: i64) -> String {
298 if nanos == i64::MAX || nanos == -i64::MAX {
299 rendered
300 } else {
301 format!("{rendered}+00")
302 }
303}
304
305#[cfg(test)]
306mod tests {
307 use super::{check, utc_text, Value, TIMESTAMP_RANGE};
308 use crate::types::TypeId;
309
310 /// Only a finite instant takes the `+00` offset, and each infinity is left
311 /// as the word `DuckDB` rendered, which an offset would make unparseable.
312 #[test]
313 fn utc_text_adds_the_offset_to_finite_instants_only() {
314 let text = |rendered: &str, nanos| utc_text(rendered.to_owned(), nanos);
315 assert_eq!(
316 text("2026-08-18 12:00:00.123456789", 1_787_054_400_123_456_789),
317 "2026-08-18 12:00:00.123456789+00"
318 );
319 assert_eq!(text("1970-01-01 00:00:00", 0), "1970-01-01 00:00:00+00");
320 assert_eq!(
321 text("1969-12-31 23:59:59.999999999", -1),
322 "1969-12-31 23:59:59.999999999+00"
323 );
324 assert_eq!(text("infinity", i64::MAX), "infinity");
325 assert_eq!(text("-infinity", -i64::MAX), "-infinity");
326 // The neighbours of each infinity are finite instants.
327 assert_eq!(text("x", i64::MAX - 1), "x+00");
328 assert_eq!(text("x", -i64::MAX + 1), "x+00");
329 }
330
331 /// An out-of-range `TIME_TZ` encoding is refused before `DuckDB` is
332 /// called, so this needs no live runtime. Passed on, it would be stored
333 /// unchecked and later render as garbage.
334 #[test]
335 fn time_tz_refuses_an_encoding_duckdb_cannot_render() {
336 // Every bit set: the time field is far past 24:00:00. Then a valid
337 // 00:00:00 with an offset field just past ±15:59:59.
338 for bits in [u64::MAX, 2 * 57_599 + 1] {
339 let err = Value::time_tz(bits).expect_err("out of range must be refused");
340 let msg = err.as_str();
341 assert!(msg.contains("Value::time_tz("), "{msg}");
342 assert!(msg.contains(&format!("{bits:#x}")), "{msg}");
343 assert!(msg.contains("TIMETZ"), "{msg}");
344 }
345 }
346
347 /// Each checked 64-bit constructor refuses a payload outside its type's
348 /// range before calling `DuckDB`, naming itself and the value.
349 #[test]
350 fn checked_constructors_refuse_out_of_range_payloads() {
351 type Ctor = fn(i64) -> Result<Value, crate::error::ExtensionError>;
352 let cases: Vec<(&str, Ctor, i64)> = vec![
353 ("time", Value::time, -1),
354 ("time", Value::time, 86_400_000_001),
355 ("timestamp", Value::timestamp, i64::MIN),
356 ("timestamp_tz", Value::timestamp_tz, i64::MIN),
357 ("timestamp_s", Value::timestamp_s, i64::MIN),
358 ("timestamp_ms", Value::timestamp_ms, i64::MIN),
359 ("timestamp_ns", Value::timestamp_ns, i64::MIN),
360 ("timestamp_tz_ns", Value::timestamp_tz_ns, i64::MIN),
361 (
362 "timestamp_tz_ns",
363 Value::timestamp_tz_ns,
364 -9_223_286_400_000_000_001,
365 ),
366 ];
367 #[cfg(feature = "duckdb-1-5")]
368 let cases = {
369 let mut cases = cases;
370 cases.push(("time_ns", Value::time_ns, -1));
371 cases
372 };
373 for (name, ctor, v) in cases {
374 let err = ctor(v).expect_err("out of range must be refused");
375 let msg = err.as_str();
376 assert!(msg.contains(&format!("Value::{name}({v})")), "{msg}");
377 }
378 }
379
380 /// The range check every fallible constructor runs before calling
381 /// `DuckDB`: an in-range payload is passed through unchanged, whatever
382 /// its value, and one just outside the range is refused with an error
383 /// naming the constructor, the value and the range.
384 #[test]
385 fn check_passes_in_range_payloads_through_and_names_the_rest() {
386 for v in [0, 1, 12_345, 86_400_000_000] {
387 assert_eq!(check(TypeId::Time, v, "time", "TIME range"), Ok(v));
388 }
389 for v in [-1, 86_400_000_001] {
390 let err = check(TypeId::Time, v, "time", "TIME range").expect_err("out of range");
391 assert!(
392 err.as_str()
393 .contains(&format!("Value::time({v}) is outside DuckDB's range")),
394 "{err}"
395 );
396 assert!(err.as_str().contains("TIME range"), "{err}");
397 }
398 for v in [i64::MAX, -i64::MAX, -2, 1_700_000_000_000_000] {
399 assert_eq!(
400 check(TypeId::Timestamp, v, "timestamp", TIMESTAMP_RANGE),
401 Ok(v)
402 );
403 }
404 }
405}