better-duck-core 0.1.0-beta.3

Rust DuckDB client with Diesel ORM support
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
use std::{
    ffi::{c_void, CStr, CString},
    mem,
    os::raw::c_char,
    ptr, str,
    sync::Arc,
};

use crate::{
    config::Config,
    error::{Error, Result},
    ffi::{
        duckdb_close, duckdb_connect, duckdb_connection, duckdb_database, duckdb_disconnect,
        duckdb_free, duckdb_open_ext, duckdb_query, duckdb_result, DuckDBError, DuckDBSuccess,
        Error as FFIError,
    },
    helpers::duck_result::result_from_duckdb_result,
    raw::{
        appender::Appender,
        result::DuckResult,
        statement::{CachedStatement, Statement},
    },
    types::appendable::AppendAble,
};

/// `RawDatabase` is a low-level wrapper around a DuckDB database handle.
///
/// This struct provides direct access to the underlying DuckDB database pointer.
/// It is intended for advanced use cases where you need to manage the database handle manually.
///
/// **Thread Safety:**
/// `RawDatabase` itself is **not** thread-safe. If you need to share it between threads or
/// multiple connections, wrap it in a thread-safe container such as [`Arc`](std::sync::Arc).
///
/// # Example
///
/// ```rust,ignore
/// use std::sync::Arc;
/// use better_duck_core::raw::RawDatabase; // raw is crate-private
/// use better_duck_core::ffi;
///
/// let mut db: ffi::duckdb_database = std::ptr::null_mut();
/// let path = std::ffi::CString::new(":memory:").unwrap();
/// let r = unsafe { ffi::duckdb_open(path.as_ptr(), &mut db) };
/// assert_eq!(r, ffi::DuckDBSuccess);
/// let raw_db = unsafe { RawDatabase::new(db).unwrap() };
/// let shared = Arc::new(raw_db);
/// ```
pub struct RawDatabase(pub(crate) duckdb_database);
impl RawDatabase {
    /// Creates a new [`RawDatabase`] from an existing raw database handle.
    ///
    /// # Safety
    ///
    /// `db` must be a valid, open `duckdb_database` obtained from a successful call to
    /// `duckdb_open` or `duckdb_open_ext`. Passing a null or invalid pointer is
    /// undefined behavior.
    ///
    /// # Errors
    ///
    /// Returns an error if `db` is null.
    #[inline]
    pub unsafe fn new(db: duckdb_database) -> Result<RawDatabase> {
        if db.is_null() {
            return Err(Error::DuckDBFailure(
                FFIError::new(DuckDBError),
                Some("database is null".to_owned()),
            ));
        }
        Ok(RawDatabase(db))
    }

    /// Opens a database at the given path with the specified config.
    ///
    /// Pass a path of `":memory:"` for an in-memory database.
    ///
    /// # Errors
    ///
    /// Returns an error if the database cannot be opened.
    pub(crate) fn open_with_flags(
        c_path: &CStr,
        config: Config,
    ) -> Result<RawDatabase> {
        // SAFETY: `c_path` is a valid null-terminated C string. `db` and `c_err` are valid
        // output pointers. On error we free `c_err` via `duckdb_free`.
        unsafe {
            let mut db: duckdb_database = ptr::null_mut();
            let mut c_err = std::ptr::null_mut();
            let r = duckdb_open_ext(c_path.as_ptr(), &mut db, config.duckdb_config(), &mut c_err);
            if r != DuckDBSuccess {
                let msg = Some(CStr::from_ptr(c_err).to_string_lossy().to_string());
                duckdb_free(c_err as *mut c_void);
                return Err(Error::DuckDBFailure(FFIError::new(r), msg));
            }
            RawDatabase::new(db)
        }
    }
}
// SAFETY: The DuckDB database handle is internally reference-counted and thread-safe.
// Multiple connections (each on its own thread) may share the same database handle.
unsafe impl Send for RawDatabase {}
// SAFETY: Read-only access to the database handle (`db.0`) does not mutate DuckDB state.
// All mutation goes through `duckdb_connect`/`duckdb_close` which are themselves thread-safe.
unsafe impl Sync for RawDatabase {}

