Skip to main content

quack_rs/
config.rs

1// SPDX-License-Identifier: MIT
2// Copyright 2026 Tom F. <https://github.com/tomtom215/>
3// My way of giving something small back to the open source community
4// and encouraging more Rust development!
5
6//! RAII wrapper for `DuckDB` database configuration.
7//!
8//! [`DbConfig`] wraps `duckdb_config` and provides a builder-style API for
9//! setting configuration options before opening a `DuckDB` database.
10//!
11//! Extension authors typically receive an already-opened connection and do not
12//! need to open databases themselves.  `DbConfig` is useful when an extension
13//! needs to open a **secondary** `DuckDB` database from within its callbacks —
14//! for example, a virtual table that reads from another `.duckdb` file.
15//!
16//! # Example
17//!
18//! ```rust,no_run
19//! use quack_rs::config::DbConfig;
20//!
21//! // fn open_secondary() -> Result<(), quack_rs::error::ExtensionError> {
22//! //     let config = DbConfig::new()?
23//! //         .set("access_mode", "READ_ONLY")?
24//! //         .set("threads", "4")?;
25//! //     // Pass config.as_raw() to duckdb_open_ext(...)
26//! //     Ok(())
27//! // }
28//! ```
29//!
30//! # Available configuration flags
31//!
32//! Use [`DbConfig::flag_count`] and [`DbConfig::get_flag`] to enumerate all
33//! supported option names and their descriptions at runtime.
34
35use std::ffi::{CStr, CString};
36
37use libduckdb_sys::{
38    duckdb_config, duckdb_config_count, duckdb_create_config, duckdb_destroy_config,
39    duckdb_get_config_flag, duckdb_set_config, DuckDBSuccess,
40};
41
42use crate::error::ExtensionError;
43
44/// RAII wrapper for a `duckdb_config` handle.
45///
46/// Configuration options are set via [`set`][DbConfig::set] and consumed by
47/// passing [`as_raw`][DbConfig::as_raw] to `duckdb_open_ext`.
48/// The handle is destroyed automatically when [`DbConfig`] is dropped.
49#[must_use]
50pub struct DbConfig {
51    config: duckdb_config,
52}
53
54impl DbConfig {
55    /// Creates a new, empty `DuckDB` configuration object.
56    ///
57    /// # Errors
58    ///
59    /// Returns `ExtensionError` if `DuckDB` fails to allocate the config
60    /// (which is extremely rare in practice).
61    pub fn new() -> Result<Self, ExtensionError> {
62        let mut config: duckdb_config = std::ptr::null_mut();
63        // SAFETY: out_config is a valid pointer to a null duckdb_config.
64        let state = unsafe { duckdb_create_config(&raw mut config) };
65        if state == DuckDBSuccess {
66            Ok(Self { config })
67        } else {
68            Err(ExtensionError::new("duckdb_create_config failed"))
69        }
70    }
71
72    /// Sets a single configuration option.
73    ///
74    /// Common options include `"access_mode"` (`"READ_ONLY"` / `"READ_WRITE"`),
75    /// `"threads"` (number of CPU threads), and `"memory_limit"` (e.g. `"1GB"`).
76    /// Use [`DbConfig::flag_count`] / [`DbConfig::get_flag`] to enumerate all
77    /// available options at runtime.
78    ///
79    /// # Unknown option names are accepted here
80    ///
81    /// `duckdb_set_config` does **not** reject a name it does not know: it
82    /// stores it among the config's unrecognised options (an extension loaded
83    /// later may define it), and the database open that uses this config is
84    /// what fails, with `unrecognized configuration parameter`. Check a name
85    /// against [`flag_count`][Self::flag_count] / [`get_flag`][Self::get_flag]
86    /// first if you need to catch a typo at this point.
87    ///
88    /// # Errors
89    ///
90    /// Returns `ExtensionError` if `name` or `value` contain interior null bytes,
91    /// or if `DuckDB` rejects the value for an option it recognises (for
92    /// example a non-numeric `"threads"`).
93    pub fn set(self, name: &str, value: &str) -> Result<Self, ExtensionError> {
94        let c_name = CString::new(name).map_err(|_| {
95            ExtensionError::new(format!("config name '{name}' contains a null byte"))
96        })?;
97        let c_value = CString::new(value).map_err(|_| {
98            ExtensionError::new(format!("config value '{value}' contains a null byte"))
99        })?;
100        // SAFETY: self.config is a valid handle; c_name and c_value are NUL-terminated.
101        let state = unsafe { duckdb_set_config(self.config, c_name.as_ptr(), c_value.as_ptr()) };
102        if state == DuckDBSuccess {
103            Ok(self)
104        } else {
105            Err(ExtensionError::new(format!(
106                "duckdb_set_config failed for option '{name}' = '{value}'"
107            )))
108        }
109    }
110
111    /// Returns the total number of available configuration flags.
112    ///
113    /// Use this together with [`get_flag`][DbConfig::get_flag] to enumerate all
114    /// configuration options that `DuckDB` accepts.
115    #[must_use]
116    pub fn flag_count() -> usize {
117        // SAFETY: pure read of a DuckDB global table; no state required.
118        unsafe { duckdb_config_count() }
119    }
120
121    /// Returns the name and the second string `DuckDB` reports for the
122    /// configuration flag at `index`.
123    ///
124    /// For a core option or one of its aliases the second string is the
125    /// option's description. For a setting that belongs to an extension
126    /// (`s3_region`, …) it is **the extension's name** (`"httpfs"`): the third
127    /// branch of `duckdb_get_config_flag` reports `entry->extension` there,
128    /// not a description.
129    ///
130    /// `index` must be less than [`flag_count()`][DbConfig::flag_count].
131    ///
132    /// # Errors
133    ///
134    /// Returns `ExtensionError` if `index` is out of range or `DuckDB` fails
135    /// to retrieve the flag information.
136    pub fn get_flag(index: usize) -> Result<(String, String), ExtensionError> {
137        let mut name_ptr: *const std::os::raw::c_char = std::ptr::null();
138        let mut desc_ptr: *const std::os::raw::c_char = std::ptr::null();
139
140        // SAFETY: out-pointers are valid stack locations; DuckDB sets them to
141        // pointers into its own static tables (no allocation, no free needed).
142        let state = unsafe { duckdb_get_config_flag(index, &raw mut name_ptr, &raw mut desc_ptr) };
143
144        if state != DuckDBSuccess {
145            return Err(ExtensionError::new(format!(
146                "duckdb_get_config_flag({index}) failed"
147            )));
148        }
149
150        // SAFETY: DuckDB sets these pointers to valid NUL-terminated strings when
151        // the call succeeds.
152        let name = unsafe { CStr::from_ptr(name_ptr) }
153            .to_string_lossy()
154            .into_owned();
155        // SAFETY: DuckDB returned this pointer for an in-range flag index, and it
156        // points at a NUL-terminated string DuckDB owns.
157        let desc = unsafe { CStr::from_ptr(desc_ptr) }
158            .to_string_lossy()
159            .into_owned();
160
161        Ok((name, desc))
162    }
163
164    /// Returns the underlying `duckdb_config` handle.
165    ///
166    /// Pass this to `duckdb_open_ext` to open a database with these settings.
167    ///
168    /// The handle remains owned by `DbConfig`; do **not** call
169    /// `duckdb_destroy_config` on the returned value.
170    #[must_use]
171    #[inline]
172    pub const fn as_raw(&self) -> duckdb_config {
173        self.config
174    }
175}
176
177impl Drop for DbConfig {
178    fn drop(&mut self) {
179        if !self.config.is_null() {
180            // SAFETY: self.config is a valid handle allocated by duckdb_create_config.
181            unsafe {
182                duckdb_destroy_config(&raw mut self.config);
183            }
184        }
185    }
186}
187
188// Note: DbConfig calls real DuckDB C API functions (duckdb_create_config,
189// duckdb_set_config, duckdb_config_count, etc.) which are only available when
190// the loadable-extension dispatch table has been populated — i.e. inside a
191// loaded extension or after `InMemoryDb::open()`. Direct unit tests are not
192// possible without that initialization (Pitfall P9). Verify DbConfig via E2E
193// SQLLogicTests in your extension's test suite.
194
195crate::debug_repr::impl_handle_debug!(DbConfig.config);