quack-rs 0.12.0

Production-grade Rust SDK for building DuckDB loadable extensions
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
// SPDX-License-Identifier: MIT
// Copyright 2026 Tom F. <https://github.com/tomtom215/>
// My way of giving something small back to the open source community
// and encouraging more Rust development!

//! Extension entry point helper.
//!
//! Provides [`init_extension`], the core helper called by the `entry_point!` macro.
//!
//! # Problem 1: Custom C entry point
//!
//! `DuckDB`'s Rust crate does not provide a safe way to obtain a raw
//! `duckdb_connection` handle for function registration. The prior approach
//! using `extract_raw_connection` relied on `Rc<RefCell<InnerConnection>>` layout,
//! causing SEGFAULTs. The correct approach is a hand-written C entry point that:
//!
//! 1. Calls `duckdb_rs_extension_api_init(info, access, "v1.2.0")`
//! 2. Calls `access.get_database(info)` to get a `duckdb_database`
//! 3. Calls `duckdb_connect(db, &mut raw_con)` to get a `duckdb_connection`
//! 4. Registers all functions
//! 5. Calls `duckdb_disconnect(&mut raw_con)`
//!
//! # Pitfall L3: No panic across FFI
//!
//! `init_extension` uses `Result` for all error propagation and never calls
//! `unwrap()` or `panic!()` inside an FFI callback.
//!
//! # Usage
//!
//! Extension authors typically use the `entry_point!` macro,
//! which generates the required `#[no_mangle] extern "C"` function automatically.
//!
//! If you need full control over the entry point, you can call `init_extension`
//! directly:
//!
//! ```rust,no_run
//! use quack_rs::entry_point::init_extension;
//!
//! #[no_mangle]
//! pub unsafe extern "C" fn my_extension_init_c_api(
//!     info: libduckdb_sys::duckdb_extension_info,
//!     access: *const libduckdb_sys::duckdb_extension_access,
//! ) -> bool {
//!     unsafe {
//!         init_extension(info, access, quack_rs::DUCKDB_API_VERSION, |con| {
//!             // register functions with `con: libduckdb_sys::duckdb_connection`
//!             Ok(())
//!         })
//!     }
//! }
//! ```

use libduckdb_sys::{
    duckdb_connect, duckdb_connection, duckdb_disconnect, duckdb_extension_access,
    duckdb_extension_info, duckdb_rs_extension_api_init, DuckDBSuccess,
};

use crate::connection::Connection;
use crate::error::ExtensionError;

/// Generates the `#[no_mangle] unsafe extern "C"` entry point for a `DuckDB` extension.
///
/// This macro eliminates the boilerplate of writing the entry point manually.
/// It emits a `#[no_mangle] pub unsafe extern "C"` function with the name you
/// supply, which `DuckDB` locates by symbol when loading the extension.
///
/// # Arguments
///
/// - `$fn_name`: The exact symbol name `DuckDB` will call (e.g.,
///   `my_extension_init_c_api`). `DuckDB` requires this to follow the
///   `{extension_name}_init_c_api` convention.
/// - `$register`: A closure or function of type
///   `fn(duckdb_connection) -> Result<(), ExtensionError>` that registers your
///   functions on the given connection.
///
/// # Example
///
/// ```rust,no_run
/// use quack_rs::entry_point;
/// use quack_rs::error::ExtensionError;
///
/// fn register_functions(
///     _con: libduckdb_sys::duckdb_connection,
/// ) -> Result<(), ExtensionError> {
///     Ok(())
/// }
///
/// entry_point!(my_extension_init_c_api, |con| register_functions(con));
/// ```
#[macro_export]
macro_rules! entry_point {
    ($fn_name:ident, $register:expr) => {
        /// DuckDB extension entry point (generated by `entry_point!`).
        ///
        /// # Safety
        ///
        /// Called by DuckDB. `info` and `access` are provided by the DuckDB runtime.
        #[no_mangle]
        pub unsafe extern "C" fn $fn_name(
            info: ::libduckdb_sys::duckdb_extension_info,
            access: *const ::libduckdb_sys::duckdb_extension_access,
        ) -> bool {
            unsafe {
                $crate::entry_point::init_extension(
                    info,
                    access,
                    $crate::DUCKDB_API_VERSION,
                    $register,
                )
            }
        }
    };
}

