Skip to main content

quack_rs/
table_description.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//! Table description metadata.
7//!
8//! Allows querying a table's structure — column names, whether a column has a
9//! `DEFAULT`, and (with `duckdb-1-5`) the column count and types — at runtime
10//! from within an extension. Useful for replacement scans, table functions, and
11//! copy functions that need to inspect existing tables before deciding what to
12//! do.
13//!
14//! # Feature flags
15//!
16//! Creating and naming columns needs no feature flag: `duckdb_table_description_*`
17//! has been in the frozen stable prefix of the extension API (slots 292–297)
18//! since v1.2.0. Two accessors are `DuckDB` 1.5.0 additions living in the
19//! unstable region and are gated on `duckdb-1-5`: `column_count` and
20//! `column_type`. They are not linked here because the links would not resolve
21//! when the feature is off, which is exactly when a reader most wants to know
22//! they exist.
23//!
24//! # Example
25//!
26//! ```rust,no_run
27//! use quack_rs::table_description::TableDescription;
28//!
29//! // From within a function callback with a valid connection:
30//! // let desc = unsafe { TableDescription::create(con, "main", "my_table")? };
31//! // let first = desc.column_name(0);
32//! ```
33
34use std::ffi::{CStr, CString};
35
36use libduckdb_sys::{
37    duckdb_column_has_default, duckdb_connection, duckdb_table_description,
38    duckdb_table_description_create, duckdb_table_description_create_ext,
39    duckdb_table_description_destroy, duckdb_table_description_error,
40    duckdb_table_description_get_column_name, idx_t, DuckDBSuccess,
41};
42#[cfg(feature = "duckdb-1-5")]
43use libduckdb_sys::{
44    duckdb_table_description_get_column_count, duckdb_table_description_get_column_type,
45};
46
47use crate::error::ExtensionError;
48#[cfg(feature = "duckdb-1-5")]
49use crate::types::LogicalType;
50
51/// RAII wrapper for a `duckdb_table_description`.
52///
53/// Provides metadata about a table's columns. Automatically destroyed on drop.
54pub struct TableDescription {
55    desc: duckdb_table_description,
56}
57
58impl TableDescription {
59    /// Creates a table description for the given schema and table.
60    ///
61    /// # Errors
62    ///
63    /// Returns `ExtensionError` if the table does not exist or cannot be described.
64    ///
65    /// # Safety
66    ///
67    /// `con` must be a valid, open `duckdb_connection`.
68    pub unsafe fn create(
69        con: duckdb_connection,
70        schema: &str,
71        table: &str,
72    ) -> Result<Self, ExtensionError> {
73        let c_schema = CString::new(schema)
74            .map_err(|_| ExtensionError::new("schema name contains null byte"))?;
75        let c_table = CString::new(table)
76            .map_err(|_| ExtensionError::new("table name contains null byte"))?;
77
78        let mut desc: duckdb_table_description = core::ptr::null_mut();
79        // SAFETY: con is valid per caller's contract.
80        let rc = unsafe {
81            duckdb_table_description_create(con, c_schema.as_ptr(), c_table.as_ptr(), &raw mut desc)
82        };
83
84        // SAFETY: `desc` is whatever DuckDB wrote; the helper takes ownership
85        // from here, including destroying it on the error path.
86        unsafe { Self::from_create_result(rc, desc, schema, table) }
87    }
88
89    /// Turns a `duckdb_table_description_create*` outcome into a `Result`.
90    ///
91    /// `duckdb.h` requires `duckdb_table_description_destroy` to be called on
92    /// the result "even if the function returns `DuckDBError`", so the failure
93    /// path must destroy the handle rather than simply dropping it — and it
94    /// must read the error message first, because destroying frees it.
95    ///
96    /// # Safety
97    ///
98    /// `desc` must be the out-parameter of a `duckdb_table_description_create*`
99    /// call that returned `rc`, and must not be used by the caller afterwards.
100    unsafe fn from_create_result(
101        rc: libduckdb_sys::duckdb_state,
102        mut desc: duckdb_table_description,
103        schema: &str,
104        table: &str,
105    ) -> Result<Self, ExtensionError> {
106        if rc == DuckDBSuccess && !desc.is_null() {
107            return Ok(Self { desc });
108        }
109        let mut message = format!("failed to describe table '{schema}.{table}'");
110        if !desc.is_null() {
111            // SAFETY: desc is non-null and was produced by a create call.
112            let err_ptr = unsafe { duckdb_table_description_error(desc) };
113            if !err_ptr.is_null() {
114                // SAFETY: err_ptr is a NUL-terminated string owned by the
115                // description; it stays valid until the destroy below.
116                let detail = unsafe { CStr::from_ptr(err_ptr) }
117                    .to_str()
118                    .unwrap_or("unknown error");
119                message.push_str(": ");
120                message.push_str(detail);
121            }
122            // SAFETY: desc is a non-null handle we own and have not returned.
123            unsafe { duckdb_table_description_destroy(&raw mut desc) };
124        }
125        Err(ExtensionError::new(message))
126    }
127
128    /// Creates a table description, fully qualified by optional `catalog` and
129    /// `schema`.
130    ///
131    /// `None` means "the default", matching `duckdb_table_description_create_ext`.
132    ///
133    /// # Errors
134    ///
135    /// Returns `ExtensionError` if any name contains an interior NUL byte, or
136    /// if the table does not exist or cannot be described.
137    ///
138    /// # Safety
139    ///
140    /// `con` must be a valid, open `duckdb_connection`.
141    pub unsafe fn with_catalog(
142        con: duckdb_connection,
143        catalog: Option<&str>,
144        schema: Option<&str>,
145        table: &str,
146    ) -> Result<Self, ExtensionError> {
147        fn to_c(label: &str, value: Option<&str>) -> Result<Option<CString>, ExtensionError> {
148            value
149                .map(|v| {
150                    CString::new(v)
151                        .map_err(|_| ExtensionError::new(format!("{label} contains null byte")))
152                })
153                .transpose()
154        }
155        let c_catalog = to_c("catalog name", catalog)?;
156        let c_schema = to_c("schema name", schema)?;
157        let c_table = CString::new(table)
158            .map_err(|_| ExtensionError::new("table name contains null byte"))?;
159        let ptr = |c: &Option<CString>| c.as_ref().map_or(core::ptr::null(), |v| v.as_ptr());
160
161        let mut desc: duckdb_table_description = core::ptr::null_mut();
162        // SAFETY: con is valid per caller's contract; each pointer is either
163        // null (meaning "default") or a NUL-terminated string alive for the call.
164        let rc = unsafe {
165            duckdb_table_description_create_ext(
166                con,
167                ptr(&c_catalog),
168                ptr(&c_schema),
169                c_table.as_ptr(),
170                &raw mut desc,
171            )
172        };
173        // SAFETY: `desc` is whatever DuckDB wrote; the helper takes it from here,
174        // including destroying it on the error path as duckdb.h requires.
175        unsafe { Self::from_create_result(rc, desc, schema.unwrap_or("<default>"), table) }
176    }
177
178    /// Returns the number of columns in the table.
179    #[cfg(feature = "duckdb-1-5")]
180    #[must_use]
181    pub fn column_count(&self) -> idx_t {
182        // SAFETY: self.desc is valid.
183        unsafe { duckdb_table_description_get_column_count(self.desc) }
184    }
185
186    /// Whether `index` may be passed to `DuckDB`, which bounds-checks every
187    /// index but one: from 1.5.0 the column accessors convert it to an
188    /// `optional_idx`, whose constructor throws for `idx_t::MAX`
189    /// (`optional_idx.hpp`) outside any `try` (`table_description-c.cpp`),
190    /// which aborts the process. That value names no column in any release.
191    const fn in_range(index: idx_t) -> bool {
192        index != idx_t::MAX
193    }
194
195    /// Returns the name of the column at the given index.
196    ///
197    /// Returns `None` if the index is out of bounds or the name is not valid UTF-8.
198    #[must_use]
199    pub fn column_name(&self, index: idx_t) -> Option<String> {
200        if !Self::in_range(index) {
201            return None;
202        }
203        // SAFETY: self.desc is valid. `DuckDB` returns a newly allocated string.
204        let ptr = unsafe { duckdb_table_description_get_column_name(self.desc, index) };
205        if ptr.is_null() {
206            return None;
207        }
208        // SAFETY: ptr is a valid null-terminated string allocated by `DuckDB`.
209        let result = unsafe { CStr::from_ptr(ptr) }
210            .to_str()
211            .ok()
212            .map(String::from);
213        // SAFETY: `duckdb_table_description_get_column_name` returns a `char *`
214        // DuckDB allocated (`malloc` + `memcpy`), so this owns it and must free
215        // it. Contrast `duckdb_table_description_error`, which returns a
216        // borrowed `const char *` and must not be freed — see LESSONS.md P11.
217        unsafe {
218            libduckdb_sys::duckdb_free(ptr.cast::<core::ffi::c_void>());
219        }
220        result
221    }
222
223    /// Returns the logical type of the column at the given index.
224    ///
225    /// Returns `None` if the index is out of bounds. The returned [`LogicalType`]
226    /// is RAII-managed and will be destroyed automatically on drop.
227    #[cfg(feature = "duckdb-1-5")]
228    #[must_use]
229    pub fn column_type(&self, index: idx_t) -> Option<LogicalType> {
230        if !Self::in_range(index) {
231            return None;
232        }
233        // SAFETY: self.desc is valid.
234        let lt = unsafe { duckdb_table_description_get_column_type(self.desc, index) };
235        if lt.is_null() {
236            None
237        } else {
238            // SAFETY: lt is a freshly created handle from duckdb_table_description_get_column_type.
239            Some(unsafe { LogicalType::from_raw(lt) })
240        }
241    }
242
243    /// Returns whether the column at `index` has a `DEFAULT` value.
244    ///
245    /// Returns `None` if the index is out of bounds.
246    ///
247    /// This does **not** say whether
248    /// [`Appender::append_default`][crate::appender::Appender::append_default]
249    /// will succeed. A column with no `DEFAULT` (`false` here) appends `NULL`
250    /// without error, while a column whose `DEFAULT` is not a constant —
251    /// `nextval('seq')`, `random()` — reports `true` here and makes
252    /// `append_default` fail, because the appender can only use defaults it
253    /// can evaluate once, up front.
254    #[must_use]
255    pub fn column_has_default(&self, index: idx_t) -> Option<bool> {
256        if !Self::in_range(index) {
257            return None;
258        }
259        let mut out = false;
260        // SAFETY: self.desc is valid and `index` is in range.
261        let state = unsafe { duckdb_column_has_default(self.desc, index, &raw mut out) };
262        if state == DuckDBSuccess {
263            Some(out)
264        } else {
265            None
266        }
267    }
268
269    /// Returns the raw `duckdb_table_description` handle without consuming the
270    /// wrapper. The wrapper retains ownership and destroys it on drop.
271    #[inline]
272    #[must_use]
273    pub const fn as_raw(&self) -> duckdb_table_description {
274        self.desc
275    }
276}
277
278impl Drop for TableDescription {
279    fn drop(&mut self) {
280        if !self.desc.is_null() {
281            // SAFETY: self.desc is a non-null handle obtained from
282            // duckdb_table_description_create.
283            unsafe {
284                duckdb_table_description_destroy(&raw mut self.desc);
285            }
286        }
287    }
288}
289
290#[cfg(all(test, feature = "_duckdb-testing"))]
291mod tests {
292    use super::*;
293
294    /// Opens a raw `duckdb_connection` for testing.
295    ///
296    /// Uses `InMemoryDb::open()` to ensure the dispatch table is initialized,
297    /// then opens a separate raw database + connection via `libduckdb_sys`.
298    fn open_raw_connection() -> (libduckdb_sys::duckdb_database, duckdb_connection) {
299        // Ensure dispatch table is populated.
300        let _db = crate::testing::InMemoryDb::open().unwrap();
301
302        let mut db: libduckdb_sys::duckdb_database = core::ptr::null_mut();
303        let mut con: duckdb_connection = core::ptr::null_mut();
304
305        // SAFETY: dispatch table is initialized, nullptr opens in-memory.
306        unsafe {
307            let rc = libduckdb_sys::duckdb_open(core::ptr::null(), &raw mut db);
308            assert_eq!(rc, libduckdb_sys::DuckDBSuccess, "duckdb_open failed");
309            let rc = libduckdb_sys::duckdb_connect(db, &raw mut con);
310            assert_eq!(rc, libduckdb_sys::DuckDBSuccess, "duckdb_connect failed");
311        }
312        (db, con)
313    }
314
315    /// Closes a raw connection and database.
316    ///
317    /// # Safety
318    ///
319    /// `con` and `db` must be valid handles from `open_raw_connection`.
320    unsafe fn close_raw_connection(
321        mut con: duckdb_connection,
322        mut db: libduckdb_sys::duckdb_database,
323    ) {
324        unsafe {
325            libduckdb_sys::duckdb_disconnect(&raw mut con);
326            libduckdb_sys::duckdb_close(&raw mut db);
327        }
328    }
329
330    #[test]
331    fn describe_existing_table() {
332        let (db, con) = open_raw_connection();
333
334        // Create a table to describe.
335        let sql = c"CREATE TABLE test_tbl (id INTEGER, name VARCHAR, score DOUBLE)";
336        // SAFETY: con is valid.
337        unsafe {
338            let rc = libduckdb_sys::duckdb_query(con, sql.as_ptr(), core::ptr::null_mut());
339            assert_eq!(rc, libduckdb_sys::DuckDBSuccess, "CREATE TABLE failed");
340        }
341
342        // SAFETY: con is valid, table exists.
343        let desc = unsafe { TableDescription::create(con, "main", "test_tbl") };
344        assert!(desc.is_ok(), "describe should succeed: {:?}", desc.err());
345        let desc = desc.unwrap();
346
347        // `column_count` and `column_type` are the two DuckDB 1.5 additions in
348        // this module; the names and defaults are stable-prefix.
349        #[cfg(feature = "duckdb-1-5")]
350        assert_eq!(desc.column_count(), 3);
351
352        assert_eq!(desc.column_name(0), Some("id".to_string()));
353        assert_eq!(desc.column_name(1), Some("name".to_string()));
354        assert_eq!(desc.column_name(2), Some("score".to_string()));
355
356        // Out-of-bounds index should return None.
357        assert_eq!(desc.column_name(99), None);
358
359        #[cfg(feature = "duckdb-1-5")]
360        {
361            // Column types should be non-null.
362            let lt0 = desc.column_type(0);
363            assert!(lt0.is_some(), "column_type(0) should be Some");
364            // LogicalType is RAII — automatically destroyed on drop.
365            drop(lt0);
366
367            // Out-of-bounds column type should return None.
368            assert!(desc.column_type(99).is_none());
369        }
370
371        drop(desc);
372        // SAFETY: valid handles.
373        unsafe { close_raw_connection(con, db) };
374    }
375
376    #[test]
377    fn describe_nonexistent_table_returns_error() {
378        let (db, con) = open_raw_connection();
379
380        // SAFETY: con is valid, table does NOT exist.
381        let result = unsafe { TableDescription::create(con, "main", "no_such_table") };
382        assert!(result.is_err());
383        let err_msg = result.err().unwrap().to_string();
384        assert!(
385            err_msg.contains("no_such_table"),
386            "error should mention table name, got: {err_msg}"
387        );
388
389        // SAFETY: valid handles.
390        unsafe { close_raw_connection(con, db) };
391    }
392
393    #[test]
394    fn describe_schema_null_byte_rejected() {
395        let (db, con) = open_raw_connection();
396
397        // SAFETY: con is valid.
398        let result = unsafe { TableDescription::create(con, "bad\0schema", "t") };
399        assert!(result.is_err());
400        assert!(result.err().unwrap().to_string().contains("null byte"));
401
402        // SAFETY: valid handles.
403        unsafe { close_raw_connection(con, db) };
404    }
405
406    #[test]
407    fn describe_table_null_byte_rejected() {
408        let (db, con) = open_raw_connection();
409
410        // SAFETY: con is valid.
411        let result = unsafe { TableDescription::create(con, "main", "bad\0table") };
412        assert!(result.is_err());
413        assert!(result.err().unwrap().to_string().contains("null byte"));
414
415        // SAFETY: valid handles.
416        unsafe { close_raw_connection(con, db) };
417    }
418}
419
420crate::debug_repr::impl_handle_debug!(TableDescription.desc);
421
422#[cfg(test)]
423mod index_tests {
424    use super::*;
425
426    #[test]
427    fn only_the_index_duckdb_throws_on_is_refused() {
428        assert!(!TableDescription::in_range(idx_t::MAX));
429        for index in [0, 1, 1 << 40, idx_t::MAX - 1] {
430            assert!(TableDescription::in_range(index), "{index}");
431        }
432    }
433}