impl Drop for RawDatabase {
    #[inline]
    fn drop(&mut self) {
        // SAFETY: `self.0` is a valid duckdb_database (or null). `duckdb_close` accepts
        // null and is idempotent. After this call the handle is invalidated.
        unsafe {
            if !self.0.is_null() {
                duckdb_close(&mut self.0);
            }
        }
    }
}

/// A low-level connection to a DuckDB database.
///
/// `RawConnection` manages both a connection handle and a reference to the underlying
/// database. It provides methods to execute SQL commands and manage the connection lifecycle.
///
/// # Thread Safety
///
/// While the database handle is shared through an [`Arc`], each connection is unique and
/// should not be shared between threads. Instead, create new connections using
/// [`try_clone`](RawConnection::try_clone) for each thread.
///
/// # Resource Management
///
/// Connections are automatically closed when dropped. The underlying database remains open
/// until all connections are dropped and the last [`Arc`] reference is released.
///
/// # Example
///
/// ```rust,ignore
/// use better_duck_core::raw::RawConnection; // raw is crate-private
/// use std::ffi::CString;
/// let path = CString::new(":memory:").unwrap();
/// let mut conn = RawConnection::open_with_flags(&path, Default::default()).unwrap();
/// let _ = conn.query("CREATE TABLE test (id INTEGER, name TEXT)").unwrap();
/// let mut conn2 = conn.try_clone().unwrap();
/// ```
pub struct RawConnection {
    /// Shared handle to the underlying database.
    pub db: Arc<RawDatabase>,
    /// The raw DuckDB connection handle.
    pub con: duckdb_connection,
}

impl RawConnection {
    /// Returns the underlying raw DuckDB connection handle.
    ///
    /// # Safety
    ///
    /// This function exposes the raw FFI connection handle. Improper use of this handle
    /// may lead to undefined behavior. Use with caution.
    #[allow(unused)]
    fn raw(&self) -> duckdb_connection {
        self.con
    }

    /// Creates a new `RawConnection` from an existing [`RawDatabase`].
    ///
    /// # Safety
    ///
    /// The `db` must contain a valid, open `duckdb_database`. This function is called
    /// internally by [`open_with_flags`](RawConnection::open_with_flags).
    ///
    /// # Errors
    ///
    /// Returns an error if the connection cannot be established.
    #[inline]
    pub(crate) fn new(db: Arc<RawDatabase>) -> Result<RawConnection> {
        let mut con: duckdb_connection = ptr::null_mut();
        // SAFETY: `db.0` is a valid open duckdb_database; `con` is a valid output pointer.
        let r = unsafe { duckdb_connect(db.0, &mut con) };
        if r != DuckDBSuccess {
            // SAFETY: `con` may be partially initialized on failure; `duckdb_disconnect`
            // handles null/invalid handles gracefully.
            unsafe { duckdb_disconnect(&mut con) };
            return Err(Error::DuckDBFailure(FFIError::new(r), Some("connect error".to_owned())));
        }
        Ok(RawConnection { db, con })
    }

    /// Opens a new connection to the database at the given path with the specified config.
    ///
    /// Pass a path of `":memory:"` for an in-memory database.
    ///
    /// # Errors
    ///
    /// Returns an error if the database cannot be opened or the connection cannot be
    /// established.
    pub fn open_with_flags(
        c_path: &CStr,
        config: Config,
    ) -> Result<RawConnection> {
        RawConnection::new(Arc::new(RawDatabase::open_with_flags(c_path, config)?))
    }

