Skip to main content

quack_rs/query/
metadata.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//! What a statement is before it runs: its [`StatementType`], parameter
7//! types and result columns, and the tables a query reads.
8
9use libduckdb_sys::{
10    duckdb_param_logical_type, duckdb_prepare_error, duckdb_prepared_statement_type,
11    duckdb_result_statement_type, duckdb_statement_type, idx_t,
12};
13
14use super::{PreparedStatement, QueryResult};
15use crate::types::LogicalType;
16
17/// What kind of SQL statement a [`PreparedStatement`] or [`QueryResult`] is,
18/// mirroring `duckdb_statement_type`.
19///
20/// `DuckDB` 1.5.5 added `COPY DATABASE`, `UPDATE EXTENSIONS` and
21/// `MERGE INTO` to the C enum; an older engine reports those three
22/// statements as [`Invalid`][Self::Invalid] (its `StatementTypeToC` has no
23/// case for them). A value from a newer `DuckDB` than this build knows is
24/// [`Other`][Self::Other].
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
26#[non_exhaustive]
27pub enum StatementType {
28    /// `DUCKDB_STATEMENT_TYPE_INVALID`: no statement, a failed prepare, or a
29    /// statement the engine's C API has no value for.
30    Invalid,
31    /// `SELECT` (and `VALUES`, `FROM t`, `WITH ...`).
32    Select,
33    /// `INSERT`.
34    Insert,
35    /// `UPDATE`.
36    Update,
37    /// `EXPLAIN`.
38    Explain,
39    /// `DELETE`.
40    Delete,
41    /// `PREPARE`.
42    Prepare,
43    /// `CREATE` (table, view, schema, sequence, type, …).
44    Create,
45    /// `EXECUTE`.
46    Execute,
47    /// `ALTER`.
48    Alter,
49    /// `BEGIN`, `COMMIT`, `ROLLBACK`.
50    Transaction,
51    /// `COPY`.
52    Copy,
53    /// `ANALYZE`.
54    Analyze,
55    /// `SET VARIABLE`.
56    VariableSet,
57    /// `CREATE FUNCTION` / `CREATE MACRO`.
58    CreateFunc,
59    /// `DROP`.
60    Drop,
61    /// `EXPORT DATABASE`.
62    Export,
63    /// `PRAGMA`.
64    Pragma,
65    /// `VACUUM`.
66    Vacuum,
67    /// `CALL`.
68    Call,
69    /// `SET` / `RESET`.
70    Set,
71    /// `LOAD`.
72    Load,
73    /// A relation built through the C++ relational API.
74    Relation,
75    /// A statement an extension's parser added.
76    Extension,
77    /// A logical plan.
78    LogicalPlan,
79    /// `ATTACH`.
80    Attach,
81    /// `DETACH`.
82    Detach,
83    /// Several statements in one.
84    Multi,
85    /// `COPY FROM DATABASE` (`DuckDB` 1.5.5+).
86    CopyDatabase,
87    /// `UPDATE EXTENSIONS` (`DuckDB` 1.5.5+).
88    UpdateExtensions,
89    /// `MERGE INTO` (`DuckDB` 1.5.5+).
90    MergeInto,
91    /// A `duckdb_statement_type` this build of quack-rs does not know.
92    Other(u32),
93}
94
95// The three values `duckdb.h` added in 1.5.5, spelled as literals so the
96// crate does not depend on the bindings declaring them (the 1.4.4 bindings do
97// not); the values are part of the C ABI.
98const COPY_DATABASE: duckdb_statement_type = 28;
99const UPDATE_EXTENSIONS: duckdb_statement_type = 29;
100const MERGE_INTO: duckdb_statement_type = 30;
101
102impl StatementType {
103    /// Converts from the C API value.
104    #[must_use]
105    pub(crate) const fn from_raw(raw: duckdb_statement_type) -> Self {
106        use libduckdb_sys as sys;
107        match raw {
108            sys::duckdb_statement_type_DUCKDB_STATEMENT_TYPE_INVALID => Self::Invalid,
109            sys::duckdb_statement_type_DUCKDB_STATEMENT_TYPE_SELECT => Self::Select,
110            sys::duckdb_statement_type_DUCKDB_STATEMENT_TYPE_INSERT => Self::Insert,
111            sys::duckdb_statement_type_DUCKDB_STATEMENT_TYPE_UPDATE => Self::Update,
112            sys::duckdb_statement_type_DUCKDB_STATEMENT_TYPE_EXPLAIN => Self::Explain,
113            sys::duckdb_statement_type_DUCKDB_STATEMENT_TYPE_DELETE => Self::Delete,
114            sys::duckdb_statement_type_DUCKDB_STATEMENT_TYPE_PREPARE => Self::Prepare,
115            sys::duckdb_statement_type_DUCKDB_STATEMENT_TYPE_CREATE => Self::Create,
116            sys::duckdb_statement_type_DUCKDB_STATEMENT_TYPE_EXECUTE => Self::Execute,
117            sys::duckdb_statement_type_DUCKDB_STATEMENT_TYPE_ALTER => Self::Alter,
118            sys::duckdb_statement_type_DUCKDB_STATEMENT_TYPE_TRANSACTION => Self::Transaction,
119            sys::duckdb_statement_type_DUCKDB_STATEMENT_TYPE_COPY => Self::Copy,
120            sys::duckdb_statement_type_DUCKDB_STATEMENT_TYPE_ANALYZE => Self::Analyze,
121            sys::duckdb_statement_type_DUCKDB_STATEMENT_TYPE_VARIABLE_SET => Self::VariableSet,
122            sys::duckdb_statement_type_DUCKDB_STATEMENT_TYPE_CREATE_FUNC => Self::CreateFunc,
123            sys::duckdb_statement_type_DUCKDB_STATEMENT_TYPE_DROP => Self::Drop,
124            sys::duckdb_statement_type_DUCKDB_STATEMENT_TYPE_EXPORT => Self::Export,
125            sys::duckdb_statement_type_DUCKDB_STATEMENT_TYPE_PRAGMA => Self::Pragma,
126            sys::duckdb_statement_type_DUCKDB_STATEMENT_TYPE_VACUUM => Self::Vacuum,
127            sys::duckdb_statement_type_DUCKDB_STATEMENT_TYPE_CALL => Self::Call,
128            sys::duckdb_statement_type_DUCKDB_STATEMENT_TYPE_SET => Self::Set,
129            sys::duckdb_statement_type_DUCKDB_STATEMENT_TYPE_LOAD => Self::Load,
130            sys::duckdb_statement_type_DUCKDB_STATEMENT_TYPE_RELATION => Self::Relation,
131            sys::duckdb_statement_type_DUCKDB_STATEMENT_TYPE_EXTENSION => Self::Extension,
132            sys::duckdb_statement_type_DUCKDB_STATEMENT_TYPE_LOGICAL_PLAN => Self::LogicalPlan,
133            sys::duckdb_statement_type_DUCKDB_STATEMENT_TYPE_ATTACH => Self::Attach,
134            sys::duckdb_statement_type_DUCKDB_STATEMENT_TYPE_DETACH => Self::Detach,
135            sys::duckdb_statement_type_DUCKDB_STATEMENT_TYPE_MULTI => Self::Multi,
136            COPY_DATABASE => Self::CopyDatabase,
137            UPDATE_EXTENSIONS => Self::UpdateExtensions,
138            MERGE_INTO => Self::MergeInto,
139            other => Self::Other(other),
140        }
141    }
142}
143
144impl PreparedStatement {
145    /// What kind of statement this is.
146    ///
147    /// Returns [`StatementType::Invalid`] for a statement whose prepare
148    /// failed (only reachable through
149    /// [`from_raw`][Self::from_raw]): on 1.x `duckdb_prepared_statement_type`
150    /// dereferences the statement data a failed prepare does not have, so it
151    /// is not called for one.
152    ///
153    /// Works on every supported `DuckDB` (stable C API slot 54).
154    ///
155    /// # Example
156    ///
157    /// ```rust,no_run
158    /// use quack_rs::query::{OwnedConnection, StatementType};
159    ///
160    /// # fn demo(con: &OwnedConnection, sql: &str) -> Result<(), quack_rs::error::ExtensionError> {
161    /// let stmt = con.prepare(sql)?;
162    /// if stmt.statement_type() != StatementType::Select {
163    ///     return Err("only SELECT statements are accepted".into());
164    /// }
165    /// # Ok(())
166    /// # }
167    /// ```
168    // Only reachable with a live statement: FFI-only, covered by
169    // tests/ffi_roundtrip/query_metadata.rs (including the failed-prepare guard).
170    #[cfg_attr(test, mutants::skip)]
171    #[must_use]
172    pub fn statement_type(&self) -> StatementType {
173        // SAFETY: `self.statement` is valid for this value's lifetime;
174        // `duckdb_prepare_error` returns null for a successful prepare and a
175        // borrowed message otherwise, and reads nothing else.
176        if !unsafe { duckdb_prepare_error(self.statement) }.is_null() {
177            return StatementType::Invalid;
178        }
179        // SAFETY: a successfully prepared statement has the data
180        // `GetStatementType` reads.
181        StatementType::from_raw(unsafe { duckdb_prepared_statement_type(self.statement) })
182    }
183
184    /// The type `DuckDB` inferred for the parameter at 1-based `index`, or
185    /// `None` when `index` is out of range or the binder could not infer a
186    /// type without a bound value (`SELECT $1`, `b || $1`).
187    ///
188    /// Once the statement has executed, `DuckDB` reports the type of the
189    /// value last bound for a parameter whose type it could not infer.
190    ///
191    /// Works on every supported `DuckDB` (stable C API slot 52).
192    // Only reachable with a live statement or connection: FFI-only, covered by
193    // tests/ffi_roundtrip/query_metadata.rs.
194    #[cfg_attr(test, mutants::skip)]
195    #[must_use]
196    pub fn parameter_type(&self, index: usize) -> Option<LogicalType> {
197        if index == 0 || index > self.parameter_count() {
198            return None;
199        }
200        // SAFETY: `self.statement` is valid and `index` is in range; DuckDB
201        // returns a new type the caller owns, or null.
202        let raw = unsafe { duckdb_param_logical_type(self.statement, index as idx_t) };
203        if raw.is_null() {
204            return None;
205        }
206        // SAFETY: `raw` is a non-null owned handle; `LogicalType` destroys it.
207        known(unsafe { LogicalType::from_raw(raw) })
208    }
209}
210
211/// `ty`, unless its id is `DUCKDB_TYPE_INVALID`, which is how `DuckDB`
212/// reports a type it has not resolved (`LogicalType::UNKNOWN` and `INVALID`
213/// both convert to it). A type id this build does not name (a `GEOMETRY`
214/// without `duckdb-1-5-3`, a type from a newer `DuckDB`) is still a type.
215// Only reachable with a live statement or connection: FFI-only, covered by
216// tests/ffi_roundtrip/query_metadata.rs.
217#[cfg_attr(test, mutants::skip)]
218fn known(ty: LogicalType) -> Option<LogicalType> {
219    // SAFETY: `ty` is a live handle (the C API is initialised: it came from it).
220    let id = unsafe { libduckdb_sys::duckdb_get_type_id(ty.as_raw()) };
221    (id != libduckdb_sys::DUCKDB_TYPE_DUCKDB_TYPE_INVALID).then_some(ty)
222}
223
224#[cfg(feature = "duckdb-1-5")]
225impl PreparedStatement {
226    /// The name and type of each column the statement returns, before it
227    /// runs (`DuckDB` 1.5.0+).
228    ///
229    /// Returns `None` when the result shape is not known until parameters
230    /// are bound: `DuckDB` then reports a single placeholder column named
231    /// `unknown` of an unresolved type (`SELECT $1`, `SELECT b || $1 FROM t`),
232    /// which is not the shape the statement returns. Also `None` for a
233    /// statement whose prepare failed. A statement that changes rows reports
234    /// the column its result has: an `INSERT` reports one `BIGINT` column,
235    /// `Count`.
236    ///
237    /// Requires `duckdb-1-5`: the four `duckdb_prepared_statement_column_*`
238    /// calls sit in the unstable region of the C API struct.
239    ///
240    /// # Example
241    ///
242    /// ```rust,no_run
243    /// # fn demo(con: &quack_rs::query::OwnedConnection) -> Result<(), quack_rs::error::ExtensionError> {
244    /// let stmt = con.prepare("SELECT 42 AS answer, 'x' AS label")?;
245    /// for (name, ty) in stmt.columns().unwrap_or_default() {
246    ///     // SAFETY: the C API is initialised (a statement exists).
247    ///     println!("{name}: {:?}", unsafe { ty.try_get_type_id() });
248    /// }
249    /// # Ok(())
250    /// # }
251    /// ```
252    // Only reachable with a live statement or connection: FFI-only, covered by
253    // tests/ffi_roundtrip/query_metadata.rs.
254    #[cfg_attr(test, mutants::skip)]
255    #[must_use]
256    pub fn columns(&self) -> Option<Vec<(String, LogicalType)>> {
257        // SAFETY: `self.statement` is valid; null means the prepare succeeded.
258        if !unsafe { duckdb_prepare_error(self.statement) }.is_null() {
259            return None;
260        }
261        // SAFETY: `self.statement` is a valid, successfully prepared statement.
262        let count =
263            unsafe { libduckdb_sys::duckdb_prepared_statement_column_count(self.statement) };
264        (0..count)
265            .map(|i| {
266                // SAFETY: `i < count`. DuckDB `strdup`s the name despite the
267                // `const char *` return (`prepared-c.cpp`, 1.4.4 to 2.0.0),
268                // so it is freed below; it returns null on a failed prepare.
269                let ptr = unsafe {
270                    libduckdb_sys::duckdb_prepared_statement_column_name(self.statement, i)
271                };
272                if ptr.is_null() {
273                    return None;
274                }
275                // SAFETY: `ptr` is NUL-terminated.
276                let name = unsafe { super::cstr::c_str_to_owned(ptr) };
277                // SAFETY: `strdup`ed by DuckDB, freed exactly once here.
278                unsafe { libduckdb_sys::duckdb_free(ptr.cast_mut().cast()) };
279                // SAFETY: `i < count`; DuckDB returns a new type the caller
280                // owns, or null.
281                let raw = unsafe {
282                    libduckdb_sys::duckdb_prepared_statement_column_logical_type(self.statement, i)
283                };
284                if raw.is_null() {
285                    return None;
286                }
287                // SAFETY: `raw` is a non-null owned handle.
288                let ty = known(unsafe { LogicalType::from_raw(raw) })?;
289                Some((name?, ty))
290            })
291            .collect()
292    }
293}
294
295impl QueryResult {
296    /// What kind of statement produced this result: for a string of several
297    /// statements, the one whose result this is (see
298    /// [`query`][super::query]).
299    ///
300    /// Works on every supported `DuckDB` (stable C API slot 17).
301    #[must_use]
302    pub fn statement_type(&self) -> StatementType {
303        // SAFETY: `duckdb_result_statement_type` takes the result by value
304        // and only reads it; it returns INVALID for a result with an error.
305        StatementType::from_raw(unsafe { duckdb_result_statement_type(self.result) })
306    }
307}
308
309/// The tables `sql` reads or writes, as `DuckDB`'s binder resolves them
310/// (`DuckDB` 1.5.0+).
311///
312/// With `qualified`, each name carries its catalog and schema as written —
313/// `main.b` for `FROM main.b`, `a` for `FROM a`; without, only the table
314/// name. Names come back in no particular order. A table function call or
315/// a CTE is not a table.
316///
317/// `sql` must be exactly one statement. `DuckDB` parses it and binds it in a
318/// names-only mode (`BindingMode::EXTRACT_NAMES`, `ClientContext::GetTableNames`),
319/// so nothing runs and the tables need not exist — but a statement whose
320/// binding needs a table's columns, such as a `JOIN … USING`, fails. It
321/// runs on `con` like a statement and needs it idle: on `DuckDB` 2.0 a
322/// streaming result open on `con` makes it fail, and before 2.0 it ends
323/// that stream.
324///
325/// # Errors
326///
327/// - `sql` contains an interior NUL byte;
328/// - `DuckDB` could not list the tables: the SQL does not parse, holds
329///   more than one statement, or binding it in that mode threw. `DuckDB`
330///   gives no reason (`duckdb_get_table_names` returns null from a
331///   `catch (...)`).
332///
333/// Requires `duckdb-1-5`: `duckdb_get_table_names` sits in the unstable
334/// region of the C API struct.
335///
336/// # Safety
337///
338/// `con` must be a valid, open `duckdb_connection`.
339// Only reachable with a live statement or connection: FFI-only, covered by
340// tests/ffi_roundtrip/query_metadata.rs.
341#[cfg_attr(test, mutants::skip)]
342#[cfg(feature = "duckdb-1-5")]
343pub unsafe fn table_names(
344    con: libduckdb_sys::duckdb_connection,
345    sql: &str,
346    qualified: bool,
347) -> Result<Vec<String>, crate::error::ExtensionError> {
348    let c_sql = super::cstr::to_c_sql(sql)?;
349    // SAFETY: `con` is valid per the caller's contract and `c_sql` outlives
350    // the call; DuckDB catches every exception and returns null, or an owned
351    // `LIST(VARCHAR)` value.
352    let raw = unsafe { libduckdb_sys::duckdb_get_table_names(con, c_sql.as_ptr(), qualified) };
353    if raw.is_null() {
354        return Err(crate::error::ExtensionError::new(
355            "duckdb_get_table_names failed: the SQL does not parse or bind (DuckDB reports no \
356             reason; prepare the statement to see the error)",
357        ));
358    }
359    // SAFETY: `raw` is a non-null owned value; `Value` destroys it.
360    let list = unsafe { crate::value::Value::from_raw(raw) };
361    list.list_items()
362        .iter()
363        .map(|name| {
364            name.as_str()
365                .map_err(|e| crate::error::ExtensionError::new(format!("table name: {e}")))
366        })
367        .collect()
368}
369
370#[cfg(test)]
371mod tests {
372    use super::*;
373
374    #[test]
375    fn every_statement_type_value_maps_to_its_variant() {
376        let named = [
377            StatementType::Invalid,
378            StatementType::Select,
379            StatementType::Insert,
380            StatementType::Update,
381            StatementType::Explain,
382            StatementType::Delete,
383            StatementType::Prepare,
384            StatementType::Create,
385            StatementType::Execute,
386            StatementType::Alter,
387            StatementType::Transaction,
388            StatementType::Copy,
389            StatementType::Analyze,
390            StatementType::VariableSet,
391            StatementType::CreateFunc,
392            StatementType::Drop,
393            StatementType::Export,
394            StatementType::Pragma,
395            StatementType::Vacuum,
396            StatementType::Call,
397            StatementType::Set,
398            StatementType::Load,
399            StatementType::Relation,
400            StatementType::Extension,
401            StatementType::LogicalPlan,
402            StatementType::Attach,
403            StatementType::Detach,
404            StatementType::Multi,
405            StatementType::CopyDatabase,
406            StatementType::UpdateExtensions,
407            StatementType::MergeInto,
408        ];
409        // `duckdb.h` numbers them 0..=30 in this order.
410        for (raw, expected) in (0_u32..).zip(named) {
411            assert_eq!(StatementType::from_raw(raw), expected, "value {raw}");
412        }
413        assert_eq!(StatementType::from_raw(31), StatementType::Other(31));
414        assert_eq!(
415            StatementType::from_raw(u32::MAX),
416            StatementType::Other(u32::MAX)
417        );
418    }
419}