quack-rs 0.12.0

Production-grade Rust SDK for building DuckDB loadable extensions
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
// SPDX-License-Identifier: MIT
// Copyright 2026 Tom F. <https://github.com/tomtom215/>
// My way of giving something small back to the open source community
// and encouraging more Rust development!

//! RAII wrapper for `duckdb_logical_type`.
//!
//! # Pitfall L7: `LogicalType` memory leak
//!
//! Every `duckdb_create_logical_type` call allocates memory that must be freed
//! with `duckdb_destroy_logical_type`. Forgetting to call the destructor leaks
//! memory. [`LogicalType`] implements `Drop` to prevent this.

use crate::types::TypeId;
use libduckdb_sys::{
    duckdb_array_type_array_size, duckdb_array_type_child_type, duckdb_create_array_type,
    duckdb_create_decimal_type, duckdb_create_enum_type, duckdb_create_list_type,
    duckdb_create_logical_type, duckdb_create_map_type, duckdb_create_struct_type,
    duckdb_create_union_type, duckdb_decimal_internal_type, duckdb_decimal_scale,
    duckdb_decimal_width, duckdb_destroy_logical_type, duckdb_enum_dictionary_size,
    duckdb_enum_dictionary_value, duckdb_enum_internal_type, duckdb_free, duckdb_get_type_id,
    duckdb_list_type_child_type, duckdb_logical_type, duckdb_logical_type_get_alias,
    duckdb_logical_type_set_alias, duckdb_map_type_key_type, duckdb_map_type_value_type,
    duckdb_struct_type_child_count, duckdb_struct_type_child_name, duckdb_struct_type_child_type,
    duckdb_union_type_member_count, duckdb_union_type_member_name, duckdb_union_type_member_type,
};
use std::fmt;

/// Error returned by fallible [`LogicalType`] constructors when the underlying
/// `DuckDB` C API returns a null pointer.
#[derive(Debug, Clone)]
pub struct LogicalTypeError {
    api_func: &'static str,
}

impl fmt::Display for LogicalTypeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} returned null", self.api_func)
    }
}

impl std::error::Error for LogicalTypeError {}

/// An RAII wrapper around a `duckdb_logical_type` handle.
///
/// Created from a [`TypeId`], this type ensures `duckdb_destroy_logical_type`
/// is called when it is dropped. This prevents the memory leak described in
/// [Pitfall L7](https://github.com/tomtom215/quack-rs/blob/main/LESSONS.md).
///
/// # Example
///
/// ```rust,no_run
/// use quack_rs::types::{LogicalType, TypeId};
///
/// // Requires DuckDB runtime to be initialized (i.e., loaded as an extension).
/// let lt = LogicalType::new(TypeId::BigInt);
/// // `lt` is automatically destroyed when it goes out of scope
/// ```
pub struct LogicalType {
    inner: duckdb_logical_type,
}

impl LogicalType {
    /// Creates a `LogicalType` from an existing raw `duckdb_logical_type` handle.
    ///
    /// The returned `LogicalType` takes ownership of the handle and will call
    /// `duckdb_destroy_logical_type` when dropped.
    ///
    /// # Safety
    ///
    /// - `ptr` must be a valid, non-null `duckdb_logical_type` handle returned by
    ///   a `duckdb_create_*` function (e.g. `duckdb_create_logical_type`,
    ///   `duckdb_create_list_type`, `duckdb_create_struct_type`, etc.).
    /// - The caller must not call `duckdb_destroy_logical_type` on the handle
    ///   after passing it to this function.
    /// - The handle must not be used after this call except through the returned
    ///   `LogicalType`.
    ///
    /// # Panics
    ///
    /// Panics if `ptr` is null.
    #[must_use]
    pub unsafe fn from_raw(ptr: duckdb_logical_type) -> Self {
        assert!(
            !ptr.is_null(),
            "LogicalType::from_raw called with null pointer"
        );
        Self { inner: ptr }
    }