    /// Closes the connection, releasing the underlying DuckDB handle.
    ///
    /// Subsequent calls are no-ops.
    ///
    /// # Errors
    ///
    /// Always returns `Ok(())`.
    pub fn close(&mut self) -> Result<()> {
        if self.con.is_null() {
            return Ok(());
        }
        // SAFETY: `self.con` is a valid open duckdb_connection. After disconnect it is
        // set to null so this code path cannot run twice.
        unsafe {
            duckdb_disconnect(&mut self.con);
            self.con = ptr::null_mut();
        }
        Ok(())
    }

    /// Creates a new connection to the same database as this one.
    ///
    /// The new connection shares the underlying database handle via [`Arc`].
    ///
    /// # Errors
    ///
    /// Returns `Error::DuckDBFailure` if the connection cannot be established.
    pub fn try_clone(&self) -> Result<Self> {
        // SAFETY: `self.db` is a valid Arc<RawDatabase> with a live database handle.
        RawConnection::new(self.db.clone())
    }

    /// Executes a SQL statement and returns the result.
    ///
    /// Use this for DDL (`CREATE TABLE`, `DROP`, etc.) and DML (`INSERT`, `UPDATE`,
    /// `DELETE`). For reading data, use [`prepare`](RawConnection::prepare) and
    /// [`Statement::execute`](crate::raw::statement::Statement::execute).
    ///
    /// # Errors
    ///
    /// Returns an error if the SQL cannot be executed or if `sql` contains a nul byte.
    #[must_use = "query returns a DuckResult; discard explicitly with `let _ = ...` if not needed"]
    pub fn query(
        &mut self,
        sql: impl AsRef<str>,
    ) -> Result<DuckResult> {
        let c_str = CString::new(sql.as_ref())?;
        // SAFETY: `mem::zeroed::<duckdb_result>()` produces an all-zeros value, which is
        // the correct initial state for a `duckdb_result` output parameter. `duckdb_result`
        // is a small `Copy` struct (a handful of counters/pointers) with no self-referential
        // fields, so it needs no stable heap address — DuckResult::new takes it by value.
        let mut out = unsafe { mem::zeroed::<duckdb_result>() };
        // SAFETY: `self.con` is a valid open duckdb_connection established in
        // `open_with_flags` and not yet disconnected. `c_str` is a valid null-terminated
        // CString that outlives this call. `&mut out` provides a pointer to the stack-local
        // zeroed `duckdb_result`. Ownership transfers to `DuckResult::new`, whose `Drop`
        // calls `duckdb_destroy_result` exactly once.
        let r = unsafe {
            duckdb_query(self.con, c_str.as_ptr() as *const c_char, &mut out as *mut duckdb_result)
        };
        result_from_duckdb_result(r, &mut out as *mut duckdb_result)?;
        Ok(DuckResult::new(out))
    }

