Skip to main content

quack_rs/entry_point/
registration.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//! How the entry point runs the registration closure: in one transaction on
7//! the registration connection, or with every statement committing on its own.
8//! See "Registration is transactional" in the [`entry_point`](super) docs.
9
10use libduckdb_sys::{duckdb_connection, duckdb_database};
11
12use crate::abi::AbiPolicy;
13use crate::error::ExtensionError;
14
15/// How the entry point runs the registration closure.
16///
17/// `#[non_exhaustive]`: a `match` outside quack-rs needs a wildcard arm.
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
19#[non_exhaustive]
20pub enum Registration {
21    /// Run the closure inside `BEGIN TRANSACTION` on the registration
22    /// connection, `COMMIT` when it returns `Ok`, and `ROLLBACK` when it
23    /// returns `Err` or panics. A failed `LOAD` then leaves no catalog entry
24    /// behind (scalar, aggregate and table functions, macros, types, copy
25    /// functions, tables) and can be retried; casts, replacement scans and
26    /// configuration options are not catalog entries and stay registered. The
27    /// default.
28    #[default]
29    Transactional,
30    /// Let every registration and statement commit on its own, as quack-rs did
31    /// before 0.20: what the closure registered before a failure stays
32    /// registered, and retrying the `LOAD` in the same database fails at the
33    /// first name it registers again. Use it when the closure must keep going
34    /// after a failed statement, or must control transactions on the
35    /// registration connection itself.
36    Autocommit,
37}
38
39/// What an entry point is configured with: the [`AbiPolicy`] and the
40/// [`Registration`] mode.
41///
42/// The middle argument of [`entry_point!`][crate::entry_point!] and
43/// [`entry_point_v2!`][crate::entry_point_v2!] is either an [`AbiPolicy`],
44/// which keeps the default registration mode, or `options = ` one of these;
45/// [`init_extension_with_options`][super::init_extension_with_options] and
46/// [`init_extension_v2_with_options`][super::init_extension_v2_with_options]
47/// take one for an entry point written by hand.
48///
49/// ```rust,no_run
50/// use quack_rs::abi::AbiPolicy;
51/// use quack_rs::entry_point::{EntryPointOptions, Registration};
52///
53/// quack_rs::entry_point_v2!(
54///     my_ext_init_c_api,
55///     options = EntryPointOptions::new()
56///         .abi_policy(AbiPolicy::Strict)
57///         .registration(Registration::Autocommit),
58///     |_con| Ok(())
59/// );
60/// ```
61#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
62#[must_use]
63pub struct EntryPointOptions {
64    abi_policy: AbiPolicy,
65    registration: Registration,
66}
67
68impl EntryPointOptions {
69    /// The defaults: [`AbiPolicy::Strict`] and [`Registration::Transactional`].
70    pub const fn new() -> Self {
71        Self {
72            abi_policy: AbiPolicy::Strict,
73            registration: Registration::Transactional,
74        }
75    }
76
77    /// Sets the [`AbiPolicy`].
78    pub const fn abi_policy(mut self, policy: AbiPolicy) -> Self {
79        self.abi_policy = policy;
80        self
81    }
82
83    /// Sets the [`Registration`] mode.
84    pub const fn registration(mut self, registration: Registration) -> Self {
85        self.registration = registration;
86        self
87    }
88
89    /// The configured [`AbiPolicy`].
90    #[must_use]
91    pub const fn get_abi_policy(&self) -> AbiPolicy {
92        self.abi_policy
93    }
94
95    /// The configured [`Registration`] mode.
96    #[must_use]
97    pub const fn get_registration(&self) -> Registration {
98        self.registration
99    }
100}
101
102impl From<AbiPolicy> for EntryPointOptions {
103    /// `policy`, with the default [`Registration`] mode.
104    fn from(policy: AbiPolicy) -> Self {
105        Self::new().abi_policy(policy)
106    }
107}
108
109/// Runs `register` on the registration connection `con` of database `db` as
110/// `mode` says, with a panic in it turned into an error.
111///
112/// # Errors
113///
114/// The closure's error; or, in [`Registration::Transactional`], `DuckDB`'s
115/// error when the transaction cannot begin or commit.
116///
117/// # Safety
118///
119/// `con` must be an open connection to `db` that nothing else uses during the
120/// call, and `db` must stay valid for it.
121pub(super) unsafe fn run<F>(
122    con: duckdb_connection,
123    db: duckdb_database,
124    mode: Registration,
125    register: F,
126) -> Result<(), ExtensionError>
127where
128    F: FnOnce() -> Result<(), ExtensionError>,
129{
130    // Only the copy-format check needs the database (see `ScopeState`).
131    #[cfg(not(feature = "duckdb-1-5"))]
132    let _ = db;
133    if mode == Registration::Autocommit {
134        return super::catch_registration_panic(register);
135    }
136    // SAFETY: `con` is open per this function's contract.
137    unsafe { crate::query::execute(con, "BEGIN TRANSACTION") }.map_err(|e| {
138        ExtensionError::new(format!(
139            "could not begin the transaction the extension registers in: {e}"
140        ))
141    })?;
142    let result = {
143        #[cfg(feature = "duckdb-1-5")]
144        let _scope = Scope::enter(con, db);
145        super::catch_registration_panic(register)
146    };
147    match result {
148        // SAFETY: as above.
149        Ok(()) => unsafe { crate::query::execute(con, "COMMIT") }
150            .map(drop)
151            .map_err(|e| {
152                ExtensionError::new(format!(
153                    "the extension's registrations could not be committed, so none of them took \
154                     effect: {e}"
155                ))
156            }),
157        Err(error) => {
158            // A failed rollback leaves the transaction open; disconnecting
159            // the connection, which the caller does next, rolls it back.
160            // SAFETY: as above.
161            let _ = unsafe { crate::query::execute(con, "ROLLBACK") };
162            Err(error)
163        }
164    }
165}
166
167/// The registration transaction the entry point has open on this thread.
168///
169/// Only the copy-format check needs it (with `duckdb-1-5`): it probes with a
170/// statement that fails on purpose, and on `DuckDB` 2.0 any failed statement
171/// aborts the transaction it runs in, so inside this one it must run on a
172/// connection of its own — which needs the database — and must be told the
173/// formats registered in the still-uncommitted transaction, which that
174/// connection cannot see.
175#[cfg(feature = "duckdb-1-5")]
176struct ScopeState {
177    con: duckdb_connection,
178    db: duckdb_database,
179    copy_formats: Vec<String>,
180}
181
182#[cfg(feature = "duckdb-1-5")]
183std::thread_local! {
184    static SCOPE: core::cell::RefCell<Option<ScopeState>> =
185        const { core::cell::RefCell::new(None) };
186}
187
188/// Marks a registration transaction as open on this thread until dropped,
189/// restoring whatever was marked before (a nested `LOAD` of another extension
190/// built with this same copy of quack-rs).
191#[cfg(feature = "duckdb-1-5")]
192struct Scope {
193    previous: Option<ScopeState>,
194}
195
196#[cfg(feature = "duckdb-1-5")]
197impl Scope {
198    fn enter(con: duckdb_connection, db: duckdb_database) -> Self {
199        let state = ScopeState {
200            con,
201            db,
202            copy_formats: Vec::new(),
203        };
204        let previous = SCOPE.with(|scope| scope.replace(Some(state)));
205        Self { previous }
206    }
207}
208
209#[cfg(feature = "duckdb-1-5")]
210impl Drop for Scope {
211    fn drop(&mut self) {
212        let previous = self.previous.take();
213        SCOPE.with(|scope| {
214            scope.replace(previous);
215        });
216    }
217}
218
219/// When `con` is the connection of the registration transaction open on this
220/// thread: its database, and whether a copy format named `name` (compared
221/// case-insensitively) was registered in that transaction.
222#[cfg(feature = "duckdb-1-5")]
223pub fn copy_format_scope(con: duckdb_connection, name: &str) -> Option<(duckdb_database, bool)> {
224    SCOPE.with(|scope| {
225        scope.borrow().as_ref().filter(|s| s.con == con).map(|s| {
226            let taken = s.copy_formats.iter().any(|f| f.eq_ignore_ascii_case(name));
227            (s.db, taken)
228        })
229    })
230}
231
232/// Records a copy format registered on `con`, if `con` is the connection of
233/// the registration transaction open on this thread.
234#[cfg(feature = "duckdb-1-5")]
235pub fn record_copy_format(con: duckdb_connection, name: &str) {
236    SCOPE.with(|scope| {
237        if let Some(s) = scope.borrow_mut().as_mut().filter(|s| s.con == con) {
238            s.copy_formats.push(name.to_owned());
239        }
240    });
241}
242
243#[cfg(test)]
244mod tests {
245    use super::{EntryPointOptions, Registration};
246    use crate::abi::AbiPolicy;
247
248    #[test]
249    fn options_default_to_strict_and_transactional() {
250        let options = EntryPointOptions::default();
251        assert_eq!(options, EntryPointOptions::new());
252        assert_eq!(options.get_abi_policy(), AbiPolicy::Strict);
253        assert_eq!(options.get_registration(), Registration::Transactional);
254        assert_eq!(Registration::default(), Registration::Transactional);
255    }
256
257    #[test]
258    fn a_policy_converts_to_options_with_the_default_registration() {
259        let options = EntryPointOptions::from(AbiPolicy::Trust);
260        assert_eq!(options.get_abi_policy(), AbiPolicy::Trust);
261        assert_eq!(options.get_registration(), Registration::Transactional);
262        let options = options.registration(Registration::Autocommit);
263        assert_eq!(options.get_abi_policy(), AbiPolicy::Trust);
264        assert_eq!(options.get_registration(), Registration::Autocommit);
265    }
266
267    /// The scope names only its own connection, and a nested scope restores
268    /// the outer one when it ends.
269    #[cfg(feature = "duckdb-1-5")]
270    #[test]
271    fn the_scope_tracks_one_connection_and_nests() {
272        use super::{copy_format_scope, record_copy_format, Scope};
273        let (outer_con, inner_con) = (0x10 as _, 0x20 as _);
274        let (outer_db, inner_db) = (0x11 as _, 0x21 as _);
275        assert_eq!(copy_format_scope(outer_con, "fmt"), None);
276        {
277            let _outer = Scope::enter(outer_con, outer_db);
278            record_copy_format(outer_con, "MyFmt");
279            record_copy_format(inner_con, "elsewhere");
280            assert_eq!(
281                copy_format_scope(outer_con, "myfmt"),
282                Some((outer_db, true))
283            );
284            assert_eq!(
285                copy_format_scope(outer_con, "elsewhere"),
286                Some((outer_db, false))
287            );
288            assert_eq!(copy_format_scope(inner_con, "myfmt"), None);
289            {
290                let _inner = Scope::enter(inner_con, inner_db);
291                assert_eq!(
292                    copy_format_scope(inner_con, "myfmt"),
293                    Some((inner_db, false))
294                );
295                assert_eq!(copy_format_scope(outer_con, "myfmt"), None);
296            }
297            assert_eq!(
298                copy_format_scope(outer_con, "myfmt"),
299                Some((outer_db, true))
300            );
301        }
302        assert_eq!(copy_format_scope(outer_con, "myfmt"), None);
303    }
304}