Skip to main content

quack_rs/query/
connection.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//! [`OwnedConnection`] and its cross-thread [`InterruptHandle`].
7
8use libduckdb_sys::{
9    duckdb_connect, duckdb_connection, duckdb_database, duckdb_disconnect, DuckDBSuccess,
10};
11
12use super::{
13    execute, interrupt, prepare, query, query_progress, InterruptHandle, OwnedConnection,
14    PreparedStatement, QueryProgress, QueryResult,
15};
16use crate::error::ExtensionError;
17
18impl InterruptHandle<'_> {
19    /// Requests cancellation of the query currently running on the connection.
20    pub fn cancel(&self) {
21        // SAFETY: the `'a` borrow keeps the connection open for this call.
22        unsafe { interrupt(self.con) };
23    }
24
25    /// Reads the progress of the query currently running on the connection.
26    ///
27    /// `percentage` is `-1.0` whenever `DuckDB` cannot say — see
28    /// [`QueryProgress`] for when that is, which on 1.x includes a whole
29    /// query whose pipelines do not all report progress.
30    #[must_use]
31    pub fn progress(&self) -> QueryProgress {
32        // SAFETY: the `'a` borrow keeps the connection open for this call.
33        unsafe { query_progress(self.con) }
34    }
35}
36
37impl OwnedConnection {
38    /// Opens a new connection to `db`.
39    ///
40    /// # Errors
41    ///
42    /// Returns [`ExtensionError`] if `DuckDB` refuses to open the connection.
43    ///
44    /// # Safety
45    ///
46    /// `db` must be a valid `duckdb_database`, such as the one obtained from
47    /// [`Connection::as_raw_database`][crate::connection::Connection::as_raw_database].
48    pub unsafe fn open(db: duckdb_database) -> Result<Self, ExtensionError> {
49        let mut con: duckdb_connection = std::ptr::null_mut();
50        // SAFETY: `db` is valid per the caller's contract.
51        if unsafe { duckdb_connect(db, &raw mut con) } != DuckDBSuccess {
52            return Err(ExtensionError::new("duckdb_connect failed"));
53        }
54        Ok(Self { con })
55    }
56
57    /// Runs `sql` on this connection.
58    ///
59    /// # Errors
60    ///
61    /// See [`query`].
62    pub fn query(&self, sql: &str) -> Result<QueryResult, ExtensionError> {
63        // SAFETY: `self.con` is open for this value's lifetime.
64        unsafe { query(self.con, sql) }
65    }
66
67    /// Runs `sql` for its side effects, returning the number of rows changed.
68    ///
69    /// # Errors
70    ///
71    /// See [`query`].
72    pub fn execute(&self, sql: &str) -> Result<u64, ExtensionError> {
73        // SAFETY: `self.con` is open for this value's lifetime.
74        unsafe { execute(self.con, sql) }
75    }
76
77    /// Prepares `sql` on this connection.
78    ///
79    /// # Errors
80    ///
81    /// See [`prepare`].
82    pub fn prepare(&self, sql: &str) -> Result<PreparedStatement, ExtensionError> {
83        // SAFETY: `self.con` is open for this value's lifetime.
84        unsafe { prepare(self.con, sql) }
85    }
86
87    /// Returns a `Send + Sync` handle for cancelling a query running on this
88    /// connection, or reading its progress, from another thread.
89    ///
90    /// The handle borrows the connection, so it cannot outlive the
91    /// `duckdb_disconnect` in [`Drop`].
92    #[must_use]
93    pub const fn interrupt_handle(&self) -> InterruptHandle<'_> {
94        InterruptHandle {
95            con: self.con,
96            _borrow: core::marker::PhantomData,
97        }
98    }
99
100    /// Requests cancellation of whatever this connection is currently running.
101    ///
102    /// See [`interrupt`] for what "cancellation" means here. To cancel from
103    /// another thread, use [`interrupt_handle`][Self::interrupt_handle].
104    pub fn interrupt(&self) {
105        // SAFETY: `self.con` is open for this value's lifetime.
106        unsafe { interrupt(self.con) };
107    }
108
109    /// Reads the progress of whatever this connection is currently running.
110    #[must_use]
111    pub fn progress(&self) -> QueryProgress {
112        // SAFETY: `self.con` is open for this value's lifetime.
113        unsafe { query_progress(self.con) }
114    }
115
116    /// Returns the raw handle. Do not disconnect it — this value still owns it.
117    #[must_use]
118    pub const fn as_raw(&self) -> duckdb_connection {
119        self.con
120    }
121
122    /// Takes ownership of a raw connection, which is then disconnected
123    /// (`duckdb_disconnect`) on drop.
124    ///
125    /// # Safety
126    ///
127    /// `con` must be a live connection from `duckdb_connect` that nothing
128    /// else disconnects. In particular **not** the connection `DuckDB` passes
129    /// to an extension's entry point
130    /// ([`Connection::as_raw_connection`][crate::connection::Connection::as_raw_connection]):
131    /// that one is borrowed, and the entry point disconnects it.
132    ///
133    /// # Example
134    ///
135    /// ```rust,no_run
136    /// use quack_rs::query::OwnedConnection;
137    ///
138    /// # unsafe fn demo(db: libduckdb_sys::duckdb_database) {
139    /// let mut raw: libduckdb_sys::duckdb_connection = std::ptr::null_mut();
140    /// // SAFETY: `db` is open.
141    /// if unsafe { libduckdb_sys::duckdb_connect(db, &raw mut raw) } == libduckdb_sys::DuckDBSuccess {
142    ///     // SAFETY: a fresh connection owned by nothing else.
143    ///     let con = unsafe { OwnedConnection::from_raw(raw) };
144    ///     let _ = con.execute("SELECT 1");
145    /// }
146    /// # }
147    /// ```
148    #[must_use]
149    pub const unsafe fn from_raw(con: duckdb_connection) -> Self {
150        Self { con }
151    }
152
153    /// Gives up ownership and returns the raw connection, which the caller
154    /// must disconnect (`duckdb_disconnect`) or hand back to
155    /// [`from_raw`][Self::from_raw].
156    #[must_use]
157    pub const fn into_raw(self) -> duckdb_connection {
158        let raw = self.con;
159        std::mem::forget(self);
160        raw
161    }
162
163    /// The tables `sql` reads or writes; see [`table_names`][super::table_names]
164    /// (`DuckDB` 1.5.0+).
165    ///
166    /// # Errors
167    ///
168    /// See [`table_names`][super::table_names].
169    #[cfg(feature = "duckdb-1-5")]
170    pub fn table_names(&self, sql: &str, qualified: bool) -> Result<Vec<String>, ExtensionError> {
171        // SAFETY: `self.con` is open for this value's lifetime.
172        unsafe { super::table_names(self.con, sql, qualified) }
173    }
174}
175
176impl std::fmt::Debug for OwnedConnection {
177    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
178        f.debug_struct("OwnedConnection")
179            .field("con", &self.con)
180            .finish()
181    }
182}
183
184impl Drop for OwnedConnection {
185    fn drop(&mut self) {
186        // SAFETY: `self.con` was opened by this value and is disconnected once.
187        unsafe { duckdb_disconnect(&raw mut self.con) };
188    }
189}