quack_rs/query/prepared.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//! Inspecting and executing a [`PreparedStatement`]; `bind.rs` binds its parameters.
7
8use std::ffi::CString;
9
10use libduckdb_sys::{
11 duckdb_bind_parameter_index, duckdb_clear_bindings, duckdb_destroy_prepare,
12 duckdb_destroy_result, duckdb_execute_prepared, duckdb_nparams, duckdb_parameter_name,
13 duckdb_prepared_statement, duckdb_result, duckdb_result_error, idx_t, DuckDBSuccess,
14};
15
16use super::cstr::c_str_to_owned;
17use super::{no_error_message, PreparedStatement, QueryResult};
18use crate::error::ExtensionError;
19
20impl PreparedStatement {
21 /// Number of `?` / `$name` parameters in the statement.
22 #[must_use]
23 pub fn parameter_count(&self) -> usize {
24 // SAFETY: `self.statement` is valid for this value's lifetime.
25 usize::try_from(unsafe { duckdb_nparams(self.statement) }).unwrap_or(0)
26 }
27
28 /// Name of the parameter at 1-based `index`, or `None` when `index` is out
29 /// of range.
30 ///
31 /// Every parameter has a name: a named one (`$foo`) returns it with its
32 /// case preserved (while [`parameter_index`][Self::parameter_index]
33 /// matches case-insensitively), and a positional one (`?`) returns its
34 /// 1-based position as text — `"1"`, `"2"`, ….
35 #[must_use]
36 pub fn parameter_name(&self, index: usize) -> Option<String> {
37 if index == 0 || index > self.parameter_count() {
38 return None;
39 }
40 // SAFETY: `index` was bounds-checked; DuckDB owns the returned string.
41 let ptr = unsafe { duckdb_parameter_name(self.statement, index as idx_t) };
42 // SAFETY: `ptr` is null or NUL-terminated.
43 let name = unsafe { c_str_to_owned(ptr) };
44 // DuckDB allocates the name; free it once copied.
45 if !ptr.is_null() {
46 // SAFETY: `ptr` came from DuckDB's allocator.
47 unsafe { libduckdb_sys::duckdb_free(ptr.cast_mut().cast()) };
48 }
49 name
50 }
51
52 /// 1-based index of the named parameter, or `None` if there is no such
53 /// parameter.
54 #[must_use]
55 pub fn parameter_index(&self, name: &str) -> Option<usize> {
56 let c_name = CString::new(name).ok()?;
57 let mut index: idx_t = 0;
58 // SAFETY: `self.statement` is valid; `c_name` outlives the call.
59 let state =
60 unsafe { duckdb_bind_parameter_index(self.statement, &raw mut index, c_name.as_ptr()) };
61 (state == DuckDBSuccess).then(|| usize::try_from(index).unwrap_or(0))
62 }
63
64 /// Executes the statement, asking `DuckDB` to stream the result instead of
65 /// materialising it.
66 ///
67 /// A materialised result holds every row in memory before the first one is
68 /// readable; a streaming result produces chunks on demand, which is what an
69 /// extension scanning a large table wants.
70 /// [`QueryResult::next_chunk`] drives both — `duckdb_fetch_chunk` is the
71 /// documented way to read either. The difference at the call site is
72 /// memory, and *when errors arrive*: a runtime error part-way through the
73 /// query surfaces from `next_chunk`, after the rows before it.
74 ///
75 /// `DuckDB` may still materialise (see
76 /// [`QueryResult::is_streaming`]), and a streaming result must be consumed
77 /// — or dropped — before another statement runs on the same connection.
78 /// What happens otherwise depends on the engine:
79 ///
80 /// - up to `DuckDB` 1.5.x, the other statement runs and invalidates the
81 /// stream; the next `next_chunk` returns an error;
82 /// - from 2.0.0, the other statement is refused with a "Resource In Use"
83 /// error (`DUCKDB_ERROR_RESOURCE_IN_USE`) and the stream carries on.
84 /// That covers everything that runs a statement on the connection:
85 /// `query`, `execute`, `prepare`, and an
86 /// [`Appender`][crate::appender::Appender]'s flush, whose rows are then
87 /// lost (see the appender docs).
88 ///
89 /// Dropping an unfinished stream is safe on both. From 2.0.0 it aborts
90 /// the query at once (`QueryResult::Close`) — in autocommit mode,
91 /// rolling back anything the statement wrote, as with
92 /// `INSERT … RETURNING` — and frees its operator states; up to 1.5.x those
93 /// live on until the next statement on the connection.
94 ///
95 /// Requires `duckdb-1-5`: `duckdb_execute_prepared_streaming` sits in the
96 /// unstable region of the C API struct.
97 ///
98 /// # Errors
99 ///
100 /// Returns [`ExtensionError`] carrying `DuckDB`'s message if execution
101 /// fails.
102 #[cfg(feature = "duckdb-1-5")]
103 pub fn execute_streaming(&self) -> Result<QueryResult, ExtensionError> {
104 // SAFETY: `duckdb_result` is a `#[repr(C)]` struct of three `idx_t`
105 // integers and three raw pointers; all-zero bits are a valid value of each
106 // (null pointers included). DuckDB overwrites it as an out-parameter.
107 let mut result: duckdb_result = unsafe { std::mem::zeroed() };
108 // SAFETY: `self.statement` is valid for this value's lifetime;
109 // `result` is a fresh out-parameter DuckDB fills in.
110 let state = unsafe {
111 libduckdb_sys::duckdb_execute_prepared_streaming(self.statement, &raw mut result)
112 };
113 if state == DuckDBSuccess {
114 return Ok(QueryResult::new(result));
115 }
116 // SAFETY: on an ordinary failure DuckDB populates the error slot and
117 // the result must be destroyed; on its `catch (...)` path `result` is
118 // left zeroed, which both calls handle.
119 let message = unsafe { c_str_to_owned(duckdb_result_error(&raw mut result)) }
120 .unwrap_or_else(|| no_error_message("duckdb_execute_prepared_streaming"));
121 // SAFETY: destroyed exactly once, here, on the error path.
122 unsafe { duckdb_destroy_result(&raw mut result) };
123 Err(ExtensionError::new(message))
124 }
125
126 /// Clears every binding, so the statement can be reused with fresh values.
127 ///
128 /// # Errors
129 ///
130 /// Returns an error if `DuckDB` rejects the request.
131 pub fn clear_bindings(&self) -> Result<(), ExtensionError> {
132 // SAFETY: `self.statement` is valid for this value's lifetime.
133 if unsafe { duckdb_clear_bindings(self.statement) } == DuckDBSuccess {
134 Ok(())
135 } else {
136 Err(ExtensionError::new("duckdb_clear_bindings failed"))
137 }
138 }
139
140 /// Executes the statement with its current bindings.
141 ///
142 /// # Errors
143 ///
144 /// Returns [`ExtensionError`] carrying `DuckDB`'s message if execution
145 /// fails.
146 pub fn execute(&self) -> Result<QueryResult, ExtensionError> {
147 // SAFETY: `duckdb_result` is a plain C struct with no invalid bit patterns;
148 // DuckDB overwrites it entirely before it is read.
149 let mut result: duckdb_result = unsafe { std::mem::zeroed() };
150 // SAFETY: `self.statement` is valid for this value's lifetime.
151 let state = unsafe { duckdb_execute_prepared(self.statement, &raw mut result) };
152 if state == DuckDBSuccess {
153 return Ok(QueryResult::new(result));
154 }
155 // SAFETY: on an ordinary failure DuckDB populated `result`; on its
156 // `catch (...)` path it left the zeroed `result` untouched, and
157 // `duckdb_result_error` returns null for that.
158 let message = unsafe { c_str_to_owned(duckdb_result_error(&raw mut result)) }
159 .unwrap_or_else(|| no_error_message("duckdb_execute_prepared"));
160 // SAFETY: destroyed exactly once, here, on the error path.
161 unsafe { duckdb_destroy_result(&raw mut result) };
162 Err(ExtensionError::new(message))
163 }
164
165 /// Returns the raw `duckdb_prepared_statement`.
166 ///
167 /// Do not destroy it — this value still owns it.
168 #[must_use]
169 pub const fn as_raw(&self) -> duckdb_prepared_statement {
170 self.statement
171 }
172
173 /// Takes ownership of a raw `duckdb_prepared_statement`, which is then
174 /// destroyed (`duckdb_destroy_prepare`) on drop: the way back into this
175 /// crate's RAII for a statement a raw call created —
176 /// `duckdb_prepare_extracted_statement`, or `duckdb_prepare` itself.
177 ///
178 /// A statement whose prepare failed is accepted: every method then
179 /// reports failure (`execute` returns its error, `statement_type` is
180 /// [`Invalid`][super::StatementType::Invalid], the counts are 0).
181 ///
182 /// # Safety
183 ///
184 /// `statement` must be a live statement from a `duckdb_prepare*` call
185 /// that nothing else destroys, and its connection must stay open for as
186 /// long as the returned value is used.
187 ///
188 /// # Example
189 ///
190 /// ```rust,no_run
191 /// use quack_rs::query::PreparedStatement;
192 ///
193 /// # unsafe fn demo(con: libduckdb_sys::duckdb_connection) {
194 /// let mut raw: libduckdb_sys::duckdb_prepared_statement = std::ptr::null_mut();
195 /// // SAFETY: `con` is open.
196 /// unsafe { libduckdb_sys::duckdb_prepare(con, c"SELECT 1".as_ptr(), &raw mut raw) };
197 /// // SAFETY: `raw` came from `duckdb_prepare` and is owned by nothing else.
198 /// let stmt = unsafe { PreparedStatement::from_raw(raw) };
199 /// let _ = stmt.execute();
200 /// # }
201 /// ```
202 #[must_use]
203 pub const unsafe fn from_raw(statement: duckdb_prepared_statement) -> Self {
204 Self { statement }
205 }
206
207 /// Gives up ownership and returns the raw statement, which the caller
208 /// must destroy (`duckdb_destroy_prepare`) or hand back to
209 /// [`from_raw`][Self::from_raw].
210 #[must_use]
211 pub const fn into_raw(self) -> duckdb_prepared_statement {
212 let raw = self.statement;
213 std::mem::forget(self);
214 raw
215 }
216}
217
218impl std::fmt::Debug for PreparedStatement {
219 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
220 f.debug_struct("PreparedStatement")
221 .field("statement", &self.statement)
222 .finish()
223 }
224}
225
226impl Drop for PreparedStatement {
227 fn drop(&mut self) {
228 // SAFETY: `self.statement` was owned by this value and is destroyed once.
229 unsafe { duckdb_destroy_prepare(&raw mut self.statement) };
230 }
231}