Skip to main content

quack_rs/
catalog.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//! Catalog entry lookup (`DuckDB` 1.5.0+).
7//!
8//! Provides read-only access to catalog entries (tables, views, types, etc.)
9//! from within extension callbacks.
10//!
11//! # Lookups that could autoload an extension are refused
12//!
13//! `duckdb_catalog_get_entry` has no `try`/`catch`. When a `TYPE` or
14//! `COLLATION` lookup misses, `DuckDB` 1.5.5 tries to autoload the extension
15//! that owns the name — `json` and `inet` for types, `icu` for 130 collation
16//! names such as `de` or `en_us` — even though the lookup asked for
17//! `RETURN_NULL` (`Catalog::GetEntry` → `AutoLoadExtensionByCatalogEntry`,
18//! `src/catalog/catalog.cpp`). If that autoload fails (autoinstall off and the
19//! extension not installed, no network, a signature problem, ...),
20//! `ExtensionHelper::AutoLoadExtension` rethrows, the exception crosses the C
21//! API and the process aborts. If it succeeds, a catalog *lookup* has just
22//! downloaded and loaded an extension.
23//!
24//! The C API offers no way to ask whether that extension is already loaded
25//! from a client context, so [`CatalogEntry::lookup`] refuses — with an
26//! `Err`, without calling `DuckDB` — a `Type` or `Collation` lookup whose name
27//! is on those lists while the `autoload_known_extensions` setting is on.
28//! With `SET autoload_known_extensions = false` no autoload is attempted and
29//! the lookup runs normally. Every other name and entry type is unaffected.
30//!
31//! # Lookups in a catalog an extension provides are refused
32//!
33//! For a catalog `DuckDB` does not implement itself — one a storage extension
34//! attaches — `duckdb_catalog_get_entry` starts that catalog's transaction
35//! (`Transaction::Get`, reached from `Catalog::TryLookupEntry`) and calls its
36//! `LookupSchema` and its schema's `LookupEntry`
37//! (`Catalog::TryLookupEntryInternal`, `catalog.cpp`), all extension code,
38//! again with no `try`. Whether they throw cannot be known
39//! from here, so [`CatalogEntry::lookup`] refuses any catalog whose type is
40//! not `"duckdb"`. `DuckDB`'s own catalogs — the database's, `temp` and
41//! `system` — all have that type.
42//!
43//! # Example
44//!
45//! ```rust,no_run
46//! use quack_rs::catalog::{CatalogEntryType, CatalogEntry};
47//! ```
48
49use std::ffi::CStr;
50
51use libduckdb_sys::{
52    duckdb_catalog, duckdb_catalog_entry_get_name, duckdb_catalog_entry_get_type,
53    duckdb_catalog_entry_type, duckdb_catalog_entry_type_DUCKDB_CATALOG_ENTRY_TYPE_COLLATION,
54    duckdb_catalog_entry_type_DUCKDB_CATALOG_ENTRY_TYPE_DATABASE,
55    duckdb_catalog_entry_type_DUCKDB_CATALOG_ENTRY_TYPE_INDEX,
56    duckdb_catalog_entry_type_DUCKDB_CATALOG_ENTRY_TYPE_INVALID,
57    duckdb_catalog_entry_type_DUCKDB_CATALOG_ENTRY_TYPE_PREPARED_STATEMENT,
58    duckdb_catalog_entry_type_DUCKDB_CATALOG_ENTRY_TYPE_SCHEMA,
59    duckdb_catalog_entry_type_DUCKDB_CATALOG_ENTRY_TYPE_SEQUENCE,
60    duckdb_catalog_entry_type_DUCKDB_CATALOG_ENTRY_TYPE_TABLE,
61    duckdb_catalog_entry_type_DUCKDB_CATALOG_ENTRY_TYPE_TYPE,
62    duckdb_catalog_entry_type_DUCKDB_CATALOG_ENTRY_TYPE_VIEW, duckdb_catalog_get_entry,
63    duckdb_catalog_get_type_name, duckdb_client_context, duckdb_client_context_get_config_option,
64    duckdb_config_option_scope, duckdb_destroy_catalog, duckdb_destroy_catalog_entry,
65};
66
67use crate::error::ExtensionError;
68
69/// Type names that make `DuckDB` 1.5.5 autoload an extension when a lookup
70/// does not find them in the catalog (`EXTENSION_TYPES` in
71/// `src/include/duckdb/main/extension_entries.hpp`).
72const AUTOLOADING_TYPE_NAMES: &[&str] = &["json", "inet"];
73
74/// Collation names that make `DuckDB` 1.5.5 autoload the `icu` extension when
75/// a lookup does not find them in the catalog (`EXTENSION_COLLATIONS` in
76/// `src/include/duckdb/main/extension_entries.hpp`).
77const AUTOLOADING_COLLATION_NAMES: &[&str] = &[
78    "af", "am", "ar", "ar_sa", "as", "az", "be", "bg", "bn", "bo", "br", "bs", "ca", "ceb", "chr",
79    "cs", "cy", "da", "de", "de_at", "dsb", "dz", "ee", "el", "en", "en_us", "eo", "es", "et",
80    "fa", "fa_af", "ff", "fi", "fil", "fo", "fr", "fr_ca", "fy", "ga", "gl", "gu", "ha", "haw",
81    "he", "he_il", "hi", "hr", "hsb", "hu", "hy", "id", "id_id", "ig", "is", "it", "ja", "ka",
82    "kk", "kl", "km", "kn", "ko", "kok", "ku", "ky", "lb", "lkt", "ln", "lo", "lt", "lv", "mk",
83    "ml", "mn", "mr", "ms", "mt", "my", "nb", "nb_no", "ne", "nl", "nn", "om", "or", "pa", "pa_in",
84    "pl", "ps", "pt", "ro", "ru", "sa", "se", "si", "sk", "sl", "smn", "sq", "sr", "sr_ba",
85    "sr_me", "sr_rs", "sv", "sw", "ta", "te", "th", "tk", "to", "tr", "ug", "uk", "ur", "uz", "vi",
86    "wae", "wo", "xh", "yi", "yo", "yue", "yue_cn", "zh", "zh_cn", "zh_hk", "zh_mo", "zh_sg",
87    "zh_tw", "zu",
88];
89
90/// Types of entries in the `DuckDB` catalog.
91#[derive(Debug, Clone, Copy, PartialEq, Eq)]
92#[non_exhaustive]
93pub enum CatalogEntryType {
94    /// Invalid catalog entry.
95    Invalid,
96    /// A table.
97    Table,
98    /// A view.
99    View,
100    /// An index.
101    Index,
102    /// A schema.
103    Schema,
104    /// A prepared statement.
105    PreparedStatement,
106    /// A sequence.
107    Sequence,
108    /// A collation.
109    Collation,
110    /// A user-defined type.
111    Type,
112    /// A database.
113    Database,
114}
115
116impl CatalogEntryType {
117    /// Converts to the `DuckDB` C API constant.
118    #[must_use]
119    pub(crate) const fn to_raw(self) -> duckdb_catalog_entry_type {
120        match self {
121            Self::Invalid => duckdb_catalog_entry_type_DUCKDB_CATALOG_ENTRY_TYPE_INVALID,
122            Self::Table => duckdb_catalog_entry_type_DUCKDB_CATALOG_ENTRY_TYPE_TABLE,
123            Self::View => duckdb_catalog_entry_type_DUCKDB_CATALOG_ENTRY_TYPE_VIEW,
124            Self::Index => duckdb_catalog_entry_type_DUCKDB_CATALOG_ENTRY_TYPE_INDEX,
125            Self::Schema => duckdb_catalog_entry_type_DUCKDB_CATALOG_ENTRY_TYPE_SCHEMA,
126            Self::PreparedStatement => {
127                duckdb_catalog_entry_type_DUCKDB_CATALOG_ENTRY_TYPE_PREPARED_STATEMENT
128            }
129            Self::Sequence => duckdb_catalog_entry_type_DUCKDB_CATALOG_ENTRY_TYPE_SEQUENCE,
130            Self::Collation => duckdb_catalog_entry_type_DUCKDB_CATALOG_ENTRY_TYPE_COLLATION,
131            Self::Type => duckdb_catalog_entry_type_DUCKDB_CATALOG_ENTRY_TYPE_TYPE,
132            Self::Database => duckdb_catalog_entry_type_DUCKDB_CATALOG_ENTRY_TYPE_DATABASE,
133        }
134    }
135
136    /// Whether a lookup of `name` as this kind of entry can make `DuckDB`
137    /// autoload an extension — see the [module docs](crate::catalog).
138    ///
139    /// `DuckDB` lower-cases the name before matching it against its lists, so
140    /// this does too.
141    #[must_use]
142    pub fn may_autoload_extension(self, name: &str) -> bool {
143        let list = match self {
144            Self::Type => AUTOLOADING_TYPE_NAMES,
145            Self::Collation => AUTOLOADING_COLLATION_NAMES,
146            _ => return false,
147        };
148        let lower = name.to_lowercase();
149        list.contains(&lower.as_str())
150    }
151
152    /// Whether `duckdb_catalog_get_entry` can look this kind of entry up.
153    ///
154    /// Lookups go through a schema's catalog sets, which exist only for
155    /// tables, views, indexes, sequences, collations and types. For
156    /// `Schema`, `Database`, `PreparedStatement` and `Invalid`, `DuckDB`
157    /// 1.5.5 throws an `InternalException` ("Unsupported catalog type in
158    /// schema") from inside the C API with no `try`/`catch`, which aborts the
159    /// Rust process. [`CatalogEntry::lookup`] therefore refuses them.
160    /// (`Type` and `Collation` are supported, but a few of their *names* are
161    /// refused too; see [`may_autoload_extension`][Self::may_autoload_extension].)
162    #[must_use]
163    pub const fn is_lookup_supported(self) -> bool {
164        matches!(
165            self,
166            Self::Table | Self::View | Self::Index | Self::Sequence | Self::Collation | Self::Type
167        )
168    }
169
170    /// Converts from the `DuckDB` C API constant.
171    #[must_use]
172    pub(crate) const fn from_raw(raw: duckdb_catalog_entry_type) -> Self {
173        match raw {
174            x if x == duckdb_catalog_entry_type_DUCKDB_CATALOG_ENTRY_TYPE_TABLE => Self::Table,
175            x if x == duckdb_catalog_entry_type_DUCKDB_CATALOG_ENTRY_TYPE_VIEW => Self::View,
176            x if x == duckdb_catalog_entry_type_DUCKDB_CATALOG_ENTRY_TYPE_INDEX => Self::Index,
177            x if x == duckdb_catalog_entry_type_DUCKDB_CATALOG_ENTRY_TYPE_SCHEMA => Self::Schema,
178            x if x == duckdb_catalog_entry_type_DUCKDB_CATALOG_ENTRY_TYPE_PREPARED_STATEMENT => {
179                Self::PreparedStatement
180            }
181            x if x == duckdb_catalog_entry_type_DUCKDB_CATALOG_ENTRY_TYPE_SEQUENCE => {
182                Self::Sequence
183            }
184            x if x == duckdb_catalog_entry_type_DUCKDB_CATALOG_ENTRY_TYPE_COLLATION => {
185                Self::Collation
186            }
187            x if x == duckdb_catalog_entry_type_DUCKDB_CATALOG_ENTRY_TYPE_TYPE => Self::Type,
188            x if x == duckdb_catalog_entry_type_DUCKDB_CATALOG_ENTRY_TYPE_DATABASE => {
189                Self::Database
190            }
191            _ => Self::Invalid,
192        }
193    }
194}
195
196/// A catalog entry found by [`CatalogEntry::lookup`]: its name and type, as
197/// they were at lookup time.
198///
199/// # Why this holds copies rather than the handle
200///
201/// A `duckdb_catalog_entry` is a plain reference to `DuckDB`'s own
202/// `CatalogEntry` (`CCatalogEntryWrapper { CatalogEntry &entry; }`,
203/// `catalog-c.cpp`), valid only while the transaction that found it lasts.
204/// Kept in a value with safe methods, it outlived that: after a
205/// `DROP TABLE` and a commit, `name()` returned the name of a different,
206/// newly created table, with valgrind reporting an invalid read in
207/// `duckdb_catalog_entry_get_name`. So the name and type are copied during
208/// [`lookup`][Self::lookup] and the handle is released there.
209#[derive(Debug, Clone, PartialEq, Eq)]
210pub struct CatalogEntry {
211    name: Option<String>,
212    entry_type: CatalogEntryType,
213}
214
215impl CatalogEntry {
216    /// Look up a catalog entry by type, schema, and name.
217    ///
218    /// Returns `Ok(None)` if no such entry exists.
219    ///
220    /// # Errors
221    ///
222    /// Refuses, without calling `DuckDB`, a lookup that would abort the
223    /// process from inside the C API:
224    ///
225    /// - an `entry_type` that is not a schema-level entry (`Schema`,
226    ///   `Database`, `PreparedStatement`, `Invalid`) — see
227    ///   [`CatalogEntryType::is_lookup_supported`];
228    /// - a `Type` or `Collation` whose name `DuckDB` would try to autoload an
229    ///   extension for, while `autoload_known_extensions` is on — see the
230    ///   [module docs](crate::catalog) and
231    ///   [`CatalogEntryType::may_autoload_extension`];
232    /// - any lookup in a catalog that is not `DuckDB`'s own (type `"duckdb"`),
233    ///   such as one a storage extension attaches: `DuckDB` runs that
234    ///   extension's schema lookup and transaction start with no `try`, so
235    ///   whatever it throws would abort the process. This reads the catalog's
236    ///   type name, which cannot throw.
237    ///
238    /// # Safety
239    ///
240    /// - `catalog` must be a valid `duckdb_catalog` handle.
241    /// - `context` must be a valid `duckdb_client_context` handle.
242    /// - Must be called from within an active transaction.
243    pub unsafe fn lookup(
244        catalog: duckdb_catalog,
245        context: duckdb_client_context,
246        schema: &CStr,
247        name: &CStr,
248        entry_type: CatalogEntryType,
249    ) -> Result<Option<Self>, ExtensionError> {
250        if !entry_type.is_lookup_supported() {
251            return Err(ExtensionError::new(format!(
252                "catalog lookup of a {entry_type:?} entry is not supported: DuckDB throws \
253                 \"Unsupported catalog type in schema\" through the C API, which would abort \
254                 the process"
255            )));
256        }
257        // SAFETY: `catalog` is valid per this function's contract; the type
258        // name is owned by the catalog wrapper and read before it is dropped.
259        let catalog_type = unsafe {
260            let ptr = duckdb_catalog_get_type_name(catalog);
261            (!ptr.is_null()).then(|| CStr::from_ptr(ptr).to_string_lossy().into_owned())
262        };
263        if !is_duckdb_catalog(catalog_type.as_deref()) {
264            return Err(ExtensionError::new(format!(
265                "catalog lookup refused in a catalog of type {catalog_type:?}: DuckDB runs the \
266                 lookup of a catalog it does not implement itself with no try/catch, so an \
267                 exception there would abort the process. Query the catalog with SQL instead."
268            )));
269        }
270        let lossy_name = name.to_string_lossy();
271        // SAFETY: `context` is valid per this function's contract.
272        if entry_type.may_autoload_extension(&lossy_name) && unsafe { autoload_enabled(context) } {
273            return Err(ExtensionError::new(format!(
274                "catalog lookup of {entry_type:?} '{lossy_name}' refused: on a miss DuckDB \
275                 autoloads the extension that owns this name, and a failed autoload throws \
276                 through the C API and aborts the process. Run \
277                 `SET autoload_known_extensions = false` first to look it up safely."
278            )));
279        }
280        // SAFETY: catalog, context, schema, and name are valid per caller's contract.
281        let entry = unsafe {
282            duckdb_catalog_get_entry(
283                catalog,
284                context,
285                entry_type.to_raw(),
286                schema.as_ptr(),
287                name.as_ptr(),
288            )
289        };
290        if entry.is_null() {
291            return Ok(None);
292        }
293        // SAFETY: `entry` is the fresh, non-null wrapper DuckDB just returned,
294        // and the transaction that found it is still active per this
295        // function's contract, so the entry it refers to is live. The name is
296        // copied out before the wrapper is destroyed below.
297        let (name, raw_type) = unsafe {
298            let ptr = duckdb_catalog_entry_get_name(entry);
299            let name = (!ptr.is_null())
300                .then(|| CStr::from_ptr(ptr).to_str().ok().map(str::to_owned))
301                .flatten();
302            (name, duckdb_catalog_entry_get_type(entry))
303        };
304        let mut entry = entry;
305        // SAFETY: `entry` was returned by `duckdb_catalog_get_entry` and is
306        // destroyed once; destroying the wrapper does not touch the entry.
307        unsafe { duckdb_destroy_catalog_entry(&raw mut entry) };
308        Ok(Some(Self {
309            name,
310            entry_type: CatalogEntryType::from_raw(raw_type),
311        }))
312    }
313
314    /// Returns the name of this catalog entry, as it was at lookup time.
315    ///
316    /// Returns `None` if the name is not valid UTF-8.
317    #[must_use]
318    pub fn name(&self) -> Option<&str> {
319        self.name.as_deref()
320    }
321
322    /// Returns the type of this catalog entry, as it was at lookup time.
323    ///
324    /// A lookup for [`CatalogEntryType::Table`] also finds a view of that name
325    /// (`DuckDB` resolves both through the same table-or-view lookup), so
326    /// check this when the difference matters.
327    #[must_use]
328    pub const fn entry_type(&self) -> CatalogEntryType {
329        self.entry_type
330    }
331}
332
333/// RAII wrapper for a `duckdb_catalog`.
334///
335/// Automatically destroyed when dropped.
336pub struct Catalog {
337    catalog: duckdb_catalog,
338}
339
340impl Catalog {
341    /// Creates a `Catalog` from a raw handle.
342    ///
343    /// # Safety
344    ///
345    /// `catalog` must be a valid, non-null `duckdb_catalog` handle.
346    pub(crate) const unsafe fn from_raw(catalog: duckdb_catalog) -> Self {
347        Self { catalog }
348    }
349
350    /// Returns the raw handle for use with [`CatalogEntry::lookup`].
351    #[must_use]
352    pub const fn as_raw(&self) -> duckdb_catalog {
353        self.catalog
354    }
355
356    /// Returns the type name of this catalog: `"duckdb"` for every catalog
357    /// `DuckDB` provides itself (the database's, `temp` and `system`), or a
358    /// storage extension's name like `"sqlite"`.
359    ///
360    /// Returns `None` if the name is not valid UTF-8.
361    #[must_use]
362    pub fn type_name(&self) -> Option<&str> {
363        // SAFETY: self.catalog is valid per constructor contract. The returned
364        // pointer is owned by DuckDB and remains valid while the catalog lives.
365        let ptr = unsafe { duckdb_catalog_get_type_name(self.catalog) };
366        if ptr.is_null() {
367            return None;
368        }
369        // SAFETY: ptr is a valid null-terminated UTF-8 string owned by DuckDB.
370        unsafe { CStr::from_ptr(ptr) }.to_str().ok()
371    }
372
373    /// Look up a catalog entry by type, schema, and name.
374    ///
375    /// Returns `Ok(None)` if no such entry exists.
376    ///
377    /// # Errors
378    ///
379    /// Returns an error, without calling `DuckDB`, for a lookup that would
380    /// abort the process; see [`CatalogEntry::lookup`].
381    ///
382    /// # Safety
383    ///
384    /// - `context` must be a valid `duckdb_client_context`.
385    /// - Must be called from within an active transaction context.
386    /// - The database this catalog belongs to must still be attached, and the
387    ///   transaction in which [`ClientContext::catalog`] returned it must still
388    ///   be active. A `duckdb_catalog` is a plain reference to `DuckDB`'s
389    ///   `Catalog` (`CCatalogWrapper`, `catalog-c.cpp`): after a `DETACH`,
390    ///   a lookup through it read freed memory and crashed in testing.
391    ///
392    /// [`ClientContext::catalog`]: crate::client_context::ClientContext::catalog
393    pub unsafe fn get_entry(
394        &self,
395        context: duckdb_client_context,
396        schema: &CStr,
397        name: &CStr,
398        entry_type: CatalogEntryType,
399    ) -> Result<Option<CatalogEntry>, ExtensionError> {
400        // SAFETY: self.catalog and context are valid, caller ensures active transaction.
401        unsafe { CatalogEntry::lookup(self.catalog, context, schema, name, entry_type) }
402    }
403}
404
405impl Drop for Catalog {
406    fn drop(&mut self) {
407        // SAFETY: self.catalog was obtained from duckdb_client_context_get_catalog.
408        unsafe {
409            duckdb_destroy_catalog(&raw mut self.catalog);
410        }
411    }
412}
413
414/// Whether a catalog of type `name` is `DuckDB`'s own: `DuckCatalog` is the
415/// only catalog in `DuckDB` itself (`duck_catalog.hpp`), and its type is
416/// `"duckdb"`. The database's catalog, `temp` and `system` are all one. Any
417/// other type comes from an extension.
418fn is_duckdb_catalog(name: Option<&str>) -> bool {
419    name == Some("duckdb")
420}
421
422/// Whether `DuckDB` would try to autoload an extension on a catalog miss.
423///
424/// Reads the `autoload_known_extensions` setting (it always exists, so this
425/// never takes the missing-setting path described on
426/// [`ClientContext::config_option`][crate::client_context::ClientContext::config_option]).
427/// Anything but a readable `false` counts as enabled.
428///
429/// # Safety
430///
431/// `context` must be a valid `duckdb_client_context`.
432unsafe fn autoload_enabled(context: duckdb_client_context) -> bool {
433    let mut scope: duckdb_config_option_scope = 0;
434    // SAFETY: `context` is valid per this function's contract.
435    let raw = unsafe {
436        duckdb_client_context_get_config_option(
437            context,
438            c"autoload_known_extensions".as_ptr(),
439            &raw mut scope,
440        )
441    };
442    if raw.is_null() {
443        return true;
444    }
445    // SAFETY: the call returns an owned value; `Value` destroys it.
446    let value = unsafe { crate::value::Value::from_raw(raw) };
447    value.as_bool() != Some(false)
448}
449
450crate::debug_repr::impl_handle_debug!(Catalog.catalog);
451
452#[cfg(test)]
453mod tests {
454    use super::*;
455
456    #[test]
457    fn only_duckdbs_own_catalog_type_is_looked_up() {
458        assert!(is_duckdb_catalog(Some("duckdb")));
459        for other in [
460            None,
461            Some(""),
462            Some("sqlite"),
463            Some("postgres"),
464            Some("DuckDB"),
465        ] {
466            assert!(!is_duckdb_catalog(other), "{other:?}");
467        }
468    }
469
470    #[test]
471    fn catalog_entry_type_round_trip_all_variants() {
472        let variants = [
473            CatalogEntryType::Invalid,
474            CatalogEntryType::Table,
475            CatalogEntryType::View,
476            CatalogEntryType::Index,
477            CatalogEntryType::Schema,
478            CatalogEntryType::PreparedStatement,
479            CatalogEntryType::Sequence,
480            CatalogEntryType::Collation,
481            CatalogEntryType::Type,
482            CatalogEntryType::Database,
483        ];
484        for variant in variants {
485            let raw = variant.to_raw();
486            let back = CatalogEntryType::from_raw(raw);
487            assert_eq!(variant, back, "round-trip failed for {variant:?}");
488        }
489    }
490
491    #[test]
492    fn only_schema_level_entry_types_are_lookup_supported() {
493        use CatalogEntryType as T;
494        for t in [
495            T::Table,
496            T::View,
497            T::Index,
498            T::Sequence,
499            T::Collation,
500            T::Type,
501        ] {
502            assert!(t.is_lookup_supported(), "{t:?}");
503        }
504        for t in [T::Schema, T::Database, T::PreparedStatement, T::Invalid] {
505            assert!(!t.is_lookup_supported(), "{t:?}");
506        }
507    }
508
509    #[test]
510    fn autoloading_names_match_duckdb_case_insensitively() {
511        assert!(CatalogEntryType::Type.may_autoload_extension("inet"));
512        assert!(CatalogEntryType::Type.may_autoload_extension("JSON"));
513        assert!(CatalogEntryType::Collation.may_autoload_extension("de"));
514        assert!(CatalogEntryType::Collation.may_autoload_extension("EN_US"));
515        assert!(CatalogEntryType::Collation.may_autoload_extension("zu"));
516        assert!(!CatalogEntryType::Type.may_autoload_extension("my_type"));
517        assert!(!CatalogEntryType::Type.may_autoload_extension("de"));
518        assert!(!CatalogEntryType::Table.may_autoload_extension("inet"));
519        assert!(!CatalogEntryType::Collation.may_autoload_extension("nocase"));
520        assert_eq!(AUTOLOADING_COLLATION_NAMES.len(), 130);
521    }
522
523    #[test]
524    fn lookup_of_an_unsupported_type_is_refused_without_calling_duckdb() {
525        // Null handles and no live DuckDB: this only passes because `lookup`
526        // returns before making any FFI call for these types.
527        for t in [
528            CatalogEntryType::Schema,
529            CatalogEntryType::Database,
530            CatalogEntryType::PreparedStatement,
531            CatalogEntryType::Invalid,
532        ] {
533            // SAFETY: returns before touching either handle.
534            let entry = unsafe {
535                CatalogEntry::lookup(
536                    std::ptr::null_mut(),
537                    std::ptr::null_mut(),
538                    c"main",
539                    c"main",
540                    t,
541                )
542            };
543            let err = entry
544                .err()
545                .unwrap_or_else(|| panic!("{t:?} must be refused"));
546            assert!(err.as_str().contains("not supported"), "{t:?}: {err}");
547        }
548    }
549
550    #[test]
551    fn catalog_entry_type_unknown_raw_maps_to_invalid() {
552        // Any unknown value should map to Invalid.
553        let result = CatalogEntryType::from_raw(9999);
554        assert_eq!(result, CatalogEntryType::Invalid);
555    }
556
557    #[test]
558    fn catalog_entry_type_debug_impl() {
559        let s = format!("{:?}", CatalogEntryType::View);
560        assert_eq!(s, "View");
561    }
562
563    #[test]
564    fn catalog_entry_type_distinct_raw_values() {
565        // Ensure no two variants share the same raw value.
566        let variants = [
567            CatalogEntryType::Invalid,
568            CatalogEntryType::Table,
569            CatalogEntryType::View,
570            CatalogEntryType::Index,
571            CatalogEntryType::Schema,
572            CatalogEntryType::PreparedStatement,
573            CatalogEntryType::Sequence,
574            CatalogEntryType::Collation,
575            CatalogEntryType::Type,
576            CatalogEntryType::Database,
577        ];
578        let raws: Vec<duckdb_catalog_entry_type> = variants.iter().map(|v| v.to_raw()).collect();
579        // Invalid is 0; every non-Invalid variant must differ from each other.
580        for (i, a) in raws.iter().enumerate().skip(1) {
581            for b in raws.iter().skip(i + 1) {
582                assert_ne!(a, b, "two non-Invalid variants share raw value {a}");
583            }
584        }
585    }
586}