    /// Creates a new `LogicalType` for the given `TypeId`.
    ///
    /// Calls `duckdb_create_logical_type` internally.
    ///
    /// # Panics
    ///
    /// Panics if `duckdb_create_logical_type` returns a null pointer (should never
    /// happen for supported types, but is checked defensively).
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use quack_rs::types::{LogicalType, TypeId};
    ///
    /// // Requires DuckDB runtime (called from within a loaded extension).
    /// let lt = LogicalType::new(TypeId::Timestamp);
    /// assert!(!lt.as_raw().is_null());
    /// ```
    #[must_use]
    pub fn new(type_id: TypeId) -> Self {
        // SAFETY: `duckdb_create_logical_type` is safe to call with any valid DUCKDB_TYPE.
        // It returns a heap-allocated handle that must be freed with duckdb_destroy_logical_type.
        let inner = unsafe { duckdb_create_logical_type(type_id.to_duckdb_type()) };
        assert!(!inner.is_null(), "duckdb_create_logical_type returned null");
        Self { inner }
    }

    /// Creates a `LIST<element_type>` logical type.
    ///
    /// Lists are variable-length sequences of the given element type.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use quack_rs::types::{LogicalType, TypeId};
    ///
    /// // Requires DuckDB runtime.
    /// let list_of_int = LogicalType::list(TypeId::Integer);
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if `duckdb_create_list_type` returns null (should never happen).
    #[must_use]
    pub fn list(element_type: TypeId) -> Self {
        let element_lt = Self::new(element_type);
        // SAFETY: element_lt.as_raw() is a valid logical type.
        let inner = unsafe { duckdb_create_list_type(element_lt.as_raw()) };
        assert!(!inner.is_null(), "duckdb_create_list_type returned null");
        Self { inner }
    }

    /// Creates a `MAP<key_type, value_type>` logical type.
    ///
    /// `DuckDB` maps are stored as `LIST<STRUCT{key: K, value: V}>`.
    ///
    /// # Panics
    ///
    /// Panics if `duckdb_create_map_type` returns null.
    #[must_use]
    pub fn map(key_type: TypeId, value_type: TypeId) -> Self {
        let key_lt = Self::new(key_type);
        let val_lt = Self::new(value_type);
        // SAFETY: both logical types are valid.
        let inner = unsafe { duckdb_create_map_type(key_lt.as_raw(), val_lt.as_raw()) };
        assert!(!inner.is_null(), "duckdb_create_map_type returned null");
        Self { inner }
    }

    /// Creates a `STRUCT` logical type from a slice of `(name, type)` field definitions.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use quack_rs::types::{LogicalType, TypeId};
    ///
    /// // Requires DuckDB runtime.
    /// let point = LogicalType::struct_type(&[
    ///     ("x", TypeId::Double),
    ///     ("y", TypeId::Double),
    /// ]);
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if any field name contains an interior null byte, or if
    /// `duckdb_create_struct_type` returns null.
    #[must_use]
    pub fn struct_type(fields: &[(&str, TypeId)]) -> Self {
        use std::ffi::CString;

        // Build arrays of logical type handles and C name pointers.
        // The logical types must outlive the duckdb_create_struct_type call.
        let field_types: Vec<Self> = fields.iter().map(|&(_, t)| Self::new(t)).collect();
        let c_names: Vec<CString> = fields
            .iter()
            .map(|&(n, _)| CString::new(n).expect("field name must not contain null bytes"))
            .collect();

        let mut type_ptrs: Vec<duckdb_logical_type> =
            field_types.iter().map(Self::as_raw).collect();
        let mut name_ptrs: Vec<*const std::os::raw::c_char> =
            c_names.iter().map(|s| s.as_ptr()).collect();

        // SAFETY: type_ptrs and name_ptrs are valid for the duration of this call.
        let inner = unsafe {
            duckdb_create_struct_type(
                type_ptrs.as_mut_ptr(),
                name_ptrs.as_mut_ptr(),
                fields.len() as libduckdb_sys::idx_t,
            )
        };
        assert!(!inner.is_null(), "duckdb_create_struct_type returned null");
        Self { inner }
    }