    /// Prepares a SQL statement for execution.
    ///
    /// The returned [`Statement`] can be executed one or more times, optionally with
    /// different bound parameters.
    ///
    /// # Errors
    ///
    /// Returns an error if the SQL cannot be compiled into a prepared statement or if
    /// `sql` contains a nul byte.
    #[must_use = "prepare returns a Statement; call execute() to run it"]
    #[allow(unused)]
    pub fn prepare(
        &self,
        sql: impl AsRef<str>,
    ) -> Result<Statement<'_>> {
        Statement::new(self, sql.as_ref())
    }

    /// Creates a new appender for the specified table and schema.
    ///
    /// # Errors
    ///
    /// Returns an error if the table does not exist or the appender cannot be created.
    #[must_use = "appender returns an Appender that must be used to insert rows"]
    pub fn appender(
        &mut self,
        table: &str,
        schema: &str,
    ) -> Result<Appender> {
        Appender::new(self.clone(), table, schema)
    }

    /// Executes a parameterized INSERT statement for each value in `values`.
    ///
    /// # Errors
    ///
    /// Returns an error if the statement fails to execute or if no rows were inserted.
    #[must_use = "insert result should be checked"]
    #[allow(unused)]
    pub fn insert<T: AppendAble, I>(
        &mut self,
        sql: &str,
        values: I,
    ) -> Result<()>
    where
        I: IntoIterator<Item = T>,
    {
        let mut stmt = Statement::new(self, sql)?;
        for mut each in values {
            stmt.bind(&mut each)?;
        }
        let mut res = stmt.execute()?;
        if res.changes() > 0 {
            Ok(())
        } else {
            Err(Error::DuckDBFailure(
                FFIError::new(DuckDBError),
                Some("Failed to insert values".to_owned()),
            ))
        }
    }

    /// Prepares `sql`, binds `binds` in order, and executes the statement.
    ///
    /// Works for all statement types. Use [`DuckResult::changes()`] for affected rows
    /// (DML), or iterate the result for SELECT / RETURNING queries.
    /// Pass `&mut []` for not parameterized queries.
    ///
    /// # Errors
    ///
    /// Returns [`Error::DuckDBFailure`] if preparation, binding, or execution fails.
    #[must_use = "the DuckResult carries both affected-row count (.changes()) and row iterator"]
    pub fn execute(
        &mut self,
        sql: impl AsRef<str>,
        binds: &mut [&mut dyn AppendAble],
    ) -> Result<DuckResult> {
        let mut stmt = CachedStatement::prepare(self, sql)?;
        for (i, bind) in binds.iter_mut().enumerate() {
            stmt.bind((i + 1) as u64, *bind)?;
        }
        stmt.execute()
    }
}

impl Clone for RawConnection {
    /// Creates a new connection to the same database.
    ///
    /// # Warning
    ///
    /// Cloning a `RawConnection` creates a new DuckDB connection to the same underlying
    /// database. Prefer using [`try_clone`](RawConnection::try_clone) if you need to
    /// handle connection errors explicitly.
    fn clone(&self) -> Self {
        match self.try_clone() {
            Ok(con) => con,
            Err(e) => panic!("Failed to clone RawConnection: {e:?}"),
        }
    }
}
impl Drop for RawConnection {
    #[inline]
    fn drop(&mut self) {
        use std::thread::panicking;
        if let Err(e) = self.close() {
            if panicking() {
                eprintln!("Error while closing DuckDB connection: {e:?}");
            } else {
                panic!("Error while closing DuckDB connection: {e:?}");
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_raw_connection_open() {
        let path = CString::new(":memory:").unwrap();
        let config = Config::default();
        let conn = RawConnection::open_with_flags(&path, config);
        assert!(conn.is_ok());
    }

    #[test]
    fn test_raw_connection_execute() {
        let path = CString::new(":memory:").unwrap();
        let config = Config::default();
        let mut conn = RawConnection::open_with_flags(&path, config).unwrap();
        let result = conn.query("CREATE TABLE test (id INTEGER PRIMARY KEY, name TEXT)");
        assert!(result.is_ok(), "{}", result.err().unwrap());
    }

    #[test]
    fn test_raw_connection_prepare() {
        let path = CString::new(":memory:").unwrap();
        let config = Config::default();
        let mut conn = RawConnection::open_with_flags(&path, config).unwrap();

        let result = conn.query("CREATE TABLE test (id INTEGER PRIMARY KEY, name TEXT)");
        assert!(result.is_ok(), "{}", result.err().unwrap());

        let stmt = conn.prepare("SELECT * FROM test");
        assert!(stmt.is_ok(), "{}", stmt.err().unwrap());
    }

    #[test]
    fn test_raw_connection_appender() {
        let path = CString::new(":memory:").unwrap();
        let config = Config::default();
        let mut conn = RawConnection::open_with_flags(&path, config).unwrap();

        let result = conn.query("CREATE TABLE test_table (id INTEGER PRIMARY KEY, name TEXT)");
        assert!(result.is_ok(), "{}", result.err().unwrap());

        let appender = conn.appender("test_table", "main");
        assert!(appender.is_ok(), "{}", appender.err().unwrap());
    }
}