Skip to main content

quack_rs/
client_context.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//! Client context access (`DuckDB` 1.5.0+).
7//!
8//! The client context provides access to the connection's catalog, configuration
9//! options, file system, and connection ID from within registered function
10//! callbacks (scalar, table, aggregate, etc.).
11//!
12//! # Obtaining a `ClientContext`
13//!
14//! Use [`ClientContext::from_connection`] from within an extension entry point,
15//! or obtain one from a callback via the `duckdb_*_get_client_context` family
16//! of C API functions.
17
18use std::ffi::CStr;
19
20use libduckdb_sys::{
21    duckdb_client_context, duckdb_client_context_get_catalog,
22    duckdb_client_context_get_config_option, duckdb_client_context_get_connection_id,
23    duckdb_config_option_scope, duckdb_connection, duckdb_connection_get_client_context,
24    duckdb_destroy_client_context,
25};
26
27use crate::catalog::Catalog;
28use crate::error::ExtensionError;
29use crate::value::Value;
30
31/// RAII wrapper for a `duckdb_client_context`.
32///
33/// Provides access to the connection's catalog, configuration, and file system.
34/// Automatically destroyed when dropped.
35///
36/// # Lifetime
37///
38/// The handle does **not** keep the connection alive. `DuckDB`'s
39/// `CClientContextWrapper` holds a plain reference to the `ClientContext` the
40/// connection owns (`src/include/duckdb/main/capi/capi_internal.hpp`), so a
41/// `ClientContext` — and a [`FileSystem`][crate::file_system::FileSystem]
42/// borrowed from it — must not be used after that connection is closed.
43/// Every constructor is `unsafe` and states this in its `# Safety` section.
44///
45/// # Threads
46///
47/// A `ClientContext` is [`Send`]: it may be moved to, used on and dropped on
48/// another thread — into a table function's bind data, for one, to open
49/// files in `init` or `scan`, where the C API has no client context of its
50/// own. It is not [`Sync`]; data that several scan threads read at once
51/// needs it behind a [`Mutex`](std::sync::Mutex).
52pub struct ClientContext {
53    ctx: duckdb_client_context,
54}
55
56// SAFETY: a `duckdb_client_context` is a heap `CClientContextWrapper {
57// ClientContext &context; }` (`capi_internal.hpp`, 1.5.6 and 2.0.0): one
58// reference, no thread-bound state, and `duckdb_destroy_client_context` only
59// deletes the wrapper. The `ClientContext` it refers to is the connection's,
60// which `DuckDB`'s executor threads all use while a query runs; the calls this
61// type makes (`get_catalog`, `get_config_option`, `get_connection_id`, and
62// `get_file_system` from `FileSystem::from_client_context`) read through it.
63// The only thread-local state on those paths is the per-thread settings
64// cache (1.5.5+), which is keyed by the settings' owner and version and so
65// answers correctly on any thread — the argument `OwnedConnection`'s `Send`
66// rests on too. The lifetime rule above is unchanged by a move. `Sync` is not implemented: this type does not
67// claim those calls are safe from two threads at the same moment. The live
68// test `a_client_context_is_used_and_dropped_on_another_thread` moves one.
69unsafe impl Send for ClientContext {}
70
71impl ClientContext {
72    /// Obtain a client context from a `duckdb_connection`.
73    ///
74    /// # Errors
75    ///
76    /// Returns `ExtensionError` if the context cannot be obtained.
77    ///
78    /// # Safety
79    ///
80    /// `con` must be a valid, open `duckdb_connection`, and must stay open for
81    /// as long as the returned context (or anything borrowed from it) is used
82    /// — see [Lifetime](Self#lifetime).
83    pub unsafe fn from_connection(con: duckdb_connection) -> Result<Self, ExtensionError> {
84        let mut ctx: duckdb_client_context = core::ptr::null_mut();
85        // SAFETY: con is valid per caller's contract.
86        unsafe { duckdb_connection_get_client_context(con, &raw mut ctx) };
87        if ctx.is_null() {
88            return Err(ExtensionError::new(
89                "failed to obtain client context from connection",
90            ));
91        }
92        Ok(Self { ctx })
93    }
94
95    /// Wrap a raw `duckdb_client_context` handle.
96    ///
97    /// # Safety
98    ///
99    /// `ctx` must be a valid, non-null `duckdb_client_context` that nothing
100    /// else destroys, and the connection it belongs to must stay open for as
101    /// long as the returned value is used — see [Lifetime](Self#lifetime).
102    pub const unsafe fn from_raw(ctx: duckdb_client_context) -> Self {
103        Self { ctx }
104    }
105
106    /// Returns the raw handle.
107    #[must_use]
108    pub const fn as_raw(&self) -> duckdb_client_context {
109        self.ctx
110    }
111
112    /// Retrieves a database catalog by name.
113    ///
114    /// Returns `None` when there is no such catalog — and in two cases that are
115    /// easy to mistake for one:
116    ///
117    /// - **`name` is empty.** `duckdb_client_context_get_catalog` rejects that
118    ///   outright (`strlen(name) == 0` is an explicit early return); it is not
119    ///   a way to ask for "the default". The catalog of an in-memory database
120    ///   is named `memory`; a file database's is the file's stem.
121    /// - **No transaction is active.** `DuckDB` checks
122    ///   `transaction.HasActiveTransaction()` and returns null otherwise, so
123    ///   this works inside a function callback but not on an idle
124    ///   auto-commit connection.
125    ///
126    /// # Safety
127    ///
128    /// Must be called from within an active transaction context.
129    pub unsafe fn catalog(&self, name: &CStr) -> Option<Catalog> {
130        // SAFETY: self.ctx is valid, caller ensures active transaction.
131        let catalog = unsafe { duckdb_client_context_get_catalog(self.ctx, name.as_ptr()) };
132        if catalog.is_null() {
133            None
134        } else {
135            // SAFETY: catalog is non-null and valid.
136            Some(unsafe { Catalog::from_raw(catalog) })
137        }
138    }
139
140    /// Retrieves a configuration option value by name, rendered as text.
141    ///
142    /// Returns `None` when the option does not exist **or its value is SQL
143    /// `NULL`** — the two are not distinguished. Several built-in settings are
144    /// `NULL` until set (`enable_profiling`, for one), and so is an extension
145    /// option after `SET my_option = NULL`. `DuckDB`'s `duckdb_get_varchar`
146    /// throws on a `NULL` value from inside the C API, which used to abort the
147    /// process; this checks `duckdb_is_null_value` first. A value that is not
148    /// valid UTF-8 is also `None`.
149    ///
150    /// # Do not use this to probe for a setting that may not exist
151    ///
152    /// `DuckDB` 1.5.5's `duckdb_client_context_get_config_option` reads the
153    /// lookup's scope before checking the lookup succeeded:
154    ///
155    /// ```text
156    /// // src/main/capi/config_options-c.cpp
157    /// switch (ctx.TryGetCurrentSetting(option_name, result).GetScope()) {
158    ///
159    /// // src/include/duckdb/main/setting_info.hpp
160    /// SettingScope GetScope() {
161    ///     D_ASSERT(scope != SettingScope::INVALID);
162    /// ```
163    ///
164    /// A missing setting yields `SettingScope::INVALID`, so `GetScope()` trips
165    /// that assertion. In a release `DuckDB` — what users run — `D_ASSERT`
166    /// compiles out, the function's own `default:` branch handles `INVALID`,
167    /// and this returns `None` as documented. Against a `DuckDB` built **with
168    /// debug assertions**, the process aborts. Verified against 1.5.5.
169    ///
170    /// So this is safe for a setting you registered or know exists, and unsafe
171    /// as an existence check. To ask whether a setting exists, use SQL, which
172    /// has no such path:
173    ///
174    /// ```sql
175    /// SELECT count(*) FROM duckdb_settings() WHERE name = 'my_setting';
176    /// ```
177    ///
178    /// The C function has no `try`, so a built-in setting whose getter threw
179    /// would abort the process too. None does in practice: every setting
180    /// `duckdb_settings()` lists was read this way on 1.5.0 (150) and 1.5.5
181    /// (157) without a throw, and the two 1.5.5 getters that can throw do so
182    /// only for a state their `SET` handlers never store. An extension's own
183    /// option has no getter.
184    pub fn config_option(&self, name: &CStr) -> Option<String> {
185        let mut scope: duckdb_config_option_scope = 0;
186        // SAFETY: self.ctx is valid.
187        let raw = unsafe {
188            duckdb_client_context_get_config_option(self.ctx, name.as_ptr(), &raw mut scope)
189        };
190        if raw.is_null() {
191            return None;
192        }
193        // SAFETY: `duckdb_client_context_get_config_option` returns an owned
194        // `duckdb_value`; `Value` destroys it on drop.
195        let value = unsafe { Value::from_raw(raw) };
196        // `Value::as_str` checks `duckdb_is_null_value` before calling
197        // `duckdb_get_varchar`, which would throw (and abort) on SQL NULL.
198        value.as_str().ok()
199    }
200
201    /// Returns the connection ID associated with this client context.
202    #[must_use]
203    pub fn connection_id(&self) -> u64 {
204        // SAFETY: self.ctx is valid.
205        unsafe { duckdb_client_context_get_connection_id(self.ctx) }
206    }
207}
208
209impl Drop for ClientContext {
210    fn drop(&mut self) {
211        // SAFETY: self.ctx was obtained from a valid `DuckDB` API call.
212        unsafe {
213            duckdb_destroy_client_context(&raw mut self.ctx);
214        }
215    }
216}
217
218#[cfg(all(test, feature = "_duckdb-testing"))]
219mod tests {
220    use super::*;
221
222    /// Opens a raw `duckdb_connection` for testing.
223    fn open_raw_connection() -> (libduckdb_sys::duckdb_database, duckdb_connection) {
224        // Ensure dispatch table is populated.
225        let _db = crate::testing::InMemoryDb::open().unwrap();
226
227        let mut db: libduckdb_sys::duckdb_database = core::ptr::null_mut();
228        let mut con: duckdb_connection = core::ptr::null_mut();
229
230        // SAFETY: dispatch table is initialized, nullptr opens in-memory.
231        unsafe {
232            let rc = libduckdb_sys::duckdb_open(core::ptr::null(), &raw mut db);
233            assert_eq!(rc, libduckdb_sys::DuckDBSuccess, "duckdb_open failed");
234            let rc = libduckdb_sys::duckdb_connect(db, &raw mut con);
235            assert_eq!(rc, libduckdb_sys::DuckDBSuccess, "duckdb_connect failed");
236        }
237        (db, con)
238    }
239
240    /// Closes a raw connection and database.
241    unsafe fn close_raw_connection(
242        mut con: duckdb_connection,
243        mut db: libduckdb_sys::duckdb_database,
244    ) {
245        unsafe {
246            libduckdb_sys::duckdb_disconnect(&raw mut con);
247            libduckdb_sys::duckdb_close(&raw mut db);
248        }
249    }
250
251    #[test]
252    fn from_connection_succeeds() {
253        let (db, con) = open_raw_connection();
254
255        // SAFETY: con is a valid open connection.
256        let ctx = unsafe { ClientContext::from_connection(con) };
257        assert!(
258            ctx.is_ok(),
259            "from_connection should succeed: {:?}",
260            ctx.err()
261        );
262
263        drop(ctx.unwrap());
264        // SAFETY: valid handles.
265        unsafe { close_raw_connection(con, db) };
266    }
267
268    #[test]
269    fn connection_id_distinguishes_connections_and_is_stable() {
270        let (db, con) = open_raw_connection();
271        let mut con2: duckdb_connection = core::ptr::null_mut();
272        // SAFETY: `db` is open.
273        let rc = unsafe { libduckdb_sys::duckdb_connect(db, &raw mut con2) };
274        assert_eq!(rc, libduckdb_sys::DuckDBSuccess);
275
276        // SAFETY: both connections are open.
277        let ctx = unsafe { ClientContext::from_connection(con) }.unwrap();
278        // SAFETY: as above.
279        let ctx_again = unsafe { ClientContext::from_connection(con) }.unwrap();
280        // SAFETY: as above.
281        let ctx2 = unsafe { ClientContext::from_connection(con2) }.unwrap();
282        assert_eq!(ctx.connection_id(), ctx_again.connection_id());
283        assert_ne!(ctx.connection_id(), ctx2.connection_id());
284
285        drop((ctx, ctx_again, ctx2));
286        // SAFETY: valid handles, closed once.
287        unsafe {
288            libduckdb_sys::duckdb_disconnect(&raw mut con2);
289            close_raw_connection(con, db);
290        }
291    }
292
293    /// Before the fix this aborted the process: `enable_profiling` is `NULL`
294    /// until set, and `duckdb_get_varchar` throws on a `NULL` value from
295    /// inside the C API ("Rust cannot catch foreign exceptions").
296    #[test]
297    fn config_option_of_a_null_setting_is_none_not_an_abort() {
298        let (db, con) = open_raw_connection();
299        // SAFETY: con is a valid open connection.
300        let ctx = unsafe { ClientContext::from_connection(con) }.unwrap();
301        assert_eq!(ctx.config_option(c"enable_profiling"), None);
302        // A non-NULL setting still reads.
303        assert!(ctx.config_option(c"threads").is_some());
304        drop(ctx);
305        // SAFETY: valid handles.
306        unsafe { close_raw_connection(con, db) };
307    }
308
309    #[test]
310    fn config_option_returns_some_for_known_setting() {
311        let (db, con) = open_raw_connection();
312
313        // SAFETY: con is a valid open connection.
314        let ctx = unsafe { ClientContext::from_connection(con) }.unwrap();
315
316        // "threads" is a well-known DuckDB config option.
317        let threads = ctx.config_option(c"threads");
318        assert!(threads.is_some(), "'threads' config option should exist");
319        // The value should be a parseable positive integer.
320        let val: usize = threads.unwrap().parse().expect("threads should be numeric");
321        assert!(val > 0, "threads should be > 0");
322
323        drop(ctx);
324        // SAFETY: valid handles.
325        unsafe { close_raw_connection(con, db) };
326    }
327
328    #[test]
329    fn catalog_is_found_by_name_inside_a_transaction() {
330        let (db, con) = open_raw_connection();
331
332        // Start a transaction so we have an active transaction context.
333        // SAFETY: con is valid.
334        unsafe {
335            let sql = c"BEGIN TRANSACTION";
336            libduckdb_sys::duckdb_query(con, sql.as_ptr(), core::ptr::null_mut());
337        }
338
339        // SAFETY: con is a valid open connection.
340        let ctx = unsafe { ClientContext::from_connection(con) }.unwrap();
341
342        // An empty name is rejected outright (`strlen(name) == 0` returns
343        // early); an in-memory database's catalog is called `memory`.
344        // SAFETY: within an active transaction.
345        assert!(unsafe { ctx.catalog(c"") }.is_none());
346        // SAFETY: within an active transaction.
347        let catalog = unsafe { ctx.catalog(c"memory") }.expect("the memory catalog");
348        assert_eq!(catalog.type_name(), Some("duckdb"));
349        drop(catalog);
350
351        drop(ctx);
352        // Rollback the transaction.
353        // SAFETY: con is valid.
354        unsafe {
355            let sql = c"ROLLBACK";
356            libduckdb_sys::duckdb_query(con, sql.as_ptr(), core::ptr::null_mut());
357        }
358        // SAFETY: valid handles.
359        unsafe { close_raw_connection(con, db) };
360    }
361}
362
363crate::debug_repr::impl_handle_debug!(ClientContext.ctx);