quack_rs/types/logical_type.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//! RAII wrapper for `duckdb_logical_type`.
7//!
8//! # Pitfall L7: `LogicalType` memory leak
9//!
10//! Every `duckdb_create_logical_type` call allocates memory that must be freed
11//! with `duckdb_destroy_logical_type`. Forgetting to call the destructor leaks
12//! memory. [`LogicalType`] implements `Drop` to prevent this.
13
14mod construct;
15
16pub use construct::MAX_UNION_MEMBERS;
17
18/// Checks one builder slot's [`TypeId`]: [`LogicalType::check_slot`] when
19/// registering, `check_slot_offline` in
20/// [`MockRegistrar`][crate::testing::MockRegistrar]. Each builder's
21/// `check_types` takes one, so both run the same sequence of checks.
22pub(crate) type SlotCheck = fn(TypeId, &str) -> Result<(), crate::error::ExtensionError>;
23
24use crate::types::TypeId;
25use libduckdb_sys::{
26 duckdb_array_type_array_size, duckdb_array_type_child_type, duckdb_decimal_internal_type,
27 duckdb_decimal_scale, duckdb_decimal_width, duckdb_destroy_logical_type,
28 duckdb_enum_dictionary_size, duckdb_enum_dictionary_value, duckdb_enum_internal_type,
29 duckdb_free, duckdb_get_type_id, duckdb_list_type_child_type, duckdb_logical_type,
30 duckdb_logical_type_get_alias, duckdb_logical_type_set_alias, duckdb_map_type_key_type,
31 duckdb_map_type_value_type, duckdb_struct_type_child_count, duckdb_struct_type_child_name,
32 duckdb_struct_type_child_type, duckdb_union_type_member_count, duckdb_union_type_member_name,
33 duckdb_union_type_member_type,
34};
35use std::fmt;
36
37/// Error returned by the fallible [`LogicalType`] constructors.
38///
39/// Two things go wrong when building a logical type, and this reports both:
40///
41/// - the underlying `DuckDB` C API returned a null pointer (an out-of-range
42/// `DECIMAL` width, for instance), or
43/// - the requested type could not be built from a bare [`TypeId`] at all — see
44/// [`TypeId::is_composite`][crate::types::TypeId::is_composite].
45#[derive(Debug, Clone)]
46pub struct LogicalTypeError {
47 api_func: &'static str,
48 /// When set, the whole message; otherwise `"<api_func> returned null"`.
49 detail: Option<String>,
50}
51
52impl LogicalTypeError {
53 /// The `DuckDB` C API function (or internal step) that failed.
54 #[must_use]
55 pub const fn api_func(&self) -> &'static str {
56 self.api_func
57 }
58
59 /// Builds the "returned null" form.
60 const fn null(api_func: &'static str) -> Self {
61 Self {
62 api_func,
63 detail: None,
64 }
65 }
66
67 /// Builds an error whose message is `detail`.
68 const fn with_detail(api_func: &'static str, detail: String) -> Self {
69 Self {
70 api_func,
71 detail: Some(detail),
72 }
73 }
74}
75
76impl fmt::Display for LogicalTypeError {
77 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
78 match &self.detail {
79 Some(detail) => f.write_str(detail),
80 None => write!(f, "{} returned null", self.api_func),
81 }
82 }
83}
84
85impl std::error::Error for LogicalTypeError {}
86
87/// The diagnostic for a composite [`TypeId`] used where a primitive was needed.
88///
89/// Shared by [`LogicalType::new`]'s panic, [`LogicalType::try_new`]'s error, and
90/// every builder that turns a `TypeId` into a parameter or return type, so the
91/// advice is identical wherever the mistake is caught.
92fn composite_message(type_id: TypeId) -> String {
93 let hint = type_id
94 .composite_constructor_hint()
95 .unwrap_or("a dedicated LogicalType constructor");
96 format!(
97 "{} carries parameters that a bare TypeId cannot express, so \
98 duckdb_create_logical_type would return an invalid (non-null) type. \
99 Build it with {hint} and pass the result through the `*_logical` \
100 variant of this method (`param_logical` / `returns_logical` / \
101 `varargs_logical` on a function builder, \
102 `CastFunctionBuilder::new_logical` for a cast).",
103 type_id.sql_name()
104 )
105}
106
107/// An RAII wrapper around a `duckdb_logical_type` handle.
108///
109/// Created from a [`TypeId`], this type ensures `duckdb_destroy_logical_type`
110/// is called when it is dropped. This prevents the memory leak described in
111/// [Pitfall L7](https://github.com/tomtom215/quack-rs/blob/main/LESSONS.md).
112///
113/// # Example
114///
115/// ```rust,no_run
116/// use quack_rs::types::{LogicalType, TypeId};
117///
118/// // Requires DuckDB runtime to be initialized (i.e., loaded as an extension).
119/// let lt = LogicalType::new(TypeId::BigInt);
120/// // `lt` is automatically destroyed when it goes out of scope
121/// ```
122pub struct LogicalType {
123 inner: duckdb_logical_type,
124}
125
126impl LogicalType {
127 /// Creates a `LogicalType` from an existing raw `duckdb_logical_type` handle.
128 ///
129 /// The returned `LogicalType` takes ownership of the handle and will call
130 /// `duckdb_destroy_logical_type` when dropped.
131 ///
132 /// # Safety
133 ///
134 /// - `ptr` must be a valid, non-null `duckdb_logical_type` handle returned by
135 /// a `duckdb_create_*` function (e.g. `duckdb_create_logical_type`,
136 /// `duckdb_create_list_type`, `duckdb_create_struct_type`, etc.).
137 /// - The caller must not call `duckdb_destroy_logical_type` on the handle
138 /// after passing it to this function.
139 /// - The handle must not be used after this call except through the returned
140 /// `LogicalType`.
141 ///
142 /// # Panics
143 ///
144 /// Panics if `ptr` is null.
145 #[must_use]
146 pub unsafe fn from_raw(ptr: duckdb_logical_type) -> Self {
147 assert!(
148 !ptr.is_null(),
149 "LogicalType::from_raw called with null pointer"
150 );
151 Self { inner: ptr }
152 }
153
154 /// Fallible version of [`LogicalType::set_alias`]. Returns an error instead
155 /// of panicking if `alias` contains an interior null byte.
156 ///
157 /// # Safety
158 ///
159 /// `self` must wrap a valid `duckdb_logical_type`.
160 pub unsafe fn try_set_alias(&self, alias: &str) -> Result<(), LogicalTypeError> {
161 let c_alias = std::ffi::CString::new(alias)
162 .map_err(|_| LogicalTypeError::null("CString::new (alias contains null byte)"))?;
163 // SAFETY: self.inner is valid per the caller's contract; c_alias outlives the call.
164 unsafe { duckdb_logical_type_set_alias(self.inner, c_alias.as_ptr()) };
165 Ok(())
166 }
167
168 // ------------------------------------------------------------------
169 // Introspection methods
170 // ------------------------------------------------------------------
171
172 /// Returns the [`TypeId`] of this logical type.
173 ///
174 /// # Panics
175 ///
176 /// Panics if `DuckDB` reports a type this build of quack-rs has no variant
177 /// for — for example `GEOMETRY` or `VARIANT` without the `duckdb-1-5-3`
178 /// feature, or a type added by a newer `DuckDB`. Inside a callback, where
179 /// the type comes from the query, prefer
180 /// [`try_get_type_id`][Self::try_get_type_id].
181 ///
182 /// # Safety
183 ///
184 /// The inner handle must be valid (requires `DuckDB` runtime).
185 #[must_use]
186 pub unsafe fn get_type_id(&self) -> TypeId {
187 // SAFETY: `self.inner` is a non-null handle this value owns and keeps live until
188 // `Drop` (type invariant: `owned_or` rejects null, `from_raw` asserts it).
189 // `duckdb_get_type_id` only reads the type's id.
190 TypeId::from_duckdb_type(unsafe { duckdb_get_type_id(self.inner) })
191 }
192
193 /// Returns the [`TypeId`] of this logical type, or `None` if this build of
194 /// quack-rs has no variant for it (see [`get_type_id`][Self::get_type_id]).
195 ///
196 /// # Safety
197 ///
198 /// The inner handle must be valid (requires `DuckDB` runtime).
199 #[must_use]
200 pub unsafe fn try_get_type_id(&self) -> Option<TypeId> {
201 // SAFETY: `self.inner` is a non-null handle this value owns and keeps live until
202 // `Drop` (type invariant: `owned_or` rejects null, `from_raw` asserts it).
203 // `duckdb_get_type_id` only reads the type's id.
204 TypeId::try_from_duckdb_type(unsafe { duckdb_get_type_id(self.inner) })
205 }
206
207 /// Returns the alias of this logical type, or `None` if no alias is set.
208 ///
209 /// # Safety
210 ///
211 /// The inner handle must be valid (requires `DuckDB` runtime).
212 #[must_use]
213 pub unsafe fn get_alias(&self) -> Option<String> {
214 // SAFETY: `self.inner` is a non-null handle this value owns and keeps live until
215 // `Drop` (type invariant: `owned_or` rejects null, `from_raw` asserts it).
216 // `duckdb_logical_type_get_alias` dereferences it unconditionally and returns a
217 // `strdup` copy of the alias or null (logical_types-c.cpp).
218 let ptr = unsafe { duckdb_logical_type_get_alias(self.inner) };
219 if ptr.is_null() {
220 return None;
221 }
222 // SAFETY: `ptr` was checked non-null just above and is a `strdup` result, so it is
223 // NUL-terminated; it stays allocated until the `duckdb_free` below.
224 let s = unsafe { std::ffi::CStr::from_ptr(ptr) }
225 .to_string_lossy()
226 .into_owned();
227 // SAFETY: `ptr` is the non-null `strdup` allocation DuckDB handed us (duckdb.h:
228 // free with `duckdb_free`, which is `free`); `s` already holds an owned copy, and
229 // this is the only free.
230 unsafe { duckdb_free(ptr.cast::<core::ffi::c_void>()) };
231 Some(s)
232 }
233
234 /// Sets an alias on this logical type.
235 ///
236 /// # Safety
237 ///
238 /// The inner handle must be valid (requires `DuckDB` runtime).
239 ///
240 /// # Panics
241 ///
242 /// Panics if `alias` contains an interior null byte.
243 pub unsafe fn set_alias(&self, alias: &str) {
244 let c_alias = std::ffi::CString::new(alias).expect("alias must not contain null bytes");
245 // SAFETY: `self.inner` is a non-null handle this value owns and keeps live until
246 // `Drop` (type invariant: `owned_or` rejects null, `from_raw` asserts it).
247 // `c_alias` is a NUL-terminated `CString` that outlives the call, and
248 // `LogicalType::SetAlias(string)` copies it, so no pointer is retained.
249 unsafe { duckdb_logical_type_set_alias(self.inner, c_alias.as_ptr()) };
250 }
251
252 /// Returns the width (total digits) of a `DECIMAL` type.
253 ///
254 /// # Safety
255 ///
256 /// The inner handle must be a `DECIMAL` logical type (requires `DuckDB` runtime).
257 #[must_use]
258 pub unsafe fn decimal_width(&self) -> u8 {
259 // SAFETY: `self.inner` is a non-null handle this value owns and keeps live until
260 // `Drop` (type invariant: `owned_or` rejects null, `from_raw` asserts it).
261 // `duckdb_decimal_width` checks the id itself and returns 0 for a non-DECIMAL type
262 // (logical_types-c.cpp), so a type of another kind is not UB here.
263 unsafe { duckdb_decimal_width(self.inner) }
264 }
265
266 /// Returns the scale (digits after decimal point) of a `DECIMAL` type.
267 ///
268 /// # Safety
269 ///
270 /// The inner handle must be a `DECIMAL` logical type (requires `DuckDB` runtime).
271 #[must_use]
272 pub unsafe fn decimal_scale(&self) -> u8 {
273 // SAFETY: `self.inner` is a non-null handle this value owns and keeps live until
274 // `Drop` (type invariant: `owned_or` rejects null, `from_raw` asserts it).
275 // `duckdb_decimal_scale` checks the id itself and returns 0 for a non-DECIMAL type
276 // (logical_types-c.cpp), so a type of another kind is not UB here.
277 unsafe { duckdb_decimal_scale(self.inner) }
278 }
279
280 /// Returns the internal storage type of a `DECIMAL` type.
281 ///
282 /// # Safety
283 ///
284 /// The inner handle must be a `DECIMAL` logical type (requires `DuckDB` runtime).
285 #[must_use]
286 pub unsafe fn decimal_internal_type(&self) -> TypeId {
287 // SAFETY: `self.inner` is a non-null handle this value owns and keeps live until
288 // `Drop` (type invariant: `owned_or` rejects null, `from_raw` asserts it).
289 // `duckdb_decimal_internal_type` checks the id itself and returns INVALID for a
290 // non-DECIMAL type (logical_types-c.cpp), so a type of another kind is not UB here.
291 TypeId::from_duckdb_type(unsafe { duckdb_decimal_internal_type(self.inner) })
292 }
293
294 /// Returns the internal storage type of an `ENUM` type.
295 ///
296 /// # Safety
297 ///
298 /// The inner handle must be an `ENUM` logical type (requires `DuckDB` runtime).
299 #[must_use]
300 pub unsafe fn enum_internal_type(&self) -> TypeId {
301 // SAFETY: `self.inner` is a non-null handle this value owns and keeps live until
302 // `Drop` (type invariant: `owned_or` rejects null, `from_raw` asserts it).
303 // `duckdb_enum_internal_type` checks the id itself and returns INVALID for a
304 // non-ENUM type (logical_types-c.cpp), so a type of another kind is not UB here.
305 TypeId::from_duckdb_type(unsafe { duckdb_enum_internal_type(self.inner) })
306 }
307
308 /// Returns the number of members in an `ENUM` type.
309 ///
310 /// # Safety
311 ///
312 /// The inner handle must be an `ENUM` logical type (requires `DuckDB` runtime).
313 #[must_use]
314 pub unsafe fn enum_dictionary_size(&self) -> u32 {
315 // SAFETY: `self.inner` is a non-null handle this value owns and keeps live until
316 // `Drop` (type invariant: `owned_or` rejects null, `from_raw` asserts it).
317 // `duckdb_enum_dictionary_size` checks the id itself and returns 0 for a non-ENUM
318 // type (logical_types-c.cpp), so a type of another kind is not UB here.
319 unsafe { duckdb_enum_dictionary_size(self.inner) }
320 }
321
322 /// Returns the name of the enum member at `index`.
323 ///
324 /// # Safety
325 ///
326 /// The inner handle must be an `ENUM` logical type and `index` must be
327 /// within bounds (requires `DuckDB` runtime).
328 ///
329 /// # Panics
330 ///
331 /// Panics if `duckdb_enum_dictionary_value` returns a null pointer.
332 #[must_use]
333 pub unsafe fn enum_dictionary_value(&self, index: u64) -> String {
334 // SAFETY: `self.inner` is a non-null handle this value owns and keeps live until
335 // `Drop` (type invariant: `owned_or` rejects null, `from_raw` asserts it).
336 // `duckdb_enum_dictionary_value` returns null for a non-ENUM type (asserted below)
337 // and does not bounds-check `index`; this function's `# Safety` clause requires
338 // `index` to be within the dictionary.
339 let ptr =
340 unsafe { duckdb_enum_dictionary_value(self.inner, index as libduckdb_sys::idx_t) };
341 assert!(!ptr.is_null(), "duckdb_enum_dictionary_value returned null");
342 // SAFETY: `ptr` is non-null (asserted on the line above) and is a `strdup` result,
343 // so it is NUL-terminated; it stays allocated until the free below.
344 let s = unsafe { std::ffi::CStr::from_ptr(ptr) }
345 .to_string_lossy()
346 .into_owned();
347 // SAFETY: `ptr` is the non-null `strdup` allocation DuckDB handed us (duckdb.h:
348 // free with `duckdb_free`, which is `free`); `s` already holds an owned copy, and
349 // this is the only free.
350 unsafe { duckdb_free(ptr.cast::<core::ffi::c_void>()) };
351 s
352 }
353
354 /// Returns the child (element) type of a `LIST` type.
355 ///
356 /// # Safety
357 ///
358 /// The inner handle must be a `LIST` logical type (requires `DuckDB` runtime).
359 #[must_use]
360 pub unsafe fn list_child_type(&self) -> Self {
361 // SAFETY: `self.inner` is a non-null handle this value owns and keeps live until
362 // `Drop` (type invariant: `owned_or` rejects null, `from_raw` asserts it).
363 // `duckdb_list_type_child_type` returns null for a non-LIST/MAP type, which
364 // `from_raw`'s assert turns into a panic; otherwise it returns a fresh heap `new
365 // LogicalType(..)` the caller owns (duckdb.h: "must be freed with
366 // `duckdb_destroy_logical_type`"), satisfying `from_raw`'s ownership clause.
367 unsafe { Self::from_raw(duckdb_list_type_child_type(self.inner)) }
368 }
369
370 /// Returns the key type of a `MAP` type.
371 ///
372 /// # Safety
373 ///
374 /// The inner handle must be a `MAP` logical type (requires `DuckDB` runtime).
375 #[must_use]
376 pub unsafe fn map_key_type(&self) -> Self {
377 // SAFETY: `self.inner` is a non-null handle this value owns and keeps live until
378 // `Drop` (type invariant: `owned_or` rejects null, `from_raw` asserts it).
379 // `duckdb_map_type_key_type` returns null for a non-MAP type, which `from_raw`'s
380 // assert turns into a panic; otherwise it returns a fresh heap `new
381 // LogicalType(..)` the caller owns (duckdb.h: "must be freed with
382 // `duckdb_destroy_logical_type`"), satisfying `from_raw`'s ownership clause.
383 unsafe { Self::from_raw(duckdb_map_type_key_type(self.inner)) }
384 }
385
386 /// Returns the value type of a `MAP` type.
387 ///
388 /// # Safety
389 ///
390 /// The inner handle must be a `MAP` logical type (requires `DuckDB` runtime).
391 #[must_use]
392 pub unsafe fn map_value_type(&self) -> Self {
393 // SAFETY: `self.inner` is a non-null handle this value owns and keeps live until
394 // `Drop` (type invariant: `owned_or` rejects null, `from_raw` asserts it).
395 // `duckdb_map_type_value_type` returns null for a non-MAP type, which `from_raw`'s
396 // assert turns into a panic; otherwise it returns a fresh heap `new
397 // LogicalType(..)` the caller owns (duckdb.h: "must be freed with
398 // `duckdb_destroy_logical_type`"), satisfying `from_raw`'s ownership clause.
399 unsafe { Self::from_raw(duckdb_map_type_value_type(self.inner)) }
400 }
401
402 /// Returns the number of child fields in a `STRUCT` type.
403 ///
404 /// # Safety
405 ///
406 /// The inner handle must be a `STRUCT` logical type (requires `DuckDB` runtime).
407 #[must_use]
408 pub unsafe fn struct_child_count(&self) -> u64 {
409 // SAFETY: `self.inner` is a non-null handle this value owns and keeps live until
410 // `Drop` (type invariant: `owned_or` rejects null, `from_raw` asserts it).
411 // `duckdb_struct_type_child_count` checks the physical type itself and returns 0
412 // for a non-STRUCT type (logical_types-c.cpp), so a type of another kind is not UB
413 // here.
414 unsafe { duckdb_struct_type_child_count(self.inner) as u64 }
415 }
416
417 /// Returns the name of the struct field at `index`.
418 ///
419 /// # Safety
420 ///
421 /// The inner handle must be a `STRUCT` logical type and `index` must be
422 /// within bounds (requires `DuckDB` runtime).
423 ///
424 /// # Panics
425 ///
426 /// Panics if `duckdb_struct_type_child_name` returns a null pointer.
427 #[must_use]
428 pub unsafe fn struct_child_name(&self, index: u64) -> String {
429 // SAFETY: `self.inner` is a non-null handle this value owns and keeps live until
430 // `Drop` (type invariant: `owned_or` rejects null, `from_raw` asserts it). `index`
431 // is in bounds per this function's `# Safety` clause:
432 // `duckdb_struct_type_child_name` does not check it (the `*Type::Get*Name` helpers
433 // in types.cpp only `D_ASSERT` it). A wrong-kind type yields null. The result is
434 // checked non-null by the assert before `CStr::from_ptr`; it is a `strdup` copy, so
435 // NUL-terminated and ours to release with `duckdb_free` (which is `free`,
436 // helper-c.cpp), exactly once, after `to_string_lossy().into_owned()` has copied
437 // it.
438 unsafe {
439 let ptr = duckdb_struct_type_child_name(self.inner, index as libduckdb_sys::idx_t);
440 assert!(
441 !ptr.is_null(),
442 "duckdb_struct_type_child_name returned null"
443 );
444 let s = std::ffi::CStr::from_ptr(ptr).to_string_lossy().into_owned();
445 duckdb_free(ptr.cast::<core::ffi::c_void>());
446 s
447 }
448 }
449
450 /// Returns the type of the struct field at `index`.
451 ///
452 /// # Safety
453 ///
454 /// The inner handle must be a `STRUCT` logical type and `index` must be
455 /// within bounds (requires `DuckDB` runtime).
456 #[must_use]
457 pub unsafe fn struct_child_type(&self, index: u64) -> Self {
458 // SAFETY: `self.inner` is a non-null handle this value owns and keeps live until
459 // `Drop` (type invariant: `owned_or` rejects null, `from_raw` asserts it). `index`
460 // is in bounds per this function's `# Safety` clause:
461 // `duckdb_struct_type_child_type` only `D_ASSERT`s it (types.cpp). A non-STRUCT
462 // type yields null, which `from_raw`'s assert turns into a panic; otherwise the
463 // result is a fresh `new LogicalType(..)` the caller owns, as `from_raw` requires.
464 unsafe {
465 Self::from_raw(duckdb_struct_type_child_type(
466 self.inner,
467 index as libduckdb_sys::idx_t,
468 ))
469 }
470 }
471
472 /// Returns the number of members in a `UNION` type.
473 ///
474 /// # Safety
475 ///
476 /// The inner handle must be a `UNION` logical type (requires `DuckDB` runtime).
477 #[must_use]
478 pub unsafe fn union_member_count(&self) -> u64 {
479 // SAFETY: `self.inner` is a non-null handle this value owns and keeps live until
480 // `Drop` (type invariant: `owned_or` rejects null, `from_raw` asserts it).
481 // `duckdb_union_type_member_count` checks the id itself and returns 0 for a
482 // non-UNION type (logical_types-c.cpp), so a type of another kind is not UB here.
483 unsafe { duckdb_union_type_member_count(self.inner) as u64 }
484 }
485
486 /// Returns the name of the union member at `index`.
487 ///
488 /// # Safety
489 ///
490 /// The inner handle must be a `UNION` logical type and `index` must be
491 /// within bounds (requires `DuckDB` runtime).
492 ///
493 /// # Panics
494 ///
495 /// Panics if `duckdb_union_type_member_name` returns a null pointer.
496 #[must_use]
497 pub unsafe fn union_member_name(&self, index: u64) -> String {
498 // SAFETY: `self.inner` is a non-null handle this value owns and keeps live until
499 // `Drop` (type invariant: `owned_or` rejects null, `from_raw` asserts it). `index`
500 // is in bounds per this function's `# Safety` clause:
501 // `duckdb_union_type_member_name` does not check it (the `*Type::Get*Name` helpers
502 // in types.cpp only `D_ASSERT` it). A wrong-kind type yields null. The result is
503 // checked non-null by the assert before `CStr::from_ptr`; it is a `strdup` copy, so
504 // NUL-terminated and ours to release with `duckdb_free` (which is `free`,
505 // helper-c.cpp), exactly once, after `to_string_lossy().into_owned()` has copied
506 // it.
507 unsafe {
508 let ptr = duckdb_union_type_member_name(self.inner, index as libduckdb_sys::idx_t);
509 assert!(
510 !ptr.is_null(),
511 "duckdb_union_type_member_name returned null"
512 );
513 let s = std::ffi::CStr::from_ptr(ptr).to_string_lossy().into_owned();
514 duckdb_free(ptr.cast::<core::ffi::c_void>());
515 s
516 }
517 }
518
519 /// Returns the type of the union member at `index`.
520 ///
521 /// # Safety
522 ///
523 /// The inner handle must be a `UNION` logical type and `index` must be
524 /// within bounds (requires `DuckDB` runtime).
525 #[must_use]
526 pub unsafe fn union_member_type(&self, index: u64) -> Self {
527 // SAFETY: `self.inner` is a non-null handle this value owns and keeps live until
528 // `Drop` (type invariant: `owned_or` rejects null, `from_raw` asserts it). `index`
529 // is in bounds per this function's `# Safety` clause:
530 // `duckdb_union_type_member_type` only `D_ASSERT`s it (types.cpp). A non-UNION type
531 // yields null, which `from_raw`'s assert turns into a panic; otherwise the result
532 // is a fresh `new LogicalType(..)` the caller owns, as `from_raw` requires.
533 unsafe {
534 Self::from_raw(duckdb_union_type_member_type(
535 self.inner,
536 index as libduckdb_sys::idx_t,
537 ))
538 }
539 }
540
541 /// Returns the fixed size of an `ARRAY` type.
542 ///
543 /// # Safety
544 ///
545 /// The inner handle must be an `ARRAY` logical type (requires `DuckDB` runtime).
546 #[must_use]
547 pub unsafe fn array_size(&self) -> u64 {
548 // SAFETY: `self.inner` is a non-null handle this value owns and keeps live until
549 // `Drop` (type invariant: `owned_or` rejects null, `from_raw` asserts it).
550 // `duckdb_array_type_array_size` checks the id itself and returns 0 for a non-ARRAY
551 // type (logical_types-c.cpp), so a type of another kind is not UB here.
552 unsafe { duckdb_array_type_array_size(self.inner) as u64 }
553 }
554
555 /// Returns the child (element) type of an `ARRAY` type.
556 ///
557 /// # Safety
558 ///
559 /// The inner handle must be an `ARRAY` logical type (requires `DuckDB` runtime).
560 #[must_use]
561 pub unsafe fn array_child_type(&self) -> Self {
562 // SAFETY: `self.inner` is a non-null handle this value owns and keeps live until
563 // `Drop` (type invariant: `owned_or` rejects null, `from_raw` asserts it).
564 // `duckdb_array_type_child_type` returns null for a non-ARRAY type, which
565 // `from_raw`'s assert turns into a panic; otherwise it returns a fresh heap `new
566 // LogicalType(..)` the caller owns (duckdb.h: "must be freed with
567 // `duckdb_destroy_logical_type`"), satisfying `from_raw`'s ownership clause.
568 unsafe { Self::from_raw(duckdb_array_type_child_type(self.inner)) }
569 }
570
571 /// Registers this type in the catalog of `con`, making it usable in SQL.
572 ///
573 /// This is how an extension ships a named type — `CREATE TYPE` from the C
574 /// API. Once registered, the alias can be used anywhere a type name can:
575 ///
576 /// ```sql
577 /// SELECT 'happy'::mood;
578 /// CREATE TABLE t(m mood);
579 /// ```
580 ///
581 /// `duckdb.h`: "Registers a custom type within the given connection. The
582 /// type must have an alias." Set one with
583 /// [`try_set_alias`][Self::try_set_alias] first; a type without an alias
584 /// has no name to register under and `DuckDB` rejects it.
585 ///
586 /// The `duckdb_create_type_info` third argument is passed as null: `DuckDB`
587 /// declares the handle but exposes no constructor for it in the C API, so
588 /// null is the only value an extension can supply.
589 ///
590 /// # Errors
591 ///
592 /// Returns an error if the type is or contains `ANY` or `INVALID` (checked
593 /// here, since `DuckDB` reports it the same way as a taken name), or if
594 /// `DuckDB` rejects the registration — no alias, or a name that already
595 /// exists in the catalog.
596 ///
597 /// # Safety
598 ///
599 /// `con` must be a valid, open `duckdb_connection`.
600 ///
601 /// # Example
602 ///
603 /// ```rust,no_run
604 /// use quack_rs::types::LogicalType;
605 ///
606 /// # fn demo(con: libduckdb_sys::duckdb_connection)
607 /// # -> Result<(), quack_rs::error::ExtensionError> {
608 /// let mood = LogicalType::enum_type(&["sad", "ok", "happy"]);
609 /// // SAFETY: `con` is the connection DuckDB handed the entry point.
610 /// unsafe {
611 /// mood.set_alias("mood");
612 /// mood.register(con)?;
613 /// }
614 /// # Ok(())
615 /// # }
616 /// ```
617 pub unsafe fn register(
618 &self,
619 con: libduckdb_sys::duckdb_connection,
620 ) -> Result<(), crate::error::ExtensionError> {
621 // `duckdb_register_logical_type` refuses such a type before it looks
622 // at the catalog, with the same bare error as a taken name.
623 // SAFETY: `self.inner` is a live logical type.
624 if unsafe { crate::table::type_check::contains_any_or_invalid(self.inner) } {
625 return Err(crate::error::ExtensionError::new(
626 "duckdb_register_logical_type: the type is or contains ANY or INVALID, which \
627 DuckDB refuses to register",
628 ));
629 }
630 // SAFETY: `con` is valid per the caller's contract, `self.inner` is a
631 // live logical type, and the info handle has no C API constructor.
632 let state = unsafe {
633 libduckdb_sys::duckdb_register_logical_type(con, self.inner, std::ptr::null_mut())
634 };
635 if state == libduckdb_sys::DuckDBSuccess {
636 return Ok(());
637 }
638 // SAFETY: `self.inner` is live; `get_alias` returns an owned String or None.
639 let alias = unsafe { self.get_alias() };
640 Err(crate::error::ExtensionError::new(alias.map_or_else(
641 || {
642 String::from(
643 "duckdb_register_logical_type failed: the type has no alias. Call \
644 `set_alias` or `try_set_alias` before registering — DuckDB has no name \
645 to register it under.",
646 )
647 },
648 |name| {
649 format!(
650 "duckdb_register_logical_type failed for alias '{name}': the name is \
651 probably already taken in this catalog"
652 )
653 },
654 )))
655 }
656
657 /// Returns the underlying raw `duckdb_logical_type` handle.
658 ///
659 /// # Safety note
660 ///
661 /// Do not call `duckdb_destroy_logical_type` on the returned handle; that is
662 /// handled by this type's `Drop` implementation.
663 #[must_use]
664 #[inline]
665 pub const fn as_raw(&self) -> duckdb_logical_type {
666 self.inner
667 }
668
669 /// Consumes this `LogicalType` and returns the raw handle without destroying it.
670 ///
671 /// The caller is responsible for calling `duckdb_destroy_logical_type` on the
672 /// returned handle.
673 #[must_use]
674 pub const fn into_raw(self) -> duckdb_logical_type {
675 let raw = self.inner;
676 // Prevent Drop from running by wrapping in ManuallyDrop
677 std::mem::forget(self);
678 raw
679 }
680}
681
682impl Drop for LogicalType {
683 #[cfg_attr(test, mutants::skip)]
684 fn drop(&mut self) {
685 // SAFETY: `self.inner` was created by `duckdb_create_logical_type` and has not
686 // been transferred elsewhere. It is safe to destroy exactly once here.
687 unsafe {
688 duckdb_destroy_logical_type(&raw mut self.inner);
689 }
690 }
691}
692
693impl From<TypeId> for LogicalType {
694 /// Creates a `LogicalType` from a `TypeId`.
695 ///
696 /// This is equivalent to calling [`LogicalType::new`].
697 fn from(type_id: TypeId) -> Self {
698 Self::new(type_id)
699 }
700}
701
702// LogicalType is not Clone or Copy because the underlying handle is not reference-counted.
703// If you need to pass it to multiple places, use `as_raw()` to borrow the handle temporarily.
704
705impl core::fmt::Debug for LogicalType {
706 /// Prints the decoded type rather than the handle address — the type id is
707 /// the only thing anyone inspects a `LogicalType` to learn.
708 ///
709 /// This calls into `DuckDB`, so it deliberately avoids anything that could
710 /// panic while formatting: a `Debug` impl that panics inside a panic message
711 /// aborts the process. A type id from a newer `DuckDB` than this build knows
712 /// renders as its numeric value rather than panicking the way
713 /// [`get_type_id`][Self::get_type_id] would.
714 ///
715 /// The null check is belt-and-braces — every constructor, `from_raw`
716 /// included, already asserts the handle is non-null — but a formatting
717 /// impl is the last place worth being clever about a single comparison.
718 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
719 if self.inner.is_null() {
720 return f.write_str("LogicalType(<null>)");
721 }
722 // SAFETY: `self.inner` is non-null and valid for this wrapper's lifetime.
723 let raw_id = unsafe { duckdb_get_type_id(self.inner) };
724 let mut out = f.debug_struct("LogicalType");
725 match TypeId::try_from_duckdb_type(raw_id) {
726 Some(type_id) => out.field("type_id", &type_id),
727 // A type id this build of quack-rs does not know — print the number
728 // rather than panicking, which is what `TypeId::from_duckdb_type`
729 // would do.
730 None => out.field("type_id", &format_args!("<unknown {raw_id}>")),
731 };
732 // SAFETY: `self.inner` is non-null and valid.
733 if let Some(alias) = unsafe { self.get_alias() } {
734 out.field("alias", &alias);
735 }
736 if TypeId::try_from_duckdb_type(raw_id) == Some(TypeId::Decimal) {
737 // SAFETY: `self.inner` is a DECIMAL logical type.
738 let (width, scale) = unsafe { (self.decimal_width(), self.decimal_scale()) };
739 out.field("width", &width).field("scale", &scale);
740 }
741 out.finish()
742 }
743}
744
745#[cfg(test)]
746mod tests {
747 use super::{composite_message, LogicalType, LogicalTypeError, TypeId};
748
749 // `check_slot` is what every builder calls *before* allocating a DuckDB
750 // handle, and `composite_message` is the advice it carries. Both are pure,
751 // and neither is reachable from the end-to-end suite without a database, so
752 // they are pinned here.
753
754 #[test]
755 fn check_slot_rejects_a_composite_before_touching_duckdb() {
756 // Only the rejection path is unit-testable: a primitive falls through
757 // to `duckdb_create_logical_type`, which needs a live dispatch table.
758 // Rejecting *before* that call is the whole point of `check_slot`, so
759 // this test reaching its assertions at all is part of what it proves.
760 let err = LogicalType::check_slot(TypeId::Struct, "parameter 0")
761 .expect_err("STRUCT cannot come from a bare TypeId");
762 let msg = err.as_str();
763 assert!(msg.contains("parameter 0"), "names the slot: {msg}");
764 assert!(msg.contains("STRUCT"), "names the type: {msg}");
765 assert!(
766 msg.contains("LogicalType::struct_type(&fields)"),
767 "names the constructor to use instead: {msg}"
768 );
769 }
770
771 /// `DuckDB` registers a function whose parameter or return type is a
772 /// literal type, then invalidates the database on the first query that
773 /// returns one. Both are refused before any `DuckDB` call.
774 #[test]
775 fn check_slot_rejects_the_literal_types_before_touching_duckdb() {
776 for (ty, name) in [
777 (TypeId::IntegerLiteral, "INTEGER_LITERAL"),
778 (TypeId::StringLiteral, "STRING_LITERAL"),
779 ] {
780 let err = LogicalType::check_slot(ty, "return type").expect_err("literal type");
781 let msg = err.as_str();
782 assert!(msg.contains("return type"), "names the slot: {msg}");
783 assert!(msg.contains(name), "names the type: {msg}");
784 assert!(msg.contains("invalidates the database"), "{msg}");
785 }
786 }
787
788 #[test]
789 fn the_composite_message_names_the_type_and_its_constructor() {
790 let msg = composite_message(TypeId::Decimal);
791 assert_ne!(msg, "");
792 assert!(msg.contains("DECIMAL"), "{msg}");
793 assert!(msg.contains("LogicalType::decimal(width, scale)"), "{msg}");
794 assert!(
795 msg.contains("param_logical"),
796 "points at the escape hatch: {msg}"
797 );
798
799 // A non-composite has no hint, so the message falls back rather than
800 // naming a constructor that does not exist.
801 let generic = composite_message(TypeId::BigInt);
802 assert!(
803 generic.contains("a dedicated LogicalType constructor"),
804 "{generic}"
805 );
806 }
807
808 #[test]
809 fn a_null_error_reports_the_api_function_that_returned_it() {
810 let err = LogicalTypeError::null("duckdb_create_list_type");
811 assert_eq!(err.api_func(), "duckdb_create_list_type");
812 assert_eq!(err.to_string(), "duckdb_create_list_type returned null");
813 }
814
815 // Note: LogicalType tests that call DuckDB API (duckdb_create_logical_type)
816 // require a running DuckDB runtime and are covered in tests/integration_test.rs.
817 // The `loadable-extension` feature uses lazy-initialized function pointers
818 // that cannot be called without a prior call to duckdb_rs_extension_api_init.
819
820 #[test]
821 fn logical_type_error_display() {
822 let err = super::LogicalTypeError::null("duckdb_create_logical_type");
823 assert_eq!(err.to_string(), "duckdb_create_logical_type returned null");
824 }
825
826 #[test]
827 fn size_of_logical_type_struct() {
828 use super::LogicalType;
829 // LogicalType must be pointer-sized (it contains a single pointer).
830 assert_eq!(
831 std::mem::size_of::<LogicalType>(),
832 std::mem::size_of::<*mut ()>()
833 );
834 }
835}
836
837/// Constructor tests that need a live `DuckDB` C API dispatch table.
838#[cfg(all(test, feature = "_duckdb-testing"))]
839mod live_tests {
840 use super::{LogicalType, TypeId, MAX_UNION_MEMBERS};
841
842 #[test]
843 fn try_constructors_reject_interior_null_bytes() {
844 let _db = crate::testing::InMemoryDb::open().expect("open in-memory DuckDB");
845 // Every fallible constructor that takes user-supplied names must report
846 // an interior NUL instead of panicking: these run inside DuckDB bind
847 // callbacks, where a panic cannot be surfaced to the user and aborts the
848 // process under `panic = "abort"`.
849 assert!(LogicalType::try_struct_type(&[("a\0b", TypeId::BigInt)]).is_err());
850 assert!(LogicalType::try_union_type(&[("a\0b", TypeId::BigInt)]).is_err());
851 assert!(LogicalType::try_enum_type(&["ok", "a\0b"]).is_err());
852 let lt = LogicalType::try_new(TypeId::BigInt).expect("BIGINT");
853 // SAFETY: `lt` wraps a valid logical type.
854 assert!(unsafe { lt.try_set_alias("a\0b") }.is_err());
855 }
856
857 #[test]
858 fn try_constructor_errors_name_the_failing_step() {
859 let _db = crate::testing::InMemoryDb::open().expect("open in-memory DuckDB");
860 let Err(err) = LogicalType::try_enum_type(&["a\0b"]) else {
861 panic!("try_enum_type must reject an interior NUL");
862 };
863 assert!(err.to_string().contains("null byte"), "{err}");
864 }
865
866 /// Regression: these six type ids exist in every `DuckDB` this crate
867 /// supports (all are in libduckdb-sys 1.4.4), but their `TypeId` variants
868 /// were gated behind `duckdb-1-5`. Without that feature, `get_type_id` on a
869 /// `TIME_NS` or `BIGNUM` column panicked. (`DuckDB` 1.4.4's C API reports a
870 /// `TIME_NS` column as `INVALID`, so on 1.4.x only `BIGNUM` reaches the
871 /// mapping; the fourth audit ran this against 1.4.4 and found the earlier
872 /// wording wrong.)
873 #[test]
874 fn type_ids_from_duckdb_1_4_resolve_without_any_feature() {
875 use libduckdb_sys::{
876 duckdb_create_logical_type, DUCKDB_TYPE_DUCKDB_TYPE_ANY,
877 DUCKDB_TYPE_DUCKDB_TYPE_BIGNUM, DUCKDB_TYPE_DUCKDB_TYPE_SQLNULL,
878 DUCKDB_TYPE_DUCKDB_TYPE_TIME_NS,
879 };
880 let _db = crate::testing::InMemoryDb::open().expect("open in-memory DuckDB");
881 for (raw, want) in [
882 (DUCKDB_TYPE_DUCKDB_TYPE_TIME_NS, TypeId::TimeNs),
883 (DUCKDB_TYPE_DUCKDB_TYPE_BIGNUM, TypeId::Varint),
884 (DUCKDB_TYPE_DUCKDB_TYPE_ANY, TypeId::Any),
885 (DUCKDB_TYPE_DUCKDB_TYPE_SQLNULL, TypeId::SqlNull),
886 ] {
887 // SAFETY: a valid DUCKDB_TYPE for a non-composite type; the handle
888 // is owned by the returned `LogicalType`.
889 let ty = unsafe { LogicalType::from_raw(duckdb_create_logical_type(raw)) };
890 // DuckDB 1.4.x's C API does not know TIME_NS: it hands back an
891 // INVALID type (and reports a TIME_NS column as INVALID), so there
892 // is no id to resolve. Any other mismatch is a failure.
893 // SAFETY: `ty` wraps a valid logical type.
894 let got = unsafe { libduckdb_sys::duckdb_get_type_id(ty.as_raw()) };
895 if raw == DUCKDB_TYPE_DUCKDB_TYPE_TIME_NS
896 && got == libduckdb_sys::DUCKDB_TYPE_DUCKDB_TYPE_INVALID
897 {
898 continue;
899 }
900 // SAFETY: `ty` wraps a valid logical type.
901 unsafe {
902 assert_eq!(ty.try_get_type_id(), Some(want));
903 assert_eq!(ty.get_type_id(), want);
904 }
905 }
906 }
907
908 /// Regression: `duckdb_create_struct_type` / `duckdb_create_union_type`
909 /// validate nothing, so these returned `Ok`, registered, and then failed
910 /// on first use with `DuckDB`'s binder errors ("Duplicate STRUCT type
911 /// argument name", "UNION type supports at most 256 type modifiers").
912 #[test]
913 fn struct_and_union_constructors_apply_duckdbs_name_rules() {
914 let _db = crate::testing::InMemoryDb::open().expect("open in-memory DuckDB");
915 assert!(
916 LogicalType::try_struct_type(&[("a", TypeId::Integer), ("a", TypeId::Integer)])
917 .is_err()
918 );
919 assert!(
920 LogicalType::try_struct_type(&[("a", TypeId::Integer), ("A", TypeId::Integer)])
921 .is_err()
922 );
923 assert!(
924 LogicalType::try_union_type(&[("m", TypeId::Integer), ("M", TypeId::Varchar)]).is_err()
925 );
926 // Unnamed structs have empty field names, repeated.
927 assert!(
928 LogicalType::try_struct_type(&[("", TypeId::Integer), ("", TypeId::Integer)]).is_ok()
929 );
930
931 let owned: Vec<String> = (0..=MAX_UNION_MEMBERS).map(|i| format!("m{i}")).collect();
932 let members: Vec<(&str, TypeId)> = owned
933 .iter()
934 .map(|n| (n.as_str(), TypeId::Integer))
935 .collect();
936 assert!(LogicalType::try_union_type(&members[..MAX_UNION_MEMBERS]).is_ok());
937 let err = LogicalType::try_union_type(&members).expect_err("one member too many");
938 assert!(
939 err.to_string()
940 .contains(&format!("at most {MAX_UNION_MEMBERS}")),
941 "{err}"
942 );
943 }
944
945 /// The fallible forms of the four constructors that had none (AUDIT.md
946 /// section 5.5) report `DuckDB`'s refusals instead of panicking. The
947 /// DECIMAL cases failed against `DuckDB` 1.5.0, whose
948 /// `duckdb_create_decimal_type` accepts any width and scale; quack-rs
949 /// checks them itself now (fourth audit).
950 #[test]
951 fn decimal_and_array_have_fallible_forms() {
952 let _db = crate::testing::InMemoryDb::open().expect("open in-memory DuckDB");
953 assert!(LogicalType::try_decimal(18, 3).is_ok());
954 for (w, s) in [(0, 0), (39, 0), (5, 6)] {
955 let err = LogicalType::try_decimal(w, s).expect_err("out of range");
956 assert_eq!(err.api_func(), "duckdb_create_decimal_type");
957 }
958 assert!(LogicalType::try_array(TypeId::Float, 99_999).is_ok());
959 assert!(LogicalType::try_array(TypeId::Float, 100_000).is_err());
960 assert!(LogicalType::try_array(TypeId::Struct, 3).is_err());
961 let element = LogicalType::new(TypeId::Integer);
962 assert!(LogicalType::try_list_from_logical(&element).is_ok());
963 assert!(LogicalType::try_map_from_logical(&element, &element).is_ok());
964 }
965
966 #[test]
967 fn try_constructors_build_valid_types() {
968 let _db = crate::testing::InMemoryDb::open().expect("open in-memory DuckDB");
969 let s = LogicalType::try_struct_type(&[("x", TypeId::BigInt), ("y", TypeId::Varchar)])
970 .expect("struct");
971 // SAFETY: `s` wraps a valid logical type.
972 unsafe {
973 assert_eq!(s.get_type_id(), TypeId::Struct);
974 assert_eq!(s.struct_child_count(), 2);
975 assert_eq!(s.struct_child_name(0), "x");
976 }
977
978 let u = LogicalType::try_union_type(&[("a", TypeId::BigInt), ("b", TypeId::Double)])
979 .expect("union");
980 // SAFETY: `u` wraps a valid logical type.
981 unsafe {
982 assert_eq!(u.get_type_id(), TypeId::Union);
983 assert_eq!(u.union_member_count(), 2);
984 }
985
986 let e = LogicalType::try_enum_type(&["red", "green", "blue"]).expect("enum");
987 // SAFETY: `e` wraps a valid logical type.
988 unsafe {
989 assert_eq!(e.get_type_id(), TypeId::Enum);
990 assert_eq!(e.enum_dictionary_size(), 3);
991 assert_eq!(e.enum_dictionary_value(1), "green");
992 }
993
994 let nested = LogicalType::try_struct_type_from_logical(&[(
995 "inner",
996 LogicalType::try_list(TypeId::Integer).expect("list"),
997 )])
998 .expect("nested struct");
999 // SAFETY: `nested` wraps a valid logical type.
1000 unsafe {
1001 assert_eq!(nested.get_type_id(), TypeId::Struct);
1002 assert_eq!(nested.struct_child_type(0).get_type_id(), TypeId::List);
1003 }
1004 }
1005}