quack_rs/value/getters.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//! The typed scalar accessors — `Value::as_i64`, `as_timestamp`, `as_decimal`, …
7//!
8//! # Why every getter returns `Option`
9//!
10//! `DuckDB`'s `duckdb_get_*` scalar getters (`CAPIGetValue` in
11//! `duckdb_value-c.cpp`) have these hazards, none of which the C API guards:
12//!
13//! 1. **A SQL `NULL` aborts the process.** The cast of a `NULL` succeeds, then
14//! `Value::GetValue<T>` throws `InternalException`, and a C++ exception
15//! cannot unwind through Rust.
16//! 2. **A null handle is dereferenced.** `UnwrapValue` has no null check.
17//! 3. **The value is mutated (1.x).** Through 1.5, `CAPIGetValue` calls the
18//! non-`const` `DefaultTryCastAs`, which overwrites the value's type and
19//! payload with the cast result: `Value::double(1.5).as_i32()` changed the
20//! value itself. From 2.0.0 `DefaultTryCastAs` is `const` and returns an
21//! `optional<Value>`, so the value is left alone.
22//!
23//! A failed cast returns `NullValue<T>` — `T::MIN`, `NaN`, `false` — which is
24//! also a legitimate value, so the result alone cannot say whether it worked.
25//! On 1.x the rewritten type said so; on 2.0 nothing observable does.
26//!
27//! 4. **Some temporal casts throw.** `DefaultTryCastAs` reports a failed cast
28//! only for pairs `DuckDB` binds through an error-reporting `TryCast` loop.
29//! A few temporal pairs (`time_casts.cpp`) use `TemplatedCastLoop` with a
30//! throwing operator instead: `as_time()` of `'infinity'::TIMESTAMP`, or
31//! `as_timestamp_ns()` of any `TIMESTAMP` after 2262, threw straight
32//! through the C API.
33//!
34//! `Value::read_cast` addresses all of them on every engine: it refuses null
35//! handles, SQL `NULL`s and non-scalar source types before any call, checks
36//! the payload of a source whose cast could throw or overflow against the
37//! exact condition `DuckDB` fails on (`checks::cast_guard`), and then does the
38//! cast itself, outside the getter: `Value::cast_copy` builds a one-element
39//! `LIST` of the target type, whose construction casts the value and turns a
40//! failure into a null handle. The getter only ever reads a private copy that
41//! already has its own type, which is a plain copy on every engine, so its
42//! sentinel is never mistaken for a value.
43
44#[cfg(feature = "duckdb-1-5")]
45use libduckdb_sys::duckdb_get_time_ns;
46use libduckdb_sys::{
47 duckdb_get_bool, duckdb_get_date, duckdb_get_decimal, duckdb_get_double, duckdb_get_enum_value,
48 duckdb_get_float, duckdb_get_hugeint, duckdb_get_int16, duckdb_get_int32, duckdb_get_int64,
49 duckdb_get_int8, duckdb_get_interval, duckdb_get_time, duckdb_get_time_tz,
50 duckdb_get_timestamp, duckdb_get_timestamp_ms, duckdb_get_timestamp_ns, duckdb_get_timestamp_s,
51 duckdb_get_timestamp_tz, duckdb_get_uhugeint, duckdb_get_uint16, duckdb_get_uint32,
52 duckdb_get_uint64, duckdb_get_uint8, duckdb_get_uuid, duckdb_value,
53};
54
55use super::checks::is_scalar_cast_source;
56use super::temporal_checks::{cast_guard, temporal_in_range, time_tz_in_range};
57use super::{hugeint_to_i128, uhugeint_to_u128, Value};
58use crate::types::TypeId;
59
60impl Value {
61 /// The value cast to `target`, as a new owned handle of exactly that
62 /// type, or `None` if the cast fails. `self` is never touched.
63 ///
64 /// The C API has no "try cast this value" call that reports failure on
65 /// every engine (see the module docs), so this wraps the value in a
66 /// one-element `LIST(target)`: `Value::LIST` casts each child to the
67 /// list's child type with `DefaultCastAs` (`value.cpp`, `Value::LIST`, in
68 /// 1.5.6 and 2.0.0 alike), which throws on a failed cast, and
69 /// `duckdb_create_list_value` catches that and returns null. The child
70 /// is then taken back out (`duckdb_get_list_child` copies it). Neither
71 /// call lets an exception escape. The construction itself is
72 /// `Value::cast_into` (`cast.rs`), shared with `Value::try_cast`.
73 pub(super) fn cast_copy(&self, target: TypeId) -> Option<Self> {
74 if self.raw.is_null() {
75 return None;
76 }
77 let ty = crate::types::LogicalType::try_new(target).ok()?;
78 let copy = self.cast_into(&ty)?;
79 // A cast of a non-NULL value that came back SQL `NULL` would send the
80 // getter into hazard 1 (`GetValue<T>` on a `NULL` throws): refuse it.
81 // No scalar-to-scalar cast is known to do this; the check is one call.
82 (!copy.is_sql_null() && copy.type_id() == Some(target)).then_some(copy)
83 }
84
85 /// Runs a `DuckDB` scalar getter that casts to `target`, without its
86 /// hazards (see the module docs).
87 ///
88 /// `read` receives a live, non-null handle holding a non-NULL value of
89 /// exactly type `target`. It must only pass it to the `duckdb_get_*`
90 /// function whose target type is `target`, whose own cast is then a
91 /// plain copy.
92 fn read_cast<R>(&self, target: TypeId, read: impl FnOnce(duckdb_value) -> R) -> Option<R> {
93 let copy = self.checked_cast_copy(target)?;
94 let out = read(copy.raw);
95 (copy.type_id() == Some(target)).then_some(out)
96 }
97
98 /// The value cast to `target` as a new owned handle of exactly that type,
99 /// after every check [`read_cast`][Self::read_cast] makes, or `None` if
100 /// one refuses or the cast fails. `self` is never touched.
101 ///
102 /// The caller reads the copy at its own type, which no engine fails or
103 /// mutates. Split out of `read_cast` so a type with no `duckdb_get_*`
104 /// getter in the stable API struct (`TIMESTAMPTZ_NS`) gets the same
105 /// checks.
106 fn checked_cast_copy(&self, target: TypeId) -> Option<Self> {
107 let source = self.type_id()?;
108 if self.is_sql_null() || !is_scalar_cast_source(source) {
109 return None;
110 }
111 // A temporal source whose own payload is out of range: `DuckDB`'s cast
112 // of it can overflow a signed multiply (`Timestamp::GetTime` on
113 // `i64::MIN`, reported by UBSan) or throw, and such values do reach a
114 // `Value` — `make_timestamp(-9223372036854775808)` is ordinary SQL. The
115 // same-type read `temporal_payload` makes comes back here with
116 // `source == target`, which skips this.
117 if source != target && !self.own_payload_in_range(source) {
118 return None;
119 }
120 // A pair `DuckDB` converts with a throwing loop or an overflowing
121 // multiply: check the payload first. `cast_guard(t, t)` is `None`, so
122 // the same-type read inside `timestamp_payload` does not come back here.
123 if let Some(guard) = cast_guard(source, target) {
124 if !guard.accepts(self.timestamp_payload(source)?) {
125 return None;
126 }
127 }
128 // The cast happens here, reporting failure as `None`. The caller then
129 // only reads a value of its own type, which no engine fails or mutates
130 // (`Value::TryCastAs` copies when the types are equal), so DuckDB's
131 // `NullValue<T>` failure sentinel never reaches it.
132 self.cast_copy(target)
133 }
134
135 /// The raw `int64` of a `TIMESTAMP`-family value, read at its own type.
136 ///
137 /// Reading a value at its own type never casts: `Value::TryCastAs` copies
138 /// it when the source and target types are equal. `None` for any other
139 /// type.
140 fn timestamp_payload(&self, source: TypeId) -> Option<i64> {
141 // SAFETY (every arm): `read_cast` passes a live, non-NULL handle of
142 // exactly the getter's type.
143 match source {
144 TypeId::Timestamp => {
145 // SAFETY: `read_cast` only calls this closure with `copy.raw`, a live
146 // non-null cast copy of a non-NULL scalar (it refuses null handles, SQL
147 // NULL and non-scalar types first), so `CAPIGetValue`'s unchecked
148 // `UnwrapValue` and `GetValue<T>` (duckdb_value-c.cpp) neither see null nor
149 // throw on NULL. This arm reads a `TIMESTAMP` at its own type, so
150 // `duckdb_get_timestamp`'s `DefaultTryCastAs` is a plain copy of the
151 // throwaway cast copy.
152 self.read_cast(source, |v| unsafe { duckdb_get_timestamp(v) }.micros)
153 }
154 TypeId::TimestampTz => {
155 // SAFETY: `read_cast` only calls this closure with `copy.raw`, a live
156 // non-null cast copy of a non-NULL scalar (it refuses null handles, SQL
157 // NULL and non-scalar types first), so `CAPIGetValue`'s unchecked
158 // `UnwrapValue` and `GetValue<T>` (duckdb_value-c.cpp) neither see null nor
159 // throw on NULL. This arm reads a `TIMESTAMPTZ` at its own type, so
160 // `duckdb_get_timestamp_tz`'s `DefaultTryCastAs` is a plain copy of the
161 // throwaway cast copy.
162 self.read_cast(source, |v| unsafe { duckdb_get_timestamp_tz(v) }.micros)
163 }
164 TypeId::TimestampS => {
165 // SAFETY: `read_cast` only calls this closure with `copy.raw`, a live
166 // non-null cast copy of a non-NULL scalar (it refuses null handles, SQL
167 // NULL and non-scalar types first), so `CAPIGetValue`'s unchecked
168 // `UnwrapValue` and `GetValue<T>` (duckdb_value-c.cpp) neither see null nor
169 // throw on NULL. This arm reads a `TIMESTAMP_S` at its own type, so
170 // `duckdb_get_timestamp_s`'s `DefaultTryCastAs` is a plain copy of the
171 // throwaway cast copy.
172 self.read_cast(source, |v| unsafe { duckdb_get_timestamp_s(v) }.seconds)
173 }
174 TypeId::TimestampMs => {
175 // SAFETY: `read_cast` only calls this closure with `copy.raw`, a live
176 // non-null cast copy of a non-NULL scalar (it refuses null handles, SQL
177 // NULL and non-scalar types first), so `CAPIGetValue`'s unchecked
178 // `UnwrapValue` and `GetValue<T>` (duckdb_value-c.cpp) neither see null nor
179 // throw on NULL. This arm reads a `TIMESTAMP_MS` at its own type, so
180 // `duckdb_get_timestamp_ms`'s `DefaultTryCastAs` is a plain copy of the
181 // throwaway cast copy.
182 self.read_cast(source, |v| unsafe { duckdb_get_timestamp_ms(v) }.millis)
183 }
184 TypeId::TimestampNs => {
185 // SAFETY: `read_cast` only calls this closure with `copy.raw`, a live
186 // non-null cast copy of a non-NULL scalar (it refuses null handles, SQL
187 // NULL and non-scalar types first), so `CAPIGetValue`'s unchecked
188 // `UnwrapValue` and `GetValue<T>` (duckdb_value-c.cpp) neither see null nor
189 // throw on NULL. This arm reads a `TIMESTAMP_NS` at its own type, so
190 // `duckdb_get_timestamp_ns`'s `DefaultTryCastAs` is a plain copy of the
191 // throwaway cast copy.
192 self.read_cast(source, |v| unsafe { duckdb_get_timestamp_ns(v) }.nanos)
193 }
194 // `duckdb_get_timestamp_tz_ns` is one of the two slots DuckDB 2.0.0
195 // appended to `duckdb_ext_api_v1`, past the 546 a build against the
196 // 1.5.2 - 1.5.6 bindings (and an engine before 2.0.0) has. It is not
197 // used, so a `TIMESTAMPTZ_NS` value reads on any bindings. The payload
198 // is instead taken from the `TIMESTAMP_NS` cast, which is a
199 // `ReinterpretCast` (`TimestampTzNsCastSwitch`, `time_casts.cpp`): the
200 // same 64 bits for every input, with no range or finiteness check to
201 // throw. This does not go through `read_cast`, whose checks read this
202 // payload.
203 TypeId::TimestampTzNs => {
204 if self.is_sql_null() {
205 return None;
206 }
207 let copy = self.cast_copy(TypeId::TimestampNs)?;
208 // SAFETY: `cast_copy` returns a live, non-null, non-NULL
209 // `TIMESTAMP_NS` (it checks the type id and refuses null and
210 // SQL NULL), so `CAPIGetValue`'s unchecked `UnwrapValue` and
211 // `GetValue<T>` neither see null nor throw on NULL, and
212 // `duckdb_get_timestamp_ns`'s `DefaultTryCastAs` is a plain
213 // copy of a same-type value.
214 Some(unsafe { duckdb_get_timestamp_ns(copy.raw) }.nanos)
215 }
216 _ => None,
217 }
218 }
219
220 /// The raw payload of a `TIME`, `TIME_NS` or timestamp-family value, read
221 /// at its own type (no cast, so no conversion can fail).
222 pub(super) fn temporal_payload(&self, source: TypeId) -> Option<i64> {
223 match source {
224 // SAFETY: `read_cast` passes a live, non-NULL handle of exactly
225 // this type, so `duckdb_get_time`'s cast is a plain copy.
226 TypeId::Time => self.read_cast(source, |v| unsafe { duckdb_get_time(v) }.micros),
227 #[cfg(feature = "duckdb-1-5")]
228 // SAFETY: as above, for `TIME_NS`.
229 TypeId::TimeNs => self.read_cast(source, |v| unsafe { duckdb_get_time_ns(v) }.nanos),
230 _ => self.timestamp_payload(source),
231 }
232 }
233
234 /// The raw 64-bit encoding of a `TIMETZ` value, read at its own type.
235 pub(super) fn time_tz_payload(&self) -> Option<u64> {
236 // SAFETY: `read_cast` passes a live, non-NULL handle; on a `TIMETZ`
237 // value `duckdb_get_time_tz`'s cast is a plain copy.
238 self.read_cast(TypeId::TimeTz, |v| unsafe { duckdb_get_time_tz(v) }.bits)
239 }
240
241 /// Whether a temporal value's own payload is in the range `DuckDB`
242 /// converts safely; `true` for every other type.
243 fn own_payload_in_range(&self, source: TypeId) -> bool {
244 match source {
245 TypeId::TimeTz => self.time_tz_payload().is_some_and(time_tz_in_range),
246 TypeId::Time
247 | TypeId::Timestamp
248 | TypeId::TimestampTz
249 | TypeId::TimestampS
250 | TypeId::TimestampMs
251 | TypeId::TimestampNs
252 | TypeId::TimestampTzNs => self
253 .temporal_payload(source)
254 .is_some_and(|v| temporal_in_range(source, v)),
255 #[cfg(feature = "duckdb-1-5")]
256 TypeId::TimeNs => self
257 .temporal_payload(source)
258 .is_some_and(|v| temporal_in_range(source, v)),
259 _ => true,
260 }
261 }
262
263 /// Whether the handle is non-null, the value is not SQL `NULL`, and its
264 /// type is exactly `expected`. Used by the getters that do not cast.
265 fn holds(&self, expected: TypeId) -> bool {
266 self.type_id() == Some(expected) && !self.is_sql_null()
267 }
268
269 /// Reads the value as an `i32`, casting it to `INTEGER` the way SQL's
270 /// `TRY_CAST` would.
271 ///
272 /// Returns `None` if the handle is null, the value is SQL `NULL`, its type
273 /// is not a scalar (`LIST`, `STRUCT`, `BLOB`, `ENUM`, …), or the cast fails
274 /// (`'abc'`, or a number out of range). Casts follow `DuckDB`: a `DOUBLE`
275 /// `1.5` reads as `2`, a `VARCHAR` `'42'` as `42`.
276 ///
277 /// The value itself is never modified. The same rules apply to every
278 /// casting `as_*` accessor; see [`as_i32_or`][Self::as_i32_or] and its
279 /// siblings for a defaulting form.
280 #[must_use]
281 pub fn as_i32(&self) -> Option<i32> {
282 // SAFETY: `read_cast` passes a live, non-NULL scalar handle.
283 self.read_cast(TypeId::Integer, |v| unsafe { duckdb_get_int32(v) })
284 }
285
286 /// Reads the value as an `i64` (`BIGINT`). `None` on a null handle, SQL
287 /// `NULL`, non-scalar type or failed cast; see [`as_i32`][Self::as_i32].
288 #[must_use]
289 pub fn as_i64(&self) -> Option<i64> {
290 // SAFETY: `read_cast` passes a live, non-NULL scalar handle.
291 self.read_cast(TypeId::BigInt, |v| unsafe { duckdb_get_int64(v) })
292 }
293
294 /// Reads the value as an `f32` (`FLOAT`). `None` on a null handle, SQL
295 /// `NULL`, non-scalar type or failed cast; see [`as_i32`][Self::as_i32].
296 #[must_use]
297 pub fn as_f32(&self) -> Option<f32> {
298 // SAFETY: `read_cast` passes a live, non-NULL scalar handle.
299 self.read_cast(TypeId::Float, |v| unsafe { duckdb_get_float(v) })
300 }
301
302 /// Reads the value as an `f64` (`DOUBLE`). `None` on a null handle, SQL
303 /// `NULL`, non-scalar type or failed cast; see [`as_i32`][Self::as_i32].
304 #[must_use]
305 pub fn as_f64(&self) -> Option<f64> {
306 // SAFETY: `read_cast` passes a live, non-NULL scalar handle.
307 self.read_cast(TypeId::Double, |v| unsafe { duckdb_get_double(v) })
308 }
309
310 /// Reads the value as a `bool` (`BOOLEAN`). `None` on a null handle, SQL
311 /// `NULL`, non-scalar type or failed cast; see [`as_i32`][Self::as_i32].
312 #[must_use]
313 pub fn as_bool(&self) -> Option<bool> {
314 // SAFETY: `read_cast` passes a live, non-NULL scalar handle.
315 self.read_cast(TypeId::Boolean, |v| unsafe { duckdb_get_bool(v) })
316 }
317
318 /// Reads the value as an `i8` (`TINYINT`). `None` on a null handle, SQL
319 /// `NULL`, non-scalar type or failed cast; see [`as_i32`][Self::as_i32].
320 #[must_use]
321 pub fn as_i8(&self) -> Option<i8> {
322 // SAFETY: `read_cast` passes a live, non-NULL scalar handle.
323 self.read_cast(TypeId::TinyInt, |v| unsafe { duckdb_get_int8(v) })
324 }
325
326 /// Reads the value as an `i16` (`SMALLINT`). `None` on a null handle, SQL
327 /// `NULL`, non-scalar type or failed cast; see [`as_i32`][Self::as_i32].
328 #[must_use]
329 pub fn as_i16(&self) -> Option<i16> {
330 // SAFETY: `read_cast` passes a live, non-NULL scalar handle.
331 self.read_cast(TypeId::SmallInt, |v| unsafe { duckdb_get_int16(v) })
332 }
333
334 /// Reads the value as a `u8` (`UTINYINT`). `None` on a null handle, SQL
335 /// `NULL`, non-scalar type or failed cast; see [`as_i32`][Self::as_i32].
336 #[must_use]
337 pub fn as_u8(&self) -> Option<u8> {
338 // SAFETY: `read_cast` passes a live, non-NULL scalar handle.
339 self.read_cast(TypeId::UTinyInt, |v| unsafe { duckdb_get_uint8(v) })
340 }
341
342 /// Reads the value as a `u16` (`USMALLINT`). `None` on a null handle, SQL
343 /// `NULL`, non-scalar type or failed cast; see [`as_i32`][Self::as_i32].
344 #[must_use]
345 pub fn as_u16(&self) -> Option<u16> {
346 // SAFETY: `read_cast` passes a live, non-NULL scalar handle.
347 self.read_cast(TypeId::USmallInt, |v| unsafe { duckdb_get_uint16(v) })
348 }
349
350 /// Reads the value as a `u32` (`UINTEGER`). `None` on a null handle, SQL
351 /// `NULL`, non-scalar type or failed cast; see [`as_i32`][Self::as_i32].
352 #[must_use]
353 pub fn as_u32(&self) -> Option<u32> {
354 // SAFETY: `read_cast` passes a live, non-NULL scalar handle.
355 self.read_cast(TypeId::UInteger, |v| unsafe { duckdb_get_uint32(v) })
356 }
357
358 /// Reads the value as a `u64` (`UBIGINT`). `None` on a null handle, SQL
359 /// `NULL`, non-scalar type or failed cast; see [`as_i32`][Self::as_i32].
360 #[must_use]
361 pub fn as_u64(&self) -> Option<u64> {
362 // SAFETY: `read_cast` passes a live, non-NULL scalar handle.
363 self.read_cast(TypeId::UBigInt, |v| unsafe { duckdb_get_uint64(v) })
364 }
365
366 /// Reads the value as an `i128` (`HUGEINT`). `None` on a null handle, SQL
367 /// `NULL`, non-scalar type or failed cast; see [`as_i32`][Self::as_i32].
368 #[must_use]
369 pub fn as_i128(&self) -> Option<i128> {
370 // SAFETY: `read_cast` passes a live, non-NULL scalar handle.
371 self.read_cast(TypeId::HugeInt, |v| unsafe { duckdb_get_hugeint(v) })
372 .map(hugeint_to_i128)
373 }
374
375 /// Reads the value as a `u128` (`UHUGEINT`). `None` on a null handle, SQL
376 /// `NULL`, non-scalar type or failed cast; see [`as_i32`][Self::as_i32].
377 #[must_use]
378 pub fn as_u128(&self) -> Option<u128> {
379 // SAFETY: `read_cast` passes a live, non-NULL scalar handle.
380 self.read_cast(TypeId::UHugeInt, |v| unsafe { duckdb_get_uhugeint(v) })
381 .map(uhugeint_to_u128)
382 }
383
384 // ── Temporal and UUID ────────────────────────────────────────────────
385 //
386 // A table function declared with `.named_param("since", TypeId::Timestamp)`
387 // hands the bind callback a `duckdb_value`; these read it without
388 // reparsing DuckDB's rendering. They cast like the numeric getters, so a
389 // `VARCHAR` '2024-01-01' reads as a `DATE`.
390 //
391 // A temporal getter also returns `None` when the conversion is one DuckDB
392 // refuses in SQL: the time of an infinite timestamp, a TIMESTAMP after
393 // 2262 as TIMESTAMP_NS, or a result outside the target type's range (the
394 // TIMESTAMP maximum rounds to a TIMESTAMP_S that DuckDB cannot convert
395 // back). Each agrees with `CAST(x AS target)` in SQL.
396
397 /// Reads a `DATE` as days since 1970-01-01. Decode it with
398 /// [`datetime::date_from_days`][crate::datetime::date_from_days].
399 ///
400 /// `None` on a null handle, SQL `NULL`, non-scalar type or failed cast;
401 /// see [`as_i32`][Self::as_i32].
402 #[must_use]
403 pub fn as_date(&self) -> Option<i32> {
404 // SAFETY: `read_cast` passes a live, non-NULL scalar handle.
405 self.read_cast(TypeId::Date, |v| unsafe { duckdb_get_date(v) }.days)
406 }
407
408 /// Reads a `TIME` as microseconds since midnight. `None` on a null handle,
409 /// SQL `NULL`, non-scalar type or failed cast — including the time of an
410 /// infinite `TIMESTAMP`, which `DuckDB` refuses (it used to abort the
411 /// process here).
412 #[must_use]
413 pub fn as_time(&self) -> Option<i64> {
414 // SAFETY: `read_cast` passes a live, non-NULL scalar handle.
415 self.read_cast(TypeId::Time, |v| unsafe { duckdb_get_time(v) }.micros)
416 .filter(|&v| temporal_in_range(TypeId::Time, v))
417 }
418
419 /// Reads a `TIMETZ` as `DuckDB`'s packed 64-bit representation. Decode it
420 /// with [`datetime::time_tz_from_bits`][crate::datetime::time_tz_from_bits].
421 ///
422 /// `None` on a null handle, SQL `NULL`, non-scalar type or failed cast.
423 #[must_use]
424 pub fn as_time_tz(&self) -> Option<u64> {
425 // SAFETY: `read_cast` passes a live, non-NULL scalar handle.
426 self.read_cast(TypeId::TimeTz, |v| unsafe { duckdb_get_time_tz(v) }.bits)
427 .filter(|&bits| time_tz_in_range(bits))
428 }
429
430 /// Reads a `TIME_NS` as nanoseconds since midnight (`DuckDB` 1.5.0+).
431 ///
432 /// `None` on a null handle, SQL `NULL`, non-scalar type or failed cast.
433 #[cfg(feature = "duckdb-1-5")]
434 #[must_use]
435 pub fn as_time_ns(&self) -> Option<i64> {
436 // SAFETY: `read_cast` passes a live, non-NULL scalar handle.
437 self.read_cast(TypeId::TimeNs, |v| unsafe { duckdb_get_time_ns(v) }.nanos)
438 .filter(|&v| temporal_in_range(TypeId::TimeNs, v))
439 }
440
441 /// Reads a `TIMESTAMP` as microseconds since the epoch. `None` on a null
442 /// handle, SQL `NULL`, non-scalar type or failed cast.
443 #[must_use]
444 pub fn as_timestamp(&self) -> Option<i64> {
445 // SAFETY: `read_cast` passes a live, non-NULL scalar handle.
446 self.read_cast(
447 TypeId::Timestamp,
448 |v| unsafe { duckdb_get_timestamp(v) }.micros,
449 )
450 .filter(|&v| temporal_in_range(TypeId::Timestamp, v))
451 }
452
453 /// Reads a `TIMESTAMPTZ` as microseconds since the epoch, in UTC. `None`
454 /// on a null handle, SQL `NULL`, non-scalar type or failed cast.
455 #[must_use]
456 pub fn as_timestamp_tz(&self) -> Option<i64> {
457 // SAFETY: `read_cast` passes a live, non-NULL scalar handle.
458 self.read_cast(TypeId::TimestampTz, |v| {
459 // SAFETY: `v` is `read_cast`'s live, non-null private cast copy of a non-NULL
460 // scalar (null handles, SQL NULL and non-scalar sources are refused first), so
461 // `duckdb_get_timestamp_tz`'s unchecked `UnwrapValue` and `GetValue<T>` cannot
462 // hit null or throw on NULL; `read_cast` has also checked `cast_guard(source,
463 // TimestampTz)` against the payload, ruling out the throwing temporal casts.
464 // The getter's own cast is a same-type copy.
465 unsafe { duckdb_get_timestamp_tz(v) }.micros
466 })
467 .filter(|&v| temporal_in_range(TypeId::TimestampTz, v))
468 }
469
470 /// Reads a `TIMESTAMP_S` as seconds since the epoch. `None` on a null
471 /// handle, SQL `NULL`, non-scalar type or failed cast.
472 #[must_use]
473 pub fn as_timestamp_s(&self) -> Option<i64> {
474 // SAFETY: `read_cast` passes a live, non-NULL scalar handle.
475 self.read_cast(TypeId::TimestampS, |v| {
476 // SAFETY: `v` is `read_cast`'s live, non-null private cast copy of a non-NULL
477 // scalar (null handles, SQL NULL and non-scalar sources are refused first), so
478 // `duckdb_get_timestamp_s`'s unchecked `UnwrapValue` and `GetValue<T>` cannot
479 // hit null or throw on NULL; `read_cast` has also checked `cast_guard(source,
480 // TimestampS)` against the payload, ruling out the throwing temporal casts.
481 // The getter's own cast is a same-type copy.
482 unsafe { duckdb_get_timestamp_s(v) }.seconds
483 })
484 .filter(|&v| temporal_in_range(TypeId::TimestampS, v))
485 }
486
487 /// Reads a `TIMESTAMP_MS` as milliseconds since the epoch. `None` on a
488 /// null handle, SQL `NULL`, non-scalar type or failed cast.
489 #[must_use]
490 pub fn as_timestamp_ms(&self) -> Option<i64> {
491 // SAFETY: `read_cast` passes a live, non-NULL scalar handle.
492 self.read_cast(TypeId::TimestampMs, |v| {
493 // SAFETY: `v` is `read_cast`'s live, non-null private cast copy of a non-NULL
494 // scalar (null handles, SQL NULL and non-scalar sources are refused first), so
495 // `duckdb_get_timestamp_ms`'s unchecked `UnwrapValue` and `GetValue<T>` cannot
496 // hit null or throw on NULL; `read_cast` has also checked `cast_guard(source,
497 // TimestampMs)` against the payload, ruling out the throwing temporal casts.
498 // The getter's own cast is a same-type copy.
499 unsafe { duckdb_get_timestamp_ms(v) }.millis
500 })
501 .filter(|&v| temporal_in_range(TypeId::TimestampMs, v))
502 }
503
504 /// Reads a `TIMESTAMP_NS` as nanoseconds since the epoch. `None` on a
505 /// null handle, SQL `NULL`, non-scalar type or failed cast — including a
506 /// timestamp outside `TIMESTAMP_NS`'s range (before 1677-09-22 or after
507 /// 2262-04-11), which `DuckDB` refuses (it used to abort the process here).
508 #[must_use]
509 pub fn as_timestamp_ns(&self) -> Option<i64> {
510 // SAFETY: `read_cast` passes a live, non-NULL scalar handle.
511 self.read_cast(TypeId::TimestampNs, |v| {
512 // SAFETY: `v` is `read_cast`'s live, non-null private cast copy of a non-NULL
513 // scalar (null handles, SQL NULL and non-scalar sources are refused first), so
514 // `duckdb_get_timestamp_ns`'s unchecked `UnwrapValue` and `GetValue<T>` cannot
515 // hit null or throw on NULL; `read_cast` has also checked `cast_guard(source,
516 // TimestampNs)` against the payload, ruling out the throwing temporal casts.
517 // The getter's own cast is a same-type copy.
518 unsafe { duckdb_get_timestamp_ns(v) }.nanos
519 })
520 .filter(|&v| temporal_in_range(TypeId::TimestampNs, v))
521 }
522
523 /// Reads a `TIMESTAMPTZ_NS` as nanoseconds since the epoch (`DuckDB`
524 /// 2.0.0+). `None` on a null handle, SQL `NULL`, non-scalar type or failed
525 /// cast — including a timestamp outside the type's range (before
526 /// 1677-09-22 or after 2262-04-11). Always `None` on an engine before
527 /// 2.0.0, which has no such type to cast to.
528 ///
529 /// Pairs with [`timestamp_tz_ns`][Value::timestamp_tz_ns] and the
530 /// [`TypeId::TimestampTzNs`] column type.
531 #[must_use]
532 pub fn as_timestamp_tz_ns(&self) -> Option<i64> {
533 let copy = self.checked_cast_copy(TypeId::TimestampTzNs)?;
534 copy.timestamp_payload(TypeId::TimestampTzNs)
535 .filter(|&v| temporal_in_range(TypeId::TimestampTzNs, v))
536 }
537
538 /// Reads an `INTERVAL`. `None` on a null handle, SQL `NULL`, non-scalar
539 /// type or failed cast.
540 #[must_use]
541 pub fn as_interval(&self) -> Option<crate::interval::DuckInterval> {
542 // SAFETY: `read_cast` passes a live, non-NULL scalar handle.
543 let raw = self.read_cast(TypeId::Interval, |v| unsafe { duckdb_get_interval(v) })?;
544 Some(crate::interval::DuckInterval {
545 months: raw.months,
546 days: raw.days,
547 micros: raw.micros,
548 })
549 }
550
551 /// Reads a `UUID` as its **textual** 128 bits, matching
552 /// [`VectorReader::read_uuid`][crate::vector::VectorReader::read_uuid]
553 /// and [`uuid`][Self::uuid].
554 ///
555 /// `DuckDB` undoes its internal top-bit flip itself here, so this is the
556 /// value the UUID renders as — not the raw `HUGEINT` a `UUID` vector holds.
557 /// `None` on a null handle, SQL `NULL`, non-scalar type or failed cast.
558 #[must_use]
559 pub fn as_uuid(&self) -> Option<u128> {
560 // SAFETY: `read_cast` passes a live, non-NULL scalar handle.
561 self.read_cast(TypeId::Uuid, |v| unsafe { duckdb_get_uuid(v) })
562 .map(uhugeint_to_u128)
563 }
564
565 // ── Non-casting getters ──────────────────────────────────────────────
566
567 /// Reads a `DECIMAL` as its width, scale and unscaled value; the
568 /// represented number is `value / 10^scale`.
569 ///
570 /// Does not cast: returns `None` unless the value is a non-NULL `DECIMAL`
571 /// (and for a null handle).
572 #[must_use]
573 pub fn as_decimal(&self) -> Option<crate::datetime::Decimal> {
574 if !self.holds(TypeId::Decimal) {
575 return None;
576 }
577 // SAFETY: `self.raw` is a live handle holding a non-NULL DECIMAL;
578 // `duckdb_get_decimal` reads it through a const reference.
579 let raw = unsafe { duckdb_get_decimal(self.raw) };
580 Some(crate::datetime::Decimal {
581 width: raw.width,
582 scale: raw.scale,
583 value: hugeint_to_i128(raw.value),
584 })
585 }
586
587 /// Returns the dictionary index of an `ENUM` value.
588 ///
589 /// Does not cast: returns `None` unless the value is a non-NULL `ENUM`
590 /// (and for a null handle). The C function returns `0` in those cases,
591 /// which is also a legitimate index.
592 #[must_use]
593 pub fn as_enum_index(&self) -> Option<u64> {
594 if !self.holds(TypeId::Enum) {
595 return None;
596 }
597 // SAFETY: `self.raw` is a live handle holding a non-NULL ENUM;
598 // `duckdb_get_enum_value` reads a copy of it.
599 Some(unsafe { duckdb_get_enum_value(self.raw) })
600 }
601}