Skip to main content

quack_rs/types/
type_id.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//! Ergonomic enum of all `DuckDB` column types.
7//!
8//! [`TypeId`] wraps the `DUCKDB_TYPE_*` integer constants from `libduckdb-sys` and
9//! provides a safe, exhaustive enum for use in builder APIs.
10
11use libduckdb_sys::{
12    DUCKDB_TYPE, DUCKDB_TYPE_DUCKDB_TYPE_ARRAY, DUCKDB_TYPE_DUCKDB_TYPE_BIGINT,
13    DUCKDB_TYPE_DUCKDB_TYPE_BIT, DUCKDB_TYPE_DUCKDB_TYPE_BLOB, DUCKDB_TYPE_DUCKDB_TYPE_BOOLEAN,
14    DUCKDB_TYPE_DUCKDB_TYPE_DATE, DUCKDB_TYPE_DUCKDB_TYPE_DECIMAL, DUCKDB_TYPE_DUCKDB_TYPE_DOUBLE,
15    DUCKDB_TYPE_DUCKDB_TYPE_ENUM, DUCKDB_TYPE_DUCKDB_TYPE_FLOAT, DUCKDB_TYPE_DUCKDB_TYPE_HUGEINT,
16    DUCKDB_TYPE_DUCKDB_TYPE_INTEGER, DUCKDB_TYPE_DUCKDB_TYPE_INTERVAL,
17    DUCKDB_TYPE_DUCKDB_TYPE_LIST, DUCKDB_TYPE_DUCKDB_TYPE_MAP, DUCKDB_TYPE_DUCKDB_TYPE_SMALLINT,
18    DUCKDB_TYPE_DUCKDB_TYPE_STRUCT, DUCKDB_TYPE_DUCKDB_TYPE_TIME,
19    DUCKDB_TYPE_DUCKDB_TYPE_TIMESTAMP, DUCKDB_TYPE_DUCKDB_TYPE_TIMESTAMP_MS,
20    DUCKDB_TYPE_DUCKDB_TYPE_TIMESTAMP_NS, DUCKDB_TYPE_DUCKDB_TYPE_TIMESTAMP_S,
21    DUCKDB_TYPE_DUCKDB_TYPE_TIMESTAMP_TZ, DUCKDB_TYPE_DUCKDB_TYPE_TIME_TZ,
22    DUCKDB_TYPE_DUCKDB_TYPE_TINYINT, DUCKDB_TYPE_DUCKDB_TYPE_UBIGINT,
23    DUCKDB_TYPE_DUCKDB_TYPE_UHUGEINT, DUCKDB_TYPE_DUCKDB_TYPE_UINTEGER,
24    DUCKDB_TYPE_DUCKDB_TYPE_UNION, DUCKDB_TYPE_DUCKDB_TYPE_USMALLINT,
25    DUCKDB_TYPE_DUCKDB_TYPE_UTINYINT, DUCKDB_TYPE_DUCKDB_TYPE_UUID,
26    DUCKDB_TYPE_DUCKDB_TYPE_VARCHAR,
27};
28use libduckdb_sys::{
29    DUCKDB_TYPE_DUCKDB_TYPE_ANY, DUCKDB_TYPE_DUCKDB_TYPE_BIGNUM,
30    DUCKDB_TYPE_DUCKDB_TYPE_INTEGER_LITERAL, DUCKDB_TYPE_DUCKDB_TYPE_SQLNULL,
31    DUCKDB_TYPE_DUCKDB_TYPE_STRING_LITERAL, DUCKDB_TYPE_DUCKDB_TYPE_TIME_NS,
32};
33#[cfg(feature = "duckdb-1-5-3")]
34use libduckdb_sys::{DUCKDB_TYPE_DUCKDB_TYPE_GEOMETRY, DUCKDB_TYPE_DUCKDB_TYPE_VARIANT};
35
36/// `DUCKDB_TYPE_TIMESTAMP_TZ_NS`, the type id `DuckDB` 2.0.0 added (`duckdb.h`).
37///
38/// Spelled as a literal, not as the `libduckdb_sys` constant, so [`TypeId`]
39/// knows the type whichever bindings Cargo resolved: only the 2.0 bindings
40/// (`libduckdb-sys` 1.20000.0+) declare the constant, and the number is part
41/// of the stable C ABI. The same choice is made for the 2.0 error categories
42/// in `error_data`.
43const DUCKDB_TYPE_TIMESTAMP_TZ_NS: DUCKDB_TYPE = 42;
44
45/// Identifies a `DuckDB` column type.
46///
47/// Use this in the aggregate function builders instead of the raw `DUCKDB_TYPE_*`
48/// integer constants. This enum is non-exhaustive — new variants may be added as
49/// `DuckDB` adds new types.
50///
51/// # Example
52///
53/// ```rust
54/// use quack_rs::types::TypeId;
55///
56/// let t = TypeId::BigInt;
57/// assert_eq!(t.to_duckdb_type(), libduckdb_sys::DUCKDB_TYPE_DUCKDB_TYPE_BIGINT);
58/// ```
59#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
60#[non_exhaustive]
61pub enum TypeId {
62    /// `BOOLEAN` — true/false
63    Boolean,
64    /// `TINYINT` — 8-bit signed integer
65    TinyInt,
66    /// `SMALLINT` — 16-bit signed integer
67    SmallInt,
68    /// `INTEGER` — 32-bit signed integer
69    Integer,
70    /// `BIGINT` — 64-bit signed integer
71    BigInt,
72    /// `UTINYINT` — 8-bit unsigned integer
73    UTinyInt,
74    /// `USMALLINT` — 16-bit unsigned integer
75    USmallInt,
76    /// `UINTEGER` — 32-bit unsigned integer
77    UInteger,
78    /// `UBIGINT` — 64-bit unsigned integer
79    UBigInt,
80    /// `HUGEINT` — 128-bit signed integer
81    HugeInt,
82    /// `FLOAT` — 32-bit floating-point
83    Float,
84    /// `DOUBLE` — 64-bit floating-point
85    Double,
86    /// `TIMESTAMP` — microseconds since epoch
87    Timestamp,
88    /// `TIMESTAMP WITH TIME ZONE` — timezone-aware timestamp
89    TimestampTz,
90    /// `DATE` — days since epoch
91    Date,
92    /// `TIME` — microseconds since midnight
93    Time,
94    /// `INTERVAL` — { months, days, micros }
95    Interval,
96    /// `VARCHAR` — UTF-8 string
97    Varchar,
98    /// `BLOB` — binary data
99    Blob,
100    /// `DECIMAL` — fixed-point decimal (width, scale)
101    Decimal,
102    /// `TIMESTAMP_S` — seconds since epoch
103    TimestampS,
104    /// `TIMESTAMP_MS` — milliseconds since epoch
105    TimestampMs,
106    /// `TIMESTAMP_NS` — nanoseconds since epoch
107    TimestampNs,
108    /// `ENUM` — enumeration type
109    Enum,
110    /// `LIST` — variable-length list
111    List,
112    /// `STRUCT` — named fields (row type)
113    Struct,
114    /// `MAP` — key-value pairs (LIST of STRUCT)
115    Map,
116    /// `UUID` — 128-bit UUID
117    Uuid,
118    /// `UNION` — tagged union of types
119    Union,
120    /// `BIT` — bitstring
121    Bit,
122    /// `TIME WITH TIME ZONE` — timezone-aware time
123    TimeTz,
124    /// `UHUGEINT` — 128-bit unsigned integer
125    UHugeInt,
126    /// `ARRAY` — fixed-length array
127    Array,
128    /// `TIME_NS` — time of day with nanosecond precision (`DuckDB` 1.4.0+)
129    TimeNs,
130    /// `ANY` — wildcard type for function signatures
131    ///
132    /// Used in function overload resolution to accept any input type.
133    /// Not a concrete column type — typically used only in builder APIs.
134    Any,
135    /// `BIGNUM` — arbitrary-precision integer (called `VARINT` before `DuckDB`
136    /// 1.4.0, and still accepted under that name)
137    ///
138    /// Arbitrary-precision integer stored as a variable-length encoding.
139    /// Maps to `DUCKDB_TYPE_BIGNUM` in the C API.
140    Varint,
141    /// `SQLNULL` — explicit SQL NULL type
142    ///
143    /// Represents the type of a bare `NULL` literal before type resolution.
144    SqlNull,
145    /// `INTEGER_LITERAL` — integer literal type used during overload resolution
146    ///
147    /// Internal type representing an unresolved integer literal in SQL. Not a
148    /// concrete column type — used by `DuckDB`'s type resolution system.
149    IntegerLiteral,
150    /// `STRING_LITERAL` — string literal type used during overload resolution
151    ///
152    /// Internal type representing an unresolved string literal in SQL. Not a
153    /// concrete column type — used by `DuckDB`'s type resolution system.
154    StringLiteral,
155    /// `GEOMETRY` — spatial geometry value (`DuckDB` 1.5.x; requires `duckdb-1-5-3`)
156    ///
157    /// Present in the C type enum as `DUCKDB_TYPE_GEOMETRY` (40). Gated behind
158    /// the `duckdb-1-5-3` feature; see that feature's documentation for the
159    /// version-floor rationale.
160    #[cfg(feature = "duckdb-1-5-3")]
161    Geometry,
162    /// `VARIANT` — self-describing nested value, e.g. for Iceberg v3 (`DuckDB` 1.5.3; requires `duckdb-1-5-3`)
163    ///
164    /// Added to the C type enum as `DUCKDB_TYPE_VARIANT` (41) in `DuckDB` 1.5.3.
165    #[cfg(feature = "duckdb-1-5-3")]
166    Variant,
167    /// `TIMESTAMPTZ_NS` — timestamp with time zone at nanosecond precision,
168    /// nanoseconds since epoch (`DuckDB` 2.0.0+)
169    ///
170    /// Added to the C type enum as `DUCKDB_TYPE_TIMESTAMP_TZ_NS` (42) in `DuckDB`
171    /// 2.0.0. Stored exactly like [`TimestampNs`][Self::TimestampNs]: an `i64`
172    /// count of nanoseconds (read it with
173    /// [`VectorReader::read_timestamp_tz_ns`][crate::vector::VectorReader::read_timestamp_tz_ns]).
174    ///
175    /// This variant exists on every build, whatever bindings or features are
176    /// in use, because the id is a plain number. A `DuckDB` before 2.0.0 has no
177    /// such type: it never reports this id, and refuses to create the type.
178    TimestampTzNs,
179}
180
181impl TypeId {
182    /// Converts this `TypeId` to the corresponding `DuckDB` C API type constant.
183    ///
184    /// # Example
185    ///
186    /// ```rust
187    /// use quack_rs::types::TypeId;
188    ///
189    /// assert_eq!(
190    ///     TypeId::Timestamp.to_duckdb_type(),
191    ///     libduckdb_sys::DUCKDB_TYPE_DUCKDB_TYPE_TIMESTAMP,
192    /// );
193    /// ```
194    #[must_use]
195    pub const fn to_duckdb_type(self) -> DUCKDB_TYPE {
196        match self {
197            Self::Boolean => DUCKDB_TYPE_DUCKDB_TYPE_BOOLEAN,
198            Self::TinyInt => DUCKDB_TYPE_DUCKDB_TYPE_TINYINT,
199            Self::SmallInt => DUCKDB_TYPE_DUCKDB_TYPE_SMALLINT,
200            Self::Integer => DUCKDB_TYPE_DUCKDB_TYPE_INTEGER,
201            Self::BigInt => DUCKDB_TYPE_DUCKDB_TYPE_BIGINT,
202            Self::UTinyInt => DUCKDB_TYPE_DUCKDB_TYPE_UTINYINT,
203            Self::USmallInt => DUCKDB_TYPE_DUCKDB_TYPE_USMALLINT,
204            Self::UInteger => DUCKDB_TYPE_DUCKDB_TYPE_UINTEGER,
205            Self::UBigInt => DUCKDB_TYPE_DUCKDB_TYPE_UBIGINT,
206            Self::HugeInt => DUCKDB_TYPE_DUCKDB_TYPE_HUGEINT,
207            Self::Float => DUCKDB_TYPE_DUCKDB_TYPE_FLOAT,
208            Self::Double => DUCKDB_TYPE_DUCKDB_TYPE_DOUBLE,
209            Self::Timestamp => DUCKDB_TYPE_DUCKDB_TYPE_TIMESTAMP,
210            Self::TimestampTz => DUCKDB_TYPE_DUCKDB_TYPE_TIMESTAMP_TZ,
211            Self::Date => DUCKDB_TYPE_DUCKDB_TYPE_DATE,
212            Self::Time => DUCKDB_TYPE_DUCKDB_TYPE_TIME,
213            Self::Interval => DUCKDB_TYPE_DUCKDB_TYPE_INTERVAL,
214            Self::Varchar => DUCKDB_TYPE_DUCKDB_TYPE_VARCHAR,
215            Self::Blob => DUCKDB_TYPE_DUCKDB_TYPE_BLOB,
216            Self::Decimal => DUCKDB_TYPE_DUCKDB_TYPE_DECIMAL,
217            Self::TimestampS => DUCKDB_TYPE_DUCKDB_TYPE_TIMESTAMP_S,
218            Self::TimestampMs => DUCKDB_TYPE_DUCKDB_TYPE_TIMESTAMP_MS,
219            Self::TimestampNs => DUCKDB_TYPE_DUCKDB_TYPE_TIMESTAMP_NS,
220            Self::Enum => DUCKDB_TYPE_DUCKDB_TYPE_ENUM,
221            Self::List => DUCKDB_TYPE_DUCKDB_TYPE_LIST,
222            Self::Struct => DUCKDB_TYPE_DUCKDB_TYPE_STRUCT,
223            Self::Map => DUCKDB_TYPE_DUCKDB_TYPE_MAP,
224            Self::Uuid => DUCKDB_TYPE_DUCKDB_TYPE_UUID,
225            Self::Union => DUCKDB_TYPE_DUCKDB_TYPE_UNION,
226            Self::Bit => DUCKDB_TYPE_DUCKDB_TYPE_BIT,
227            Self::TimeTz => DUCKDB_TYPE_DUCKDB_TYPE_TIME_TZ,
228            Self::UHugeInt => DUCKDB_TYPE_DUCKDB_TYPE_UHUGEINT,
229            Self::Array => DUCKDB_TYPE_DUCKDB_TYPE_ARRAY,
230            Self::TimeNs => DUCKDB_TYPE_DUCKDB_TYPE_TIME_NS,
231            Self::Any => DUCKDB_TYPE_DUCKDB_TYPE_ANY,
232            Self::Varint => DUCKDB_TYPE_DUCKDB_TYPE_BIGNUM,
233            Self::SqlNull => DUCKDB_TYPE_DUCKDB_TYPE_SQLNULL,
234            Self::IntegerLiteral => DUCKDB_TYPE_DUCKDB_TYPE_INTEGER_LITERAL,
235            Self::StringLiteral => DUCKDB_TYPE_DUCKDB_TYPE_STRING_LITERAL,
236            #[cfg(feature = "duckdb-1-5-3")]
237            Self::Geometry => DUCKDB_TYPE_DUCKDB_TYPE_GEOMETRY,
238            #[cfg(feature = "duckdb-1-5-3")]
239            Self::Variant => DUCKDB_TYPE_DUCKDB_TYPE_VARIANT,
240            Self::TimestampTzNs => DUCKDB_TYPE_TIMESTAMP_TZ_NS,
241        }
242    }
243
244    /// Converts a raw `DUCKDB_TYPE` constant into a [`TypeId`], or `None` if the
245    /// value is not one this build knows about.
246    ///
247    /// Recognizes every variant available in the active feature set: all the
248    /// type-enum values of the `DuckDB` 1.4.4 floor (`TIME_NS`, `ANY`,
249    /// `BIGNUM`/`VARINT`, `SQLNULL`, `INTEGER_LITERAL` and `STRING_LITERAL`
250    /// among them, ungated), plus `GEOMETRY` and `VARIANT` when the
251    /// `duckdb-1-5-3` feature is enabled.
252    ///
253    /// **Prefer this over [`from_duckdb_type`][Self::from_duckdb_type] inside
254    /// `DuckDB` callbacks.** An extension routinely sees type values it was not
255    /// built for — a column of a type added in a newer `DuckDB`, or a `GEOMETRY`
256    /// or `VARIANT` column reaching an extension compiled without `duckdb-1-5-3`. Returning `None`
257    /// lets the callback raise a `DuckDB` error, which a panic cannot: quack-rs
258    /// turns a caught panic into an error message, but only when the extension
259    /// ships `panic = "unwind"` — under `panic = "abort"` the process dies.
260    ///
261    /// # Example
262    ///
263    /// ```rust
264    /// use quack_rs::types::TypeId;
265    /// use libduckdb_sys::DUCKDB_TYPE_DUCKDB_TYPE_BIGINT;
266    ///
267    /// assert_eq!(
268    ///     TypeId::try_from_duckdb_type(DUCKDB_TYPE_DUCKDB_TYPE_BIGINT),
269    ///     Some(TypeId::BigInt)
270    /// );
271    /// // A value from a future DuckDB is reported, not fatal.
272    /// assert_eq!(TypeId::try_from_duckdb_type(9999), None);
273    /// ```
274    #[must_use]
275    pub const fn try_from_duckdb_type(raw: DUCKDB_TYPE) -> Option<Self> {
276        // Using if-else chain because match on non-primitive constants is not
277        // allowed in const context.
278        if raw == DUCKDB_TYPE_DUCKDB_TYPE_BOOLEAN {
279            Some(Self::Boolean)
280        } else if raw == DUCKDB_TYPE_DUCKDB_TYPE_TINYINT {
281            Some(Self::TinyInt)
282        } else if raw == DUCKDB_TYPE_DUCKDB_TYPE_SMALLINT {
283            Some(Self::SmallInt)
284        } else if raw == DUCKDB_TYPE_DUCKDB_TYPE_INTEGER {
285            Some(Self::Integer)
286        } else if raw == DUCKDB_TYPE_DUCKDB_TYPE_BIGINT {
287            Some(Self::BigInt)
288        } else if raw == DUCKDB_TYPE_DUCKDB_TYPE_UTINYINT {
289            Some(Self::UTinyInt)
290        } else if raw == DUCKDB_TYPE_DUCKDB_TYPE_USMALLINT {
291            Some(Self::USmallInt)
292        } else if raw == DUCKDB_TYPE_DUCKDB_TYPE_UINTEGER {
293            Some(Self::UInteger)
294        } else if raw == DUCKDB_TYPE_DUCKDB_TYPE_UBIGINT {
295            Some(Self::UBigInt)
296        } else if raw == DUCKDB_TYPE_DUCKDB_TYPE_HUGEINT {
297            Some(Self::HugeInt)
298        } else if raw == DUCKDB_TYPE_DUCKDB_TYPE_FLOAT {
299            Some(Self::Float)
300        } else if raw == DUCKDB_TYPE_DUCKDB_TYPE_DOUBLE {
301            Some(Self::Double)
302        } else if raw == DUCKDB_TYPE_DUCKDB_TYPE_TIMESTAMP {
303            Some(Self::Timestamp)
304        } else if raw == DUCKDB_TYPE_DUCKDB_TYPE_TIMESTAMP_TZ {
305            Some(Self::TimestampTz)
306        } else if raw == DUCKDB_TYPE_DUCKDB_TYPE_DATE {
307            Some(Self::Date)
308        } else if raw == DUCKDB_TYPE_DUCKDB_TYPE_TIME {
309            Some(Self::Time)
310        } else if raw == DUCKDB_TYPE_DUCKDB_TYPE_INTERVAL {
311            Some(Self::Interval)
312        } else if raw == DUCKDB_TYPE_DUCKDB_TYPE_VARCHAR {
313            Some(Self::Varchar)
314        } else if raw == DUCKDB_TYPE_DUCKDB_TYPE_BLOB {
315            Some(Self::Blob)
316        } else if raw == DUCKDB_TYPE_DUCKDB_TYPE_DECIMAL {
317            Some(Self::Decimal)
318        } else if raw == DUCKDB_TYPE_DUCKDB_TYPE_TIMESTAMP_S {
319            Some(Self::TimestampS)
320        } else if raw == DUCKDB_TYPE_DUCKDB_TYPE_TIMESTAMP_MS {
321            Some(Self::TimestampMs)
322        } else if raw == DUCKDB_TYPE_DUCKDB_TYPE_TIMESTAMP_NS {
323            Some(Self::TimestampNs)
324        } else if raw == DUCKDB_TYPE_DUCKDB_TYPE_ENUM {
325            Some(Self::Enum)
326        } else if raw == DUCKDB_TYPE_DUCKDB_TYPE_LIST {
327            Some(Self::List)
328        } else if raw == DUCKDB_TYPE_DUCKDB_TYPE_STRUCT {
329            Some(Self::Struct)
330        } else if raw == DUCKDB_TYPE_DUCKDB_TYPE_MAP {
331            Some(Self::Map)
332        } else if raw == DUCKDB_TYPE_DUCKDB_TYPE_UUID {
333            Some(Self::Uuid)
334        } else if raw == DUCKDB_TYPE_DUCKDB_TYPE_UNION {
335            Some(Self::Union)
336        } else if raw == DUCKDB_TYPE_DUCKDB_TYPE_BIT {
337            Some(Self::Bit)
338        } else if raw == DUCKDB_TYPE_DUCKDB_TYPE_TIME_TZ {
339            Some(Self::TimeTz)
340        } else if raw == DUCKDB_TYPE_DUCKDB_TYPE_UHUGEINT {
341            Some(Self::UHugeInt)
342        } else if raw == DUCKDB_TYPE_DUCKDB_TYPE_ARRAY {
343            Some(Self::Array)
344        } else {
345            Self::try_from_later_duckdb_type(raw)
346        }
347    }
348
349    /// The type-enum values `DuckDB` added after the core set, for
350    /// [`try_from_duckdb_type`][Self::try_from_duckdb_type].
351    const fn try_from_later_duckdb_type(raw: DUCKDB_TYPE) -> Option<Self> {
352        // The first six are defined in libduckdb-sys 1.4.4, this crate's floor.
353        if raw == DUCKDB_TYPE_DUCKDB_TYPE_TIME_NS {
354            return Some(Self::TimeNs);
355        }
356        if raw == DUCKDB_TYPE_DUCKDB_TYPE_ANY {
357            return Some(Self::Any);
358        }
359        if raw == DUCKDB_TYPE_DUCKDB_TYPE_BIGNUM {
360            return Some(Self::Varint);
361        }
362        if raw == DUCKDB_TYPE_DUCKDB_TYPE_SQLNULL {
363            return Some(Self::SqlNull);
364        }
365        if raw == DUCKDB_TYPE_DUCKDB_TYPE_INTEGER_LITERAL {
366            return Some(Self::IntegerLiteral);
367        }
368        if raw == DUCKDB_TYPE_DUCKDB_TYPE_STRING_LITERAL {
369            return Some(Self::StringLiteral);
370        }
371        // DuckDB 2.0.0: a literal, not a bindings constant (see its definition).
372        if raw == DUCKDB_TYPE_TIMESTAMP_TZ_NS {
373            return Some(Self::TimestampTzNs);
374        }
375        // DuckDB 1.5.3+ type-enum values (feature-gated).
376        #[cfg(feature = "duckdb-1-5-3")]
377        {
378            if raw == DUCKDB_TYPE_DUCKDB_TYPE_GEOMETRY {
379                return Some(Self::Geometry);
380            }
381            if raw == DUCKDB_TYPE_DUCKDB_TYPE_VARIANT {
382                return Some(Self::Variant);
383            }
384        }
385        None
386    }
387
388    /// Converts a raw `DUCKDB_TYPE` constant back into a [`TypeId`].
389    ///
390    /// # Panics
391    ///
392    /// Panics if `raw` does not correspond to any `TypeId` variant available in
393    /// the current feature configuration — for example, `GEOMETRY` or `VARIANT`
394    /// when the `duckdb-1-5-3` feature is disabled, or a future/unknown type value.
395    ///
396    /// Inside a `DuckDB` callback use
397    /// [`try_from_duckdb_type`][Self::try_from_duckdb_type] instead: returning
398    /// `None` lets you raise a proper `DuckDB` error, whereas a panic is at best
399    /// caught and reported by quack-rs, and under `panic = "abort"` kills the
400    /// process outright.
401    #[must_use]
402    pub const fn from_duckdb_type(raw: DUCKDB_TYPE) -> Self {
403        match Self::try_from_duckdb_type(raw) {
404            Some(id) => id,
405            None => panic!("unknown DUCKDB_TYPE value"),
406        }
407    }
408
409    /// Names the constructor to use for a type id that carries parameters, or
410    /// `None` for a plain primitive.
411    ///
412    /// See [`is_composite`][Self::is_composite] for why these types are special.
413    ///
414    /// # Example
415    ///
416    /// ```rust
417    /// use quack_rs::types::TypeId;
418    ///
419    /// assert_eq!(
420    ///     TypeId::List.composite_constructor_hint(),
421    ///     Some("LogicalType::list(element_type)")
422    /// );
423    /// assert_eq!(TypeId::BigInt.composite_constructor_hint(), None);
424    /// ```
425    #[must_use]
426    pub const fn composite_constructor_hint(self) -> Option<&'static str> {
427        // `duckdb.h` on `duckdb_create_logical_type`: "Returns an invalid
428        // logical type, if type is: DUCKDB_TYPE_INVALID, DUCKDB_TYPE_DECIMAL,
429        // DUCKDB_TYPE_ENUM, DUCKDB_TYPE_LIST, DUCKDB_TYPE_STRUCT,
430        // DUCKDB_TYPE_MAP, DUCKDB_TYPE_ARRAY, or DUCKDB_TYPE_UNION."
431        //
432        // "Invalid" there means a non-null handle wrapping LogicalTypeId::INVALID
433        // -- verified against DuckDB 1.5.4 -- so a null check does not catch it.
434        // The failure surfaces much later as an opaque
435        // `duckdb_register_*_function failed`, or as a panic from
436        // `LogicalType::get_type_id`.
437        match self {
438            Self::Decimal => Some("LogicalType::decimal(width, scale)"),
439            Self::Enum => Some("LogicalType::enum_type(&members)"),
440            Self::List => Some("LogicalType::list(element_type)"),
441            Self::Struct => Some("LogicalType::struct_type(&fields)"),
442            Self::Map => Some("LogicalType::map(key_type, value_type)"),
443            Self::Array => Some("LogicalType::array(element_type, size)"),
444            Self::Union => Some("LogicalType::union_type(&members)"),
445            _ => None,
446        }
447    }
448
449    /// Returns `true` for the types `duckdb_create_logical_type` cannot build.
450    ///
451    /// `DECIMAL`, `ENUM`, `LIST`, `STRUCT`, `MAP`, `ARRAY` and `UNION` all carry
452    /// parameters — a width, a member list, a child type — that a bare type id
453    /// does not express, so each has its own `duckdb_create_*_type` constructor.
454    /// Passing one of them where a *primitive* type id is expected yields a
455    /// silently invalid type rather than an error, which is why
456    /// [`LogicalType::new`][crate::types::LogicalType::new] and the function
457    /// builders reject them up front.
458    ///
459    /// Use [`composite_constructor_hint`][Self::composite_constructor_hint] to
460    /// name the constructor to use instead, and pass the result through the
461    /// builders' `param_logical` / `returns_logical` methods.
462    ///
463    /// # Example
464    ///
465    /// ```rust
466    /// use quack_rs::types::TypeId;
467    ///
468    /// assert!(TypeId::Struct.is_composite());
469    /// assert!(TypeId::Decimal.is_composite());
470    /// assert!(!TypeId::BigInt.is_composite());
471    /// ```
472    #[must_use]
473    pub const fn is_composite(self) -> bool {
474        self.composite_constructor_hint().is_some()
475    }
476
477    /// Returns a human-readable SQL type name for this `TypeId`.
478    ///
479    /// # Example
480    ///
481    /// ```rust
482    /// use quack_rs::types::TypeId;
483    ///
484    /// assert_eq!(TypeId::BigInt.sql_name(), "BIGINT");
485    /// assert_eq!(TypeId::Varchar.sql_name(), "VARCHAR");
486    /// ```
487    #[must_use]
488    pub const fn sql_name(self) -> &'static str {
489        match self {
490            Self::Boolean => "BOOLEAN",
491            Self::TinyInt => "TINYINT",
492            Self::SmallInt => "SMALLINT",
493            Self::Integer => "INTEGER",
494            Self::BigInt => "BIGINT",
495            Self::UTinyInt => "UTINYINT",
496            Self::USmallInt => "USMALLINT",
497            Self::UInteger => "UINTEGER",
498            Self::UBigInt => "UBIGINT",
499            Self::HugeInt => "HUGEINT",
500            Self::Float => "FLOAT",
501            Self::Double => "DOUBLE",
502            Self::Timestamp => "TIMESTAMP",
503            Self::TimestampTz => "TIMESTAMPTZ",
504            Self::Date => "DATE",
505            Self::Time => "TIME",
506            Self::Interval => "INTERVAL",
507            Self::Varchar => "VARCHAR",
508            Self::Blob => "BLOB",
509            Self::Decimal => "DECIMAL",
510            Self::TimestampS => "TIMESTAMP_S",
511            Self::TimestampMs => "TIMESTAMP_MS",
512            Self::TimestampNs => "TIMESTAMP_NS",
513            Self::Enum => "ENUM",
514            Self::List => "LIST",
515            Self::Struct => "STRUCT",
516            Self::Map => "MAP",
517            Self::Uuid => "UUID",
518            Self::Union => "UNION",
519            Self::Bit => "BIT",
520            Self::TimeTz => "TIMETZ",
521            Self::UHugeInt => "UHUGEINT",
522            Self::Array => "ARRAY",
523            Self::TimeNs => "TIME_NS",
524            Self::Any => "ANY",
525            Self::Varint => "BIGNUM",
526            Self::SqlNull => "SQLNULL",
527            Self::IntegerLiteral => "INTEGER_LITERAL",
528            Self::StringLiteral => "STRING_LITERAL",
529            #[cfg(feature = "duckdb-1-5-3")]
530            Self::Geometry => "GEOMETRY",
531            #[cfg(feature = "duckdb-1-5-3")]
532            Self::Variant => "VARIANT",
533            Self::TimestampTzNs => "TIMESTAMPTZ_NS",
534        }
535    }
536}
537
538impl std::fmt::Display for TypeId {
539    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
540        f.write_str(self.sql_name())
541    }
542}
543
544#[cfg(test)]
545mod tests {
546    // `composite_constructor_hint` is the one place the crate tells a user how
547    // to build a type `duckdb_create_logical_type` refuses. A wrong or missing
548    // arm turns a precise diagnostic into a generic one, and nothing else in
549    // the suite reads the arms individually, so pin every one of them.
550
551    #[test]
552    fn every_composite_type_names_its_own_constructor() {
553        for (type_id, expected) in [
554            (TypeId::Decimal, "LogicalType::decimal(width, scale)"),
555            (TypeId::Enum, "LogicalType::enum_type(&members)"),
556            (TypeId::List, "LogicalType::list(element_type)"),
557            (TypeId::Struct, "LogicalType::struct_type(&fields)"),
558            (TypeId::Map, "LogicalType::map(key_type, value_type)"),
559            (TypeId::Array, "LogicalType::array(element_type, size)"),
560            (TypeId::Union, "LogicalType::union_type(&members)"),
561        ] {
562            assert_eq!(
563                type_id.composite_constructor_hint(),
564                Some(expected),
565                "{type_id:?} must name its own constructor"
566            );
567            assert!(type_id.is_composite(), "{type_id:?} is composite");
568        }
569    }
570
571    #[test]
572    fn primitive_types_have_no_constructor_hint_and_are_not_composite() {
573        // The set `duckdb.h` names is exactly the seven above; everything else
574        // `duckdb_create_logical_type` builds directly.
575        for type_id in [
576            TypeId::Boolean,
577            TypeId::TinyInt,
578            TypeId::SmallInt,
579            TypeId::Integer,
580            TypeId::BigInt,
581            TypeId::HugeInt,
582            TypeId::Float,
583            TypeId::Double,
584            TypeId::Varchar,
585            TypeId::Blob,
586            TypeId::Date,
587            TypeId::Time,
588            TypeId::Timestamp,
589            TypeId::Interval,
590            TypeId::Uuid,
591        ] {
592            assert_eq!(
593                type_id.composite_constructor_hint(),
594                None,
595                "{type_id:?} is primitive"
596            );
597            assert!(!type_id.is_composite(), "{type_id:?} is not composite");
598        }
599    }
600
601    use super::*;
602
603    #[test]
604    fn all_types_round_trip_display() {
605        let types = [
606            TypeId::Boolean,
607            TypeId::TinyInt,
608            TypeId::SmallInt,
609            TypeId::Integer,
610            TypeId::BigInt,
611            TypeId::UTinyInt,
612            TypeId::USmallInt,
613            TypeId::UInteger,
614            TypeId::UBigInt,
615            TypeId::HugeInt,
616            TypeId::Float,
617            TypeId::Double,
618            TypeId::Timestamp,
619            TypeId::TimestampTz,
620            TypeId::Date,
621            TypeId::Time,
622            TypeId::Interval,
623            TypeId::Varchar,
624            TypeId::Blob,
625            TypeId::Decimal,
626            TypeId::TimestampS,
627            TypeId::TimestampMs,
628            TypeId::TimestampNs,
629            TypeId::Enum,
630            TypeId::List,
631            TypeId::Struct,
632            TypeId::Map,
633            TypeId::Uuid,
634            TypeId::Union,
635            TypeId::Bit,
636            TypeId::TimeTz,
637            TypeId::UHugeInt,
638            TypeId::Array,
639            TypeId::TimeNs,
640            TypeId::Any,
641            TypeId::Varint,
642            TypeId::SqlNull,
643            TypeId::IntegerLiteral,
644            TypeId::StringLiteral,
645            #[cfg(feature = "duckdb-1-5-3")]
646            TypeId::Geometry,
647            #[cfg(feature = "duckdb-1-5-3")]
648            TypeId::Variant,
649            TypeId::TimestampTzNs,
650        ];
651        for t in types {
652            // sql_name should not be empty and should match Display
653            assert_ne!(t.sql_name(), "");
654            assert_eq!(t.sql_name(), format!("{t}"));
655        }
656    }
657
658    #[test]
659    fn bigint_maps_to_correct_duckdb_type() {
660        assert_eq!(
661            TypeId::BigInt.to_duckdb_type(),
662            DUCKDB_TYPE_DUCKDB_TYPE_BIGINT
663        );
664    }
665
666    #[test]
667    fn boolean_maps_to_correct_duckdb_type() {
668        assert_eq!(
669            TypeId::Boolean.to_duckdb_type(),
670            DUCKDB_TYPE_DUCKDB_TYPE_BOOLEAN
671        );
672    }
673
674    #[test]
675    fn timestamp_maps_to_correct_duckdb_type() {
676        assert_eq!(
677            TypeId::Timestamp.to_duckdb_type(),
678            DUCKDB_TYPE_DUCKDB_TYPE_TIMESTAMP
679        );
680    }
681
682    #[test]
683    fn varchar_maps_to_correct_duckdb_type() {
684        assert_eq!(
685            TypeId::Varchar.to_duckdb_type(),
686            DUCKDB_TYPE_DUCKDB_TYPE_VARCHAR
687        );
688    }
689
690    #[test]
691    fn type_id_clone_copy() {
692        let t = TypeId::Integer;
693        let t2 = t; // Copy
694        assert_eq!(t, t2);
695        let t3 = t;
696        assert_eq!(t, t3);
697    }
698
699    #[test]
700    fn type_id_debug() {
701        let s = format!("{:?}", TypeId::Interval);
702        assert!(s.contains("Interval"));
703    }
704
705    // ---- Type ids added after the original set (all present from DuckDB 1.4.0) ----
706
707    #[test]
708    fn time_ns_maps_to_correct_duckdb_type() {
709        assert_eq!(
710            TypeId::TimeNs.to_duckdb_type(),
711            DUCKDB_TYPE_DUCKDB_TYPE_TIME_NS
712        );
713    }
714
715    #[test]
716    fn any_maps_to_correct_duckdb_type() {
717        assert_eq!(TypeId::Any.to_duckdb_type(), DUCKDB_TYPE_DUCKDB_TYPE_ANY);
718    }
719
720    #[test]
721    fn varint_maps_to_correct_duckdb_type() {
722        assert_eq!(
723            TypeId::Varint.to_duckdb_type(),
724            DUCKDB_TYPE_DUCKDB_TYPE_BIGNUM
725        );
726    }
727
728    #[test]
729    fn sql_null_maps_to_correct_duckdb_type() {
730        assert_eq!(
731            TypeId::SqlNull.to_duckdb_type(),
732            DUCKDB_TYPE_DUCKDB_TYPE_SQLNULL
733        );
734    }
735
736    #[test]
737    fn later_type_id_variants_sql_names() {
738        assert_eq!(TypeId::TimeNs.sql_name(), "TIME_NS");
739        assert_eq!(TypeId::Any.sql_name(), "ANY");
740        assert_eq!(TypeId::Varint.sql_name(), "BIGNUM");
741        assert_eq!(TypeId::SqlNull.sql_name(), "SQLNULL");
742        assert_eq!(TypeId::IntegerLiteral.sql_name(), "INTEGER_LITERAL");
743        assert_eq!(TypeId::StringLiteral.sql_name(), "STRING_LITERAL");
744    }
745
746    #[test]
747    fn later_type_id_variants_display_matches_sql_name() {
748        assert_eq!(format!("{}", TypeId::TimeNs), "TIME_NS");
749        assert_eq!(format!("{}", TypeId::Any), "ANY");
750        assert_eq!(format!("{}", TypeId::Varint), "BIGNUM");
751        assert_eq!(format!("{}", TypeId::SqlNull), "SQLNULL");
752        assert_eq!(format!("{}", TypeId::IntegerLiteral), "INTEGER_LITERAL");
753        assert_eq!(format!("{}", TypeId::StringLiteral), "STRING_LITERAL");
754    }
755
756    #[test]
757    fn later_type_id_variants_hash_eq() {
758        use std::collections::HashSet;
759        let mut set = HashSet::new();
760        set.insert(TypeId::TimeNs);
761        set.insert(TypeId::Any);
762        set.insert(TypeId::Varint);
763        set.insert(TypeId::SqlNull);
764        set.insert(TypeId::IntegerLiteral);
765        set.insert(TypeId::StringLiteral);
766        assert_eq!(set.len(), 6);
767        assert!(set.contains(&TypeId::TimeNs));
768        assert!(set.contains(&TypeId::Any));
769        assert!(set.contains(&TypeId::Varint));
770        assert!(set.contains(&TypeId::SqlNull));
771        assert!(set.contains(&TypeId::IntegerLiteral));
772        assert!(set.contains(&TypeId::StringLiteral));
773    }
774
775    #[test]
776    fn integer_literal_maps_to_correct_duckdb_type() {
777        assert_eq!(
778            TypeId::IntegerLiteral.to_duckdb_type(),
779            DUCKDB_TYPE_DUCKDB_TYPE_INTEGER_LITERAL
780        );
781    }
782
783    #[test]
784    fn string_literal_maps_to_correct_duckdb_type() {
785        assert_eq!(
786            TypeId::StringLiteral.to_duckdb_type(),
787            DUCKDB_TYPE_DUCKDB_TYPE_STRING_LITERAL
788        );
789    }
790
791    /// Every `TypeId` variant available in the active feature set.
792    fn all_type_ids() -> Vec<TypeId> {
793        vec![
794            TypeId::Boolean,
795            TypeId::TinyInt,
796            TypeId::SmallInt,
797            TypeId::Integer,
798            TypeId::BigInt,
799            TypeId::UTinyInt,
800            TypeId::USmallInt,
801            TypeId::UInteger,
802            TypeId::UBigInt,
803            TypeId::HugeInt,
804            TypeId::Float,
805            TypeId::Double,
806            TypeId::Timestamp,
807            TypeId::TimestampTz,
808            TypeId::Date,
809            TypeId::Time,
810            TypeId::Interval,
811            TypeId::Varchar,
812            TypeId::Blob,
813            TypeId::Decimal,
814            TypeId::TimestampS,
815            TypeId::TimestampMs,
816            TypeId::TimestampNs,
817            TypeId::Enum,
818            TypeId::List,
819            TypeId::Struct,
820            TypeId::Map,
821            TypeId::Uuid,
822            TypeId::Union,
823            TypeId::Bit,
824            TypeId::TimeTz,
825            TypeId::UHugeInt,
826            TypeId::Array,
827            // Later type ids: from_duckdb_type must handle these too
828            // (previously it panicked on them — see the panic-gap fix).
829            TypeId::TimeNs,
830            TypeId::Any,
831            TypeId::Varint,
832            TypeId::SqlNull,
833            TypeId::IntegerLiteral,
834            TypeId::StringLiteral,
835            #[cfg(feature = "duckdb-1-5-3")]
836            TypeId::Geometry,
837            #[cfg(feature = "duckdb-1-5-3")]
838            TypeId::Variant,
839            TypeId::TimestampTzNs,
840        ]
841    }
842
843    /// `DUCKDB_TYPE_TIMESTAMP_TZ_NS` is 42 in `DuckDB` 2.0.0's `duckdb.h`. The
844    /// number is part of the stable C ABI, so it is pinned here: the constant
845    /// is a literal, with no bindings constant to be checked against on a
846    /// 1.x build. 42 follows `GEOMETRY` (40) and `VARIANT` (41).
847    #[test]
848    fn timestamp_tz_ns_is_type_42_and_named_like_duckdb_names_it() {
849        assert_eq!(TypeId::TimestampTzNs.to_duckdb_type(), 42);
850        assert_eq!(
851            TypeId::try_from_duckdb_type(42),
852            Some(TypeId::TimestampTzNs)
853        );
854        assert_eq!(TypeId::TimestampTzNs.sql_name(), "TIMESTAMPTZ_NS");
855        assert_eq!(TypeId::from_duckdb_type(42), TypeId::TimestampTzNs);
856    }
857
858    #[test]
859    fn try_from_duckdb_type_reports_unknown_values() {
860        // Values DuckDB has never used, and values a future DuckDB might.
861        for raw in [9999u32, 200, 100, u32::MAX] {
862            assert_eq!(
863                TypeId::try_from_duckdb_type(raw),
864                None,
865                "raw {raw} must not resolve to a TypeId"
866            );
867        }
868    }
869
870    #[test]
871    fn try_from_duckdb_type_agrees_with_to_duckdb_type() {
872        for id in all_type_ids() {
873            assert_eq!(TypeId::try_from_duckdb_type(id.to_duckdb_type()), Some(id));
874        }
875    }
876
877    #[test]
878    #[should_panic(expected = "unknown DUCKDB_TYPE value")]
879    fn from_duckdb_type_still_panics_on_unknown() {
880        let _ = TypeId::from_duckdb_type(9999);
881    }
882
883    #[test]
884    fn from_duckdb_type_roundtrip() {
885        let variants = all_type_ids();
886        for &tid in &variants {
887            let raw = tid.to_duckdb_type();
888            let back = TypeId::from_duckdb_type(raw);
889            assert_eq!(back, tid, "roundtrip failed for {tid:?}");
890        }
891    }
892
893    #[cfg(feature = "duckdb-1-5-3")]
894    #[test]
895    fn geometry_maps_to_correct_duckdb_type() {
896        assert_eq!(
897            TypeId::Geometry.to_duckdb_type(),
898            DUCKDB_TYPE_DUCKDB_TYPE_GEOMETRY
899        );
900    }
901
902    #[cfg(feature = "duckdb-1-5-3")]
903    #[test]
904    fn variant_maps_to_correct_duckdb_type() {
905        assert_eq!(
906            TypeId::Variant.to_duckdb_type(),
907            DUCKDB_TYPE_DUCKDB_TYPE_VARIANT
908        );
909    }
910
911    #[cfg(feature = "duckdb-1-5-3")]
912    #[test]
913    fn geometry_variant_sql_names_and_display() {
914        assert_eq!(TypeId::Geometry.sql_name(), "GEOMETRY");
915        assert_eq!(TypeId::Variant.sql_name(), "VARIANT");
916        assert_eq!(format!("{}", TypeId::Geometry), "GEOMETRY");
917        assert_eq!(format!("{}", TypeId::Variant), "VARIANT");
918    }
919}