pub struct PreparedStatement { /* private fields */ }Expand description
A duckdb_prepared_statement, destroyed on drop.
Prepared statements are how an extension runs SQL with values it did not author. Interpolating a table name or a user-supplied string into SQL text is an injection bug; binding it is not.
Parameters are 1-indexed, matching the C API.
Implementations§
Source§impl PreparedStatement
impl PreparedStatement
Sourcepub fn bind_i64(&self, index: usize, value: i64) -> Result<(), ExtensionError>
pub fn bind_i64(&self, index: usize, value: i64) -> Result<(), ExtensionError>
Binds a BIGINT at 1-based index.
§Errors
Returns an error if DuckDB rejects the binding (bad index or type).
Sourcepub fn bind_decimal(
&self,
index: usize,
width: u8,
scale: u8,
unscaled: i128,
) -> Result<(), ExtensionError>
pub fn bind_decimal( &self, index: usize, width: u8, scale: u8, unscaled: i128, ) -> Result<(), ExtensionError>
Binds a DECIMAL(width, scale) at 1-based index.
unscaled is the value multiplied by 10^scale.
§Errors
Returns an error, without calling DuckDB, when width is not in
1..=38, scale > width, or unscaled has more than width digits.
duckdb_bind_decimal validates none of these: a bad width or an
unscaled too wide for the physical type throws (aborting the
process), and for width <= 18 it keeps only the low 64 bits of
unscaled, silently binding a different number. Otherwise see
bind_i64.
Sourcepub fn bind_date(&self, index: usize, days: i32) -> Result<(), ExtensionError>
pub fn bind_date(&self, index: usize, days: i32) -> Result<(), ExtensionError>
Binds a DATE at 1-based index, as days since 1970-01-01.
Every i32 is accepted, as by Value::date:
DuckDB renders any day count without failing. Days outside the range
its SQL produces (i32::MIN renders as 5877642-06-23 (BC)) come back
as text DuckDB cannot parse again.
§Errors
See bind_i64.
Sourcepub fn bind_time(&self, index: usize, micros: i64) -> Result<(), ExtensionError>
pub fn bind_time(&self, index: usize, micros: i64) -> Result<(), ExtensionError>
Binds a TIME at 1-based index, as microseconds since midnight.
§Errors
See bind_i64; also refuses, before calling DuckDB,
a value outside 0..=86_400_000_000 (00:00:00–24:00:00).
duckdb_bind_time checks nothing, and rendering such a value crashed
the process (i64::MIN) or invalidated the database (i64::MAX).
Sourcepub fn bind_timestamp(
&self,
index: usize,
micros: i64,
) -> Result<(), ExtensionError>
pub fn bind_timestamp( &self, index: usize, micros: i64, ) -> Result<(), ExtensionError>
Binds a TIMESTAMP at 1-based index, as microseconds since the epoch.
§Errors
See bind_i64; also refuses, before calling DuckDB,
a value below 290309-12-22 (BC) other than -infinity — the range of
Value::timestamp. DuckDB stores
such a value unchecked and then fails every read of it.
Sourcepub fn bind_timestamp_tz(
&self,
index: usize,
micros: i64,
) -> Result<(), ExtensionError>
pub fn bind_timestamp_tz( &self, index: usize, micros: i64, ) -> Result<(), ExtensionError>
Binds a TIMESTAMP WITH TIME ZONE at 1-based index, as microseconds
since the epoch.
§Errors
See bind_i64; also refuses the out-of-range values
bind_timestamp refuses.
Sourcepub fn bind_interval(
&self,
index: usize,
value: DuckInterval,
) -> Result<(), ExtensionError>
pub fn bind_interval( &self, index: usize, value: DuckInterval, ) -> Result<(), ExtensionError>
Sourcepub fn bind_value(
&self,
index: usize,
value: &Value,
) -> Result<(), ExtensionError>
pub fn bind_value( &self, index: usize, value: &Value, ) -> Result<(), ExtensionError>
Binds an arbitrary Value at 1-based index.
This is the escape hatch for everything the typed bind_* methods do
not cover — STRUCT, LIST, MAP, ARRAY, UNION, ENUM, UUID,
BIT, and any type a future DuckDB adds. DuckDB copies the value, so
value may be dropped immediately afterwards.
§Errors
See bind_i64.
§Example
use quack_rs::types::{LogicalType, TypeId};
use quack_rs::value::Value;
let ty = LogicalType::list(TypeId::BigInt);
let list = Value::list_value(&ty, &[Value::bigint(1), Value::bigint(2)])?;
stmt.bind_value(1, &list)?;Source§impl PreparedStatement
impl PreparedStatement
Sourcepub fn statement_type(&self) -> StatementType
pub fn statement_type(&self) -> StatementType
What kind of statement this is.
Returns StatementType::Invalid for a statement whose prepare
failed (only reachable through
from_raw): on 1.x duckdb_prepared_statement_type
dereferences the statement data a failed prepare does not have, so it
is not called for one.
Works on every supported DuckDB (stable C API slot 54).
§Example
use quack_rs::query::{OwnedConnection, StatementType};
let stmt = con.prepare(sql)?;
if stmt.statement_type() != StatementType::Select {
return Err("only SELECT statements are accepted".into());
}Sourcepub fn parameter_type(&self, index: usize) -> Option<LogicalType>
pub fn parameter_type(&self, index: usize) -> Option<LogicalType>
The type DuckDB inferred for the parameter at 1-based index, or
None when index is out of range or the binder could not infer a
type without a bound value (SELECT $1, b || $1).
Once the statement has executed, DuckDB reports the type of the
value last bound for a parameter whose type it could not infer.
Works on every supported DuckDB (stable C API slot 52).
Source§impl PreparedStatement
impl PreparedStatement
Sourcepub fn columns(&self) -> Option<Vec<(String, LogicalType)>>
pub fn columns(&self) -> Option<Vec<(String, LogicalType)>>
The name and type of each column the statement returns, before it
runs (DuckDB 1.5.0+).
Returns None when the result shape is not known until parameters
are bound: DuckDB then reports a single placeholder column named
unknown of an unresolved type (SELECT $1, SELECT b || $1 FROM t),
which is not the shape the statement returns. Also None for a
statement whose prepare failed. A statement that changes rows reports
the column its result has: an INSERT reports one BIGINT column,
Count.
Requires duckdb-1-5: the four duckdb_prepared_statement_column_*
calls sit in the unstable region of the C API struct.
§Example
let stmt = con.prepare("SELECT 42 AS answer, 'x' AS label")?;
for (name, ty) in stmt.columns().unwrap_or_default() {
// SAFETY: the C API is initialised (a statement exists).
println!("{name}: {:?}", unsafe { ty.try_get_type_id() });
}Source§impl PreparedStatement
impl PreparedStatement
Sourcepub fn parameter_count(&self) -> usize
pub fn parameter_count(&self) -> usize
Number of ? / $name parameters in the statement.
Sourcepub fn parameter_name(&self, index: usize) -> Option<String>
pub fn parameter_name(&self, index: usize) -> Option<String>
Name of the parameter at 1-based index, or None when index is out
of range.
Every parameter has a name: a named one ($foo) returns it with its
case preserved (while parameter_index
matches case-insensitively), and a positional one (?) returns its
1-based position as text — "1", "2", ….
Sourcepub fn parameter_index(&self, name: &str) -> Option<usize>
pub fn parameter_index(&self, name: &str) -> Option<usize>
1-based index of the named parameter, or None if there is no such
parameter.
Sourcepub fn execute_streaming(&self) -> Result<QueryResult, ExtensionError>
pub fn execute_streaming(&self) -> Result<QueryResult, ExtensionError>
Executes the statement, asking DuckDB to stream the result instead of
materialising it.
A materialised result holds every row in memory before the first one is
readable; a streaming result produces chunks on demand, which is what an
extension scanning a large table wants.
QueryResult::next_chunk drives both — duckdb_fetch_chunk is the
documented way to read either. The difference at the call site is
memory, and when errors arrive: a runtime error part-way through the
query surfaces from next_chunk, after the rows before it.
DuckDB may still materialise (see
QueryResult::is_streaming), and a streaming result must be consumed
— or dropped — before another statement runs on the same connection.
What happens otherwise depends on the engine:
- up to
DuckDB1.5.x, the other statement runs and invalidates the stream; the nextnext_chunkreturns an error; - from 2.0.0, the other statement is refused with a “Resource In Use”
error (
DUCKDB_ERROR_RESOURCE_IN_USE) and the stream carries on. That covers everything that runs a statement on the connection:query,execute,prepare, and anAppender’s flush, whose rows are then lost (see the appender docs).
Dropping an unfinished stream is safe on both. From 2.0.0 it aborts
the query at once (QueryResult::Close) — in autocommit mode,
rolling back anything the statement wrote, as with
INSERT … RETURNING — and frees its operator states; up to 1.5.x those
live on until the next statement on the connection.
Requires duckdb-1-5: duckdb_execute_prepared_streaming sits in the
unstable region of the C API struct.
§Errors
Returns ExtensionError carrying DuckDB’s message if execution
fails.
Sourcepub fn clear_bindings(&self) -> Result<(), ExtensionError>
pub fn clear_bindings(&self) -> Result<(), ExtensionError>
Clears every binding, so the statement can be reused with fresh values.
§Errors
Returns an error if DuckDB rejects the request.
Sourcepub fn execute(&self) -> Result<QueryResult, ExtensionError>
pub fn execute(&self) -> Result<QueryResult, ExtensionError>
Executes the statement with its current bindings.
§Errors
Returns ExtensionError carrying DuckDB’s message if execution
fails.
Sourcepub const fn as_raw(&self) -> duckdb_prepared_statement
pub const fn as_raw(&self) -> duckdb_prepared_statement
Returns the raw duckdb_prepared_statement.
Do not destroy it — this value still owns it.
Sourcepub const unsafe fn from_raw(statement: duckdb_prepared_statement) -> Self
pub const unsafe fn from_raw(statement: duckdb_prepared_statement) -> Self
Takes ownership of a raw duckdb_prepared_statement, which is then
destroyed (duckdb_destroy_prepare) on drop: the way back into this
crate’s RAII for a statement a raw call created —
duckdb_prepare_extracted_statement, or duckdb_prepare itself.
A statement whose prepare failed is accepted: every method then
reports failure (execute returns its error, statement_type is
Invalid, the counts are 0).
§Safety
statement must be a live statement from a duckdb_prepare* call
that nothing else destroys, and its connection must stay open for as
long as the returned value is used.
§Example
use quack_rs::query::PreparedStatement;
let mut raw: libduckdb_sys::duckdb_prepared_statement = std::ptr::null_mut();
// SAFETY: `con` is open.
unsafe { libduckdb_sys::duckdb_prepare(con, c"SELECT 1".as_ptr(), &raw mut raw) };
// SAFETY: `raw` came from `duckdb_prepare` and is owned by nothing else.
let stmt = unsafe { PreparedStatement::from_raw(raw) };
let _ = stmt.execute();