    /// Creates a `DECIMAL(width, scale)` logical type.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use quack_rs::types::LogicalType;
    ///
    /// // DECIMAL(18, 3) — 18 total digits, 3 after the decimal point
    /// let price = LogicalType::decimal(18, 3);
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if `duckdb_create_decimal_type` returns null.
    #[must_use]
    pub fn decimal(width: u8, scale: u8) -> Self {
        let inner = unsafe { duckdb_create_decimal_type(width, scale) };
        assert!(!inner.is_null(), "duckdb_create_decimal_type returned null");
        Self { inner }
    }

    /// Creates an `ARRAY<element_type>[size]` logical type (fixed-size array).
    ///
    /// Unlike `LIST`, arrays have a fixed number of elements known at type
    /// definition time.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use quack_rs::types::{LogicalType, TypeId};
    ///
    /// // FLOAT[3] — a 3-element array of floats (e.g., for a 3D vector)
    /// let vec3 = LogicalType::array(TypeId::Float, 3);
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if `duckdb_create_array_type` returns null.
    #[must_use]
    pub fn array(element_type: TypeId, size: u64) -> Self {
        let element_lt = Self::new(element_type);
        let inner =
            unsafe { duckdb_create_array_type(element_lt.as_raw(), size as libduckdb_sys::idx_t) };
        assert!(!inner.is_null(), "duckdb_create_array_type returned null");
        Self { inner }
    }

    /// Creates an `ARRAY<element>[size]` logical type from an existing [`LogicalType`].
    ///
    /// Use this when the element type is itself a complex type.
    ///
    /// # Panics
    ///
    /// Panics if `duckdb_create_array_type` returns null.
    #[must_use]
    pub fn array_from_logical(element: &Self, size: u64) -> Self {
        let inner =
            unsafe { duckdb_create_array_type(element.as_raw(), size as libduckdb_sys::idx_t) };
        assert!(!inner.is_null(), "duckdb_create_array_type returned null");
        Self { inner }
    }

    /// Creates a `UNION` logical type from a slice of `(name, type)` member definitions.
    ///
    /// A `UNION` can hold one value of any of its member types at a time,
    /// similar to a tagged union or sum type.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use quack_rs::types::{LogicalType, TypeId};
    ///
    /// let result = LogicalType::union_type(&[
    ///     ("str", TypeId::Varchar),
    ///     ("num", TypeId::BigInt),
    /// ]);
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if any member name contains an interior null byte, or if
    /// `duckdb_create_union_type` returns null.
    #[must_use]
    pub fn union_type(members: &[(&str, TypeId)]) -> Self {
        use std::ffi::CString;

        let member_types: Vec<Self> = members.iter().map(|&(_, t)| Self::new(t)).collect();
        let c_names: Vec<CString> = members
            .iter()
            .map(|&(n, _)| CString::new(n).expect("member name must not contain null bytes"))
            .collect();

        let mut type_ptrs: Vec<duckdb_logical_type> =
            member_types.iter().map(Self::as_raw).collect();
        let mut name_ptrs: Vec<*const std::os::raw::c_char> =
            c_names.iter().map(|s| s.as_ptr()).collect();

        let inner = unsafe {
            duckdb_create_union_type(
                type_ptrs.as_mut_ptr(),
                name_ptrs.as_mut_ptr(),
                members.len() as libduckdb_sys::idx_t,
            )
        };
        assert!(!inner.is_null(), "duckdb_create_union_type returned null");
        Self { inner }
    }

    /// Creates a `UNION` logical type from a slice of `(name, LogicalType)` members.
    ///
    /// Use this when members have complex types.
    ///
    /// # Panics
    ///
    /// Panics if any member name contains an interior null byte, or if
    /// `duckdb_create_union_type` returns null.
    #[must_use]
    pub fn union_type_from_logical(members: &[(&str, Self)]) -> Self {
        use std::ffi::CString;

        let c_names: Vec<CString> = members
            .iter()
            .map(|&(n, _)| CString::new(n).expect("member name must not contain null bytes"))
            .collect();

        let mut type_ptrs: Vec<duckdb_logical_type> =
            members.iter().map(|(_, lt)| lt.as_raw()).collect();
        let mut name_ptrs: Vec<*const std::os::raw::c_char> =
            c_names.iter().map(|s| s.as_ptr()).collect();

        let inner = unsafe {
            duckdb_create_union_type(
                type_ptrs.as_mut_ptr(),
                name_ptrs.as_mut_ptr(),
                members.len() as libduckdb_sys::idx_t,
            )
        };
        assert!(!inner.is_null(), "duckdb_create_union_type returned null");
        Self { inner }
    }

    /// Creates an `ENUM` logical type from a list of member names.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use quack_rs::types::LogicalType;
    ///
    /// let color = LogicalType::enum_type(&["red", "green", "blue"]);
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if any name contains an interior null byte, or if
    /// `duckdb_create_enum_type` returns null.
    #[must_use]
    pub fn enum_type(members: &[&str]) -> Self {
        use std::ffi::CString;

        let c_names: Vec<CString> = members
            .iter()
            .map(|n| CString::new(*n).expect("enum member name must not contain null bytes"))
            .collect();

        let mut name_ptrs: Vec<*const std::os::raw::c_char> =
            c_names.iter().map(|s| s.as_ptr()).collect();

        let inner = unsafe {
            duckdb_create_enum_type(
                name_ptrs.as_mut_ptr(),
                members.len() as libduckdb_sys::idx_t,
            )
        };
        assert!(!inner.is_null(), "duckdb_create_enum_type returned null");
        Self { inner }
    }

    /// Creates a `LIST<element>` logical type from an existing [`LogicalType`].
    ///
    /// Use this when the element type is itself a complex type (e.g.
    /// `LIST(STRUCT(...))`) that cannot be expressed as a simple [`TypeId`].
    ///
    /// # Panics
    ///
    /// Panics if `duckdb_create_list_type` returns null.
    #[must_use]
    pub fn list_from_logical(element: &Self) -> Self {
        let inner = unsafe { duckdb_create_list_type(element.as_raw()) };
        assert!(!inner.is_null(), "duckdb_create_list_type returned null");
        Self { inner }
    }

    /// Creates a `MAP<key, value>` logical type from existing [`LogicalType`]s.
    ///
    /// Use this when the key or value types are complex types that cannot be
    /// expressed as simple [`TypeId`] values.
    ///
    /// # Panics
    ///
    /// Panics if `duckdb_create_map_type` returns null.
    #[must_use]
    pub fn map_from_logical(key: &Self, value: &Self) -> Self {
        let inner = unsafe { duckdb_create_map_type(key.as_raw(), value.as_raw()) };
        assert!(!inner.is_null(), "duckdb_create_map_type returned null");
        Self { inner }
    }

    /// Creates a `STRUCT` logical type from a slice of `(name, LogicalType)` fields.
    ///
    /// Use this when struct members have complex types (e.g.
    /// `STRUCT(headers MAP(VARCHAR, VARCHAR), body VARCHAR)`) that cannot be
    /// expressed as simple [`TypeId`] values.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use quack_rs::types::{LogicalType, TypeId};
    ///
    /// // STRUCT(status INTEGER, headers MAP(VARCHAR, VARCHAR), body VARCHAR)
    /// let response = LogicalType::struct_type_from_logical(&[
    ///     ("status", LogicalType::new(TypeId::Integer)),
    ///     ("headers", LogicalType::map(TypeId::Varchar, TypeId::Varchar)),
    ///     ("body", LogicalType::new(TypeId::Varchar)),
    /// ]);
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if any field name contains an interior null byte, or if
    /// `duckdb_create_struct_type` returns null.
    #[must_use]
    pub fn struct_type_from_logical(fields: &[(&str, Self)]) -> Self {
        use std::ffi::CString;

        let c_names: Vec<CString> = fields
            .iter()
            .map(|&(n, _)| CString::new(n).expect("field name must not contain null bytes"))
            .collect();

        let mut type_ptrs: Vec<duckdb_logical_type> =
            fields.iter().map(|(_, lt)| lt.as_raw()).collect();
        let mut name_ptrs: Vec<*const std::os::raw::c_char> =
            c_names.iter().map(|s| s.as_ptr()).collect();

        let inner = unsafe {
            duckdb_create_struct_type(
                type_ptrs.as_mut_ptr(),
                name_ptrs.as_mut_ptr(),
                fields.len() as libduckdb_sys::idx_t,
            )
        };
        assert!(!inner.is_null(), "duckdb_create_struct_type returned null");
        Self { inner }
    }

    /// Fallible version of [`LogicalType::new`]. Returns an error instead of
    /// panicking if the `DuckDB` C API returns a null pointer.
    pub fn try_new(type_id: TypeId) -> Result<Self, LogicalTypeError> {
        let inner = unsafe { duckdb_create_logical_type(type_id.to_duckdb_type()) };
        if inner.is_null() {
            return Err(LogicalTypeError {
                api_func: "duckdb_create_logical_type",
            });
        }
        Ok(Self { inner })
    }

    /// Fallible version of [`LogicalType::list`]. Returns an error instead of
    /// panicking if the `DuckDB` C API returns a null pointer.
    pub fn try_list(element_type: TypeId) -> Result<Self, LogicalTypeError> {
        let element_lt = Self::try_new(element_type)?;
        let inner = unsafe { duckdb_create_list_type(element_lt.as_raw()) };
        if inner.is_null() {
            return Err(LogicalTypeError {
                api_func: "duckdb_create_list_type",
            });
        }
        Ok(Self { inner })
    }

    /// Fallible version of [`LogicalType::map`]. Returns an error instead of
    /// panicking if the `DuckDB` C API returns a null pointer.
    pub fn try_map(key_type: TypeId, value_type: TypeId) -> Result<Self, LogicalTypeError> {
        let key_lt = Self::try_new(key_type)?;
        let val_lt = Self::try_new(value_type)?;
        let inner = unsafe { duckdb_create_map_type(key_lt.as_raw(), val_lt.as_raw()) };
        if inner.is_null() {
            return Err(LogicalTypeError {
                api_func: "duckdb_create_map_type",
            });
        }
        Ok(Self { inner })
    }

    /// Fallible version of [`LogicalType::struct_type`]. Returns an error
    /// instead of panicking if a field name contains an interior null byte or
    /// if the `DuckDB` C API returns a null pointer.
    pub fn try_struct_type(fields: &[(&str, TypeId)]) -> Result<Self, LogicalTypeError> {
        use std::ffi::CString;

        let field_types: Vec<Self> = fields
            .iter()
            .map(|&(_, t)| Self::try_new(t))
            .collect::<Result<_, _>>()?;
        let c_names: Vec<CString> = fields
            .iter()
            .map(|&(n, _)| {
                CString::new(n).map_err(|_| LogicalTypeError {
                    api_func: "CString::new (field name contains null byte)",
                })
            })
            .collect::<Result<_, _>>()?;

        let mut type_ptrs: Vec<duckdb_logical_type> =
            field_types.iter().map(Self::as_raw).collect();
        let mut name_ptrs: Vec<*const std::os::raw::c_char> =
            c_names.iter().map(|s| s.as_ptr()).collect();

        let inner = unsafe {
            duckdb_create_struct_type(
                type_ptrs.as_mut_ptr(),
                name_ptrs.as_mut_ptr(),
                fields.len() as libduckdb_sys::idx_t,
            )
        };
        if inner.is_null() {
            return Err(LogicalTypeError {
                api_func: "duckdb_create_struct_type",
            });
        }
        Ok(Self { inner })
    }

    // ------------------------------------------------------------------
    // Introspection methods
    // ------------------------------------------------------------------

    /// Returns the [`TypeId`] of this logical type.
    ///
    /// # Safety
    ///
    /// The inner handle must be valid (requires `DuckDB` runtime).
    #[must_use]
    pub unsafe fn get_type_id(&self) -> TypeId {
        TypeId::from_duckdb_type(unsafe { duckdb_get_type_id(self.inner) })
    }

    /// Returns the alias of this logical type, or `None` if no alias is set.
    ///
    /// # Safety
    ///
    /// The inner handle must be valid (requires `DuckDB` runtime).
    #[must_use]
    pub unsafe fn get_alias(&self) -> Option<String> {
        let ptr = unsafe { duckdb_logical_type_get_alias(self.inner) };
        if ptr.is_null() {
            return None;
        }
        let s = unsafe { std::ffi::CStr::from_ptr(ptr) }
            .to_string_lossy()
            .into_owned();
        unsafe { duckdb_free(ptr.cast::<core::ffi::c_void>()) };
        Some(s)
    }

    /// Sets an alias on this logical type.
    ///
    /// # Safety
    ///
    /// The inner handle must be valid (requires `DuckDB` runtime).
    ///
    /// # Panics
    ///
    /// Panics if `alias` contains an interior null byte.
    pub unsafe fn set_alias(&self, alias: &str) {
        let c_alias = std::ffi::CString::new(alias).expect("alias must not contain null bytes");
        unsafe { duckdb_logical_type_set_alias(self.inner, c_alias.as_ptr()) };
    }

    /// Returns the width (total digits) of a `DECIMAL` type.
    ///
    /// # Safety
    ///
    /// The inner handle must be a `DECIMAL` logical type (requires `DuckDB` runtime).
    #[must_use]
    pub unsafe fn decimal_width(&self) -> u8 {
        unsafe { duckdb_decimal_width(self.inner) }
    }

    /// Returns the scale (digits after decimal point) of a `DECIMAL` type.
    ///
    /// # Safety
    ///
    /// The inner handle must be a `DECIMAL` logical type (requires `DuckDB` runtime).
    #[must_use]
    pub unsafe fn decimal_scale(&self) -> u8 {
        unsafe { duckdb_decimal_scale(self.inner) }
    }

    /// Returns the internal storage type of a `DECIMAL` type.
    ///
    /// # Safety
    ///
    /// The inner handle must be a `DECIMAL` logical type (requires `DuckDB` runtime).
    #[must_use]
    pub unsafe fn decimal_internal_type(&self) -> TypeId {
        TypeId::from_duckdb_type(unsafe { duckdb_decimal_internal_type(self.inner) })
    }

    /// Returns the internal storage type of an `ENUM` type.
    ///
    /// # Safety
    ///
    /// The inner handle must be an `ENUM` logical type (requires `DuckDB` runtime).
    #[must_use]
    pub unsafe fn enum_internal_type(&self) -> TypeId {
        TypeId::from_duckdb_type(unsafe { duckdb_enum_internal_type(self.inner) })
    }

    /// Returns the number of members in an `ENUM` type.
    ///
    /// # Safety
    ///
    /// The inner handle must be an `ENUM` logical type (requires `DuckDB` runtime).
    #[must_use]
    pub unsafe fn enum_dictionary_size(&self) -> u32 {
        unsafe { duckdb_enum_dictionary_size(self.inner) }
    }

    /// Returns the name of the enum member at `index`.
    ///
    /// # Safety
    ///
    /// The inner handle must be an `ENUM` logical type and `index` must be
    /// within bounds (requires `DuckDB` runtime).
    ///
    /// # Panics
    ///
    /// Panics if `duckdb_enum_dictionary_value` returns a null pointer.
    #[must_use]
    pub unsafe fn enum_dictionary_value(&self, index: u64) -> String {
        let ptr =
            unsafe { duckdb_enum_dictionary_value(self.inner, index as libduckdb_sys::idx_t) };
        assert!(!ptr.is_null(), "duckdb_enum_dictionary_value returned null");
        let s = unsafe { std::ffi::CStr::from_ptr(ptr) }
            .to_string_lossy()
            .into_owned();
        unsafe { duckdb_free(ptr.cast::<core::ffi::c_void>()) };
        s
    }

    /// Returns the child (element) type of a `LIST` type.
    ///
    /// # Safety
    ///
    /// The inner handle must be a `LIST` logical type (requires `DuckDB` runtime).
    #[must_use]
    pub unsafe fn list_child_type(&self) -> Self {
        unsafe { Self::from_raw(duckdb_list_type_child_type(self.inner)) }
    }

    /// Returns the key type of a `MAP` type.
    ///
    /// # Safety
    ///
    /// The inner handle must be a `MAP` logical type (requires `DuckDB` runtime).
    #[must_use]
    pub unsafe fn map_key_type(&self) -> Self {
        unsafe { Self::from_raw(duckdb_map_type_key_type(self.inner)) }
    }

    /// Returns the value type of a `MAP` type.
    ///
    /// # Safety
    ///
    /// The inner handle must be a `MAP` logical type (requires `DuckDB` runtime).
    #[must_use]
    pub unsafe fn map_value_type(&self) -> Self {
        unsafe { Self::from_raw(duckdb_map_type_value_type(self.inner)) }
    }

    /// Returns the number of child fields in a `STRUCT` type.
    ///
    /// # Safety
    ///
    /// The inner handle must be a `STRUCT` logical type (requires `DuckDB` runtime).
    #[must_use]
    pub unsafe fn struct_child_count(&self) -> u64 {
        unsafe { duckdb_struct_type_child_count(self.inner) as u64 }
    }

    /// Returns the name of the struct field at `index`.
    ///
    /// # Safety
    ///
    /// The inner handle must be a `STRUCT` logical type and `index` must be
    /// within bounds (requires `DuckDB` runtime).
    ///
    /// # Panics
    ///
    /// Panics if `duckdb_struct_type_child_name` returns a null pointer.
    #[must_use]
    pub unsafe fn struct_child_name(&self, index: u64) -> String {
        unsafe {
            let ptr = duckdb_struct_type_child_name(self.inner, index as libduckdb_sys::idx_t);
            assert!(
                !ptr.is_null(),
                "duckdb_struct_type_child_name returned null"
            );
            let s = std::ffi::CStr::from_ptr(ptr).to_string_lossy().into_owned();
            duckdb_free(ptr.cast::<core::ffi::c_void>());
            s
        }
    }

    /// Returns the type of the struct field at `index`.
    ///
    /// # Safety
    ///
    /// The inner handle must be a `STRUCT` logical type and `index` must be
    /// within bounds (requires `DuckDB` runtime).
    #[must_use]
    pub unsafe fn struct_child_type(&self, index: u64) -> Self {
        unsafe {
            Self::from_raw(duckdb_struct_type_child_type(
                self.inner,
                index as libduckdb_sys::idx_t,
            ))
        }
    }

    /// Returns the number of members in a `UNION` type.
    ///
    /// # Safety
    ///
    /// The inner handle must be a `UNION` logical type (requires `DuckDB` runtime).
    #[must_use]
    pub unsafe fn union_member_count(&self) -> u64 {
        unsafe { duckdb_union_type_member_count(self.inner) as u64 }
    }

    /// Returns the name of the union member at `index`.
    ///
    /// # Safety
    ///
    /// The inner handle must be a `UNION` logical type and `index` must be
    /// within bounds (requires `DuckDB` runtime).
    ///
    /// # Panics
    ///
    /// Panics if `duckdb_union_type_member_name` returns a null pointer.
    #[must_use]
    pub unsafe fn union_member_name(&self, index: u64) -> String {
        unsafe {
            let ptr = duckdb_union_type_member_name(self.inner, index as libduckdb_sys::idx_t);
            assert!(
                !ptr.is_null(),
                "duckdb_union_type_member_name returned null"
            );
            let s = std::ffi::CStr::from_ptr(ptr).to_string_lossy().into_owned();
            duckdb_free(ptr.cast::<core::ffi::c_void>());
            s
        }
    }

    /// Returns the type of the union member at `index`.
    ///
    /// # Safety
    ///
    /// The inner handle must be a `UNION` logical type and `index` must be
    /// within bounds (requires `DuckDB` runtime).
    #[must_use]
    pub unsafe fn union_member_type(&self, index: u64) -> Self {
        unsafe {
            Self::from_raw(duckdb_union_type_member_type(
                self.inner,
                index as libduckdb_sys::idx_t,
            ))
        }
    }

    /// Returns the fixed size of an `ARRAY` type.
    ///
    /// # Safety
    ///
    /// The inner handle must be an `ARRAY` logical type (requires `DuckDB` runtime).
    #[must_use]
    pub unsafe fn array_size(&self) -> u64 {
        unsafe { duckdb_array_type_array_size(self.inner) as u64 }
    }

    /// Returns the child (element) type of an `ARRAY` type.
    ///
    /// # Safety
    ///
    /// The inner handle must be an `ARRAY` logical type (requires `DuckDB` runtime).
    #[must_use]
    pub unsafe fn array_child_type(&self) -> Self {
        unsafe { Self::from_raw(duckdb_array_type_child_type(self.inner)) }
    }

    /// Returns the underlying raw `duckdb_logical_type` handle.
    ///
    /// # Safety note
    ///
    /// Do not call `duckdb_destroy_logical_type` on the returned handle; that is
    /// handled by this type's `Drop` implementation.
    #[must_use]
    #[inline]
    pub const fn as_raw(&self) -> duckdb_logical_type {
        self.inner
    }

    /// Consumes this `LogicalType` and returns the raw handle without destroying it.
    ///
    /// The caller is responsible for calling `duckdb_destroy_logical_type` on the
    /// returned handle.
    #[must_use]
    pub const fn into_raw(self) -> duckdb_logical_type {
        let raw = self.inner;
        // Prevent Drop from running by wrapping in ManuallyDrop
        std::mem::forget(self);
        raw
    }
}

impl Drop for LogicalType {
    #[mutants::skip]
    fn drop(&mut self) {
        // SAFETY: `self.inner` was created by `duckdb_create_logical_type` and has not
        // been transferred elsewhere. It is safe to destroy exactly once here.
        unsafe {
            duckdb_destroy_logical_type(&raw mut self.inner);
        }
    }
}

impl From<TypeId> for LogicalType {
    /// Creates a `LogicalType` from a `TypeId`.
    ///
    /// This is equivalent to calling [`LogicalType::new`].
    fn from(type_id: TypeId) -> Self {
        Self::new(type_id)
    }
}

// LogicalType is not Clone or Copy because the underlying handle is not reference-counted.
// If you need to pass it to multiple places, use `as_raw()` to borrow the handle temporarily.

#[cfg(test)]
mod tests {
    // Note: LogicalType tests that call DuckDB API (duckdb_create_logical_type)
    // require a running DuckDB runtime and are covered in tests/integration_test.rs.
    // The `loadable-extension` feature uses lazy-initialized function pointers
    // that cannot be called without a prior call to duckdb_rs_extension_api_init.

    #[test]
    fn logical_type_error_display() {
        let err = super::LogicalTypeError {
            api_func: "duckdb_create_logical_type",
        };
        assert_eq!(err.to_string(), "duckdb_create_logical_type returned null");
    }

    #[test]
    fn size_of_logical_type_struct() {
        use super::LogicalType;
        // LogicalType must be pointer-sized (it contains a single pointer).
        assert_eq!(
            std::mem::size_of::<LogicalType>(),
            std::mem::size_of::<*mut ()>()
        );
    }
}