/// Generates the `#[no_mangle] unsafe extern "C"` entry point using the
/// version-agnostic [`Connection`] facade.
///
/// This is the recommended alternative to [`entry_point!`]. The registration
/// callback receives a <code>&[Connection]</code> instead of a raw `duckdb_connection`,
/// giving access to the [`Registrar`][crate::connection::Registrar] trait and to
/// both the connection and database handles.
///
/// # Arguments
///
/// - `$fn_name`: The exact symbol name `DuckDB` will call.
/// - `$register`: A closure of type `fn(&Connection) -> Result<(), ExtensionError>`.
///
/// # Example
///
/// ```rust,no_run
/// use quack_rs::connection::Registrar;
/// use quack_rs::error::ExtensionError;
/// use quack_rs::connection::Connection;
///
/// quack_rs::entry_point_v2!(my_extension_init_c_api, |con| {
///     // unsafe { con.register_scalar(builder)? };
///     Ok(())
/// });
/// ```
#[macro_export]
macro_rules! entry_point_v2 {
    ($fn_name:ident, $register:expr) => {
        /// DuckDB extension entry point (generated by `entry_point_v2!`).
        ///
        /// # Safety
        ///
        /// Called by DuckDB. `info` and `access` are provided by the DuckDB runtime.
        #[no_mangle]
        pub unsafe extern "C" fn $fn_name(
            info: ::libduckdb_sys::duckdb_extension_info,
            access: *const ::libduckdb_sys::duckdb_extension_access,
        ) -> bool {
            unsafe {
                $crate::entry_point::init_extension_v2(
                    info,
                    access,
                    $crate::DUCKDB_API_VERSION,
                    $register,
                )
            }
        }
    };
}

/// Core entry point helper — sets up a connection and calls your registration closure.
///
/// This function encapsulates the correct initialization sequence for a `DuckDB`
/// loadable extension written in Rust:
///
/// 1. Calls `duckdb_rs_extension_api_init` with the given `api_version`.
/// 2. Extracts the `duckdb_database` via `access.get_database`.
/// 3. Opens a `duckdb_connection` via `duckdb_connect`.
/// 4. Calls `register(connection)`.
/// 5. Disconnects with `duckdb_disconnect`.
/// 6. On any error, reports via `access.set_error` and returns `false`.
///
/// # Return value
///
/// Returns `true` if initialization succeeded, `false` on any error.
///
/// # Safety
///
/// - `info` must be the `duckdb_extension_info` passed by `DuckDB` to your entry point.
/// - `access` must be the `*const duckdb_extension_access` passed by `DuckDB`.
/// - Both pointers must remain valid for the duration of this call.
///
/// # Pitfall L3: No panic across FFI
///
/// This function never panics. All errors are reported via `access.set_error`.
///
/// # Example
///
/// ```rust,no_run
/// use quack_rs::entry_point::init_extension;
///
/// #[no_mangle]
/// pub unsafe extern "C" fn my_ext_init_c_api(
///     info: libduckdb_sys::duckdb_extension_info,
///     access: *const libduckdb_sys::duckdb_extension_access,
/// ) -> bool {
///     unsafe {
///         init_extension(info, access, quack_rs::DUCKDB_API_VERSION, |_con| {
///             // Register your functions here
///             Ok(())
///         })
///     }
/// }
/// ```
pub unsafe fn init_extension<F>(
    info: duckdb_extension_info,
    access: *const duckdb_extension_access,
    api_version: &str,
    register: F,
) -> bool
where
    F: FnOnce(duckdb_connection) -> Result<(), ExtensionError>,
{
    match unsafe { init_extension_internal(info, access, api_version, register) } {
        Ok(result) => result,
        Err(e) => {
            // SAFETY: access is a valid pointer per the caller's contract.
            unsafe { report_error(info, access, &e) };
            false
        }
    }
}

/// Core entry point helper — sets up a [`Connection`] and calls your registration closure.
///
/// Identical to [`init_extension`] except that the callback receives a
/// <code>&[Connection]</code> instead of a raw `duckdb_connection`. [`Connection`]
/// implements [`Registrar`][crate::connection::Registrar] and also exposes the
/// `duckdb_database` handle for replacement scan registration.
///
/// Prefer this over [`init_extension`] for new extensions. The raw
/// `duckdb_connection` entry point is retained for backward compatibility.
///
/// # Return value
///
/// Returns `true` if initialization succeeded, `false` on any error.
///
/// # Safety
///
/// - `info` must be the `duckdb_extension_info` passed by `DuckDB` to your entry point.
/// - `access` must be the `*const duckdb_extension_access` passed by `DuckDB`.
/// - Both pointers must remain valid for the duration of this call.
///
/// # Example
///
/// ```rust,no_run
/// use quack_rs::entry_point::init_extension_v2;
/// use quack_rs::connection::Registrar;
///
/// #[no_mangle]
/// pub unsafe extern "C" fn my_ext_init_c_api(
///     info: libduckdb_sys::duckdb_extension_info,
///     access: *const libduckdb_sys::duckdb_extension_access,
/// ) -> bool {
///     unsafe {
///         init_extension_v2(info, access, quack_rs::DUCKDB_API_VERSION, |con| {
///             // unsafe { con.register_scalar(builder)?; }
///             Ok(())
///         })
///     }
/// }
/// ```
pub unsafe fn init_extension_v2<F>(
    info: duckdb_extension_info,
    access: *const duckdb_extension_access,
    api_version: &str,
    register: F,
) -> bool
where
    F: FnOnce(&Connection) -> Result<(), crate::error::ExtensionError>,
{
    match unsafe { init_extension_v2_internal(info, access, api_version, register) } {
        Ok(result) => result,
        Err(e) => {
            // SAFETY: access is a valid pointer per the caller's contract.
            unsafe { report_error(info, access, &e) };
            false
        }
    }
}

/// Internal implementation of [`init_extension_v2`] using `?` for error propagation.
///
/// # Safety
///
/// Same invariants as [`init_extension_v2`].
unsafe fn init_extension_v2_internal<F>(
    info: duckdb_extension_info,
    access: *const duckdb_extension_access,
    api_version: &str,
    register: F,
) -> Result<bool, crate::error::ExtensionError>
where
    F: FnOnce(&Connection) -> Result<(), crate::error::ExtensionError>,
{
    // Step 1: Initialize the DuckDB C API.
    //
    // PITFALL P2: Use the C API version, not the DuckDB release version.
    // DuckDB v1.4.x and v1.5.x use C API version v1.2.0.
    //
    // SAFETY: info and access are valid pointers provided by DuckDB.
    let have_api = unsafe {
        duckdb_rs_extension_api_init(info, access, api_version)
            .map_err(|e| crate::error::ExtensionError::new(e.to_string()))?
    };

    if !have_api {
        return Ok(false);
    }

    // Step 2: Get the database handle.
    // SAFETY: access is valid and have_api is true, so get_database is non-null.
    let get_database = unsafe { (*access).get_database }.ok_or_else(|| {
        crate::error::ExtensionError::new("get_database function pointer is null")
    })?;

    // SAFETY: info is valid. The returned pointer is DuckDB-managed.
    let db = unsafe { *get_database(info) };

    // Step 3: Open a connection for function registration.
    let mut raw_con: duckdb_connection = core::ptr::null_mut();
    // SAFETY: db is a valid duckdb_database returned by get_database.
    let rc = unsafe { duckdb_connect(db, &raw mut raw_con) };
    if rc != DuckDBSuccess {
        return Err(crate::error::ExtensionError::new(
            "duckdb_connect failed during extension initialization",
        ));
    }

    // Step 4: Build the Connection facade and call the user's registration closure.
    //
    // SAFETY: raw_con and db are both valid for the duration of this scope.
    let con = unsafe { Connection::from_raw(raw_con, db) };
    let result = register(&con);

    // Step 5: Always disconnect, even if registration failed.
    // SAFETY: raw_con was successfully created by duckdb_connect above.
    unsafe { duckdb_disconnect(&raw mut raw_con) };

    result?;
    Ok(true)
}

/// Internal implementation using `?` for ergonomic error propagation.
///
/// # Safety
///
/// Same invariants as [`init_extension`].
unsafe fn init_extension_internal<F>(
    info: duckdb_extension_info,
    access: *const duckdb_extension_access,
    api_version: &str,
    register: F,
) -> Result<bool, ExtensionError>
where
    F: FnOnce(duckdb_connection) -> Result<(), ExtensionError>,
{
    // Step 1: Initialize the DuckDB C API. This must be called before any other
    // libduckdb_sys function in a loadable extension. The version string must be
    // the C API version (e.g. "v1.2.0"), NOT the DuckDB release version.
    //
    // PITFALL P2: Use the C API version, not the DuckDB release version.
    // DuckDB v1.4.x and v1.5.x use C API version v1.2.0.
    //
    // SAFETY: info and access are valid pointers provided by DuckDB.
    let have_api = unsafe {
        duckdb_rs_extension_api_init(info, access, api_version)
            .map_err(|e| ExtensionError::new(e.to_string()))?
    };

    if !have_api {
        // DuckDB indicated that the API version is not available. Return false
        // without an error — this can happen when the extension is loaded by
        // an older DuckDB version that predates the requested API version.
        return Ok(false);
    }

    // Step 2: Get the database handle.
    // SAFETY: access is valid and have_api is true, so get_database is non-null.
    let get_database = unsafe { (*access).get_database }
        .ok_or_else(|| ExtensionError::new("get_database function pointer is null"))?;

    // SAFETY: info is valid. The returned pointer is DuckDB-managed.
    let db = unsafe { *get_database(info) };

    // Step 3: Open a connection for function registration.
    let mut raw_con: duckdb_connection = core::ptr::null_mut();
    // SAFETY: db is a valid duckdb_database returned by get_database.
    let rc = unsafe { duckdb_connect(db, &raw mut raw_con) };
    if rc != DuckDBSuccess {
        return Err(ExtensionError::new(
            "duckdb_connect failed during extension initialization",
        ));
    }

    // Step 4: Call the user's registration closure.
    let result = register(raw_con);

    // Step 5: Always disconnect, even if registration failed.
    // SAFETY: raw_con was successfully created by duckdb_connect above.
    unsafe { duckdb_disconnect(&raw mut raw_con) };

    result?;
    Ok(true)
}

/// Reports an `ExtensionError` back to `DuckDB` via `access.set_error`.
///
/// # Safety
///
/// `info` and `access` must be valid pointers provided by `DuckDB`.
unsafe fn report_error(
    info: duckdb_extension_info,
    access: *const duckdb_extension_access,
    error: &ExtensionError,
) {
    // Defensive: if access is null, we cannot report the error to DuckDB.
    if access.is_null() {
        return;
    }
    // SAFETY: access is non-null per the check above and valid per caller's contract.
    if let Some(set_error) = unsafe { (*access).set_error } {
        let c_msg = error.to_c_string();
        // SAFETY: c_msg is a valid CString; info is valid.
        unsafe { set_error(info, c_msg.as_ptr()) };
    }
}

#[cfg(test)]
mod tests {
    // Integration tests for init_extension require a DuckDB instance and are in
    // tests/integration_test.rs. Unit tests here verify pure-Rust logic.

    #[test]
    fn extension_error_to_c_string() {
        use crate::error::ExtensionError;
        let err = ExtensionError::new("test error message");
        let cstr = err.to_c_string();
        assert_eq!(cstr.to_str().unwrap(), "test error message");
    }
}