Skip to main content

PreparedStatement

Struct PreparedStatement 

Source
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

Source

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).

Source

pub fn bind_f64(&self, index: usize, value: f64) -> Result<(), ExtensionError>

Binds a DOUBLE at 1-based index.

§Errors

See bind_i64.

Source

pub fn bind_bool(&self, index: usize, value: bool) -> Result<(), ExtensionError>

Binds a BOOLEAN at 1-based index.

§Errors

See bind_i64.

Source

pub fn bind_str(&self, index: usize, value: &str) -> Result<(), ExtensionError>

Binds a VARCHAR at 1-based index.

The length is passed explicitly, so embedded NUL bytes are preserved and no CString conversion can fail.

§Errors

See bind_i64.

Source

pub fn bind_blob( &self, index: usize, value: &[u8], ) -> Result<(), ExtensionError>

Binds a BLOB at 1-based index.

§Errors

See bind_i64.

Source

pub fn bind_null(&self, index: usize) -> Result<(), ExtensionError>

Binds SQL NULL at 1-based index.

§Errors

See bind_i64.

Source

pub fn bind_i8(&self, index: usize, value: i8) -> Result<(), ExtensionError>

Binds a TINYINT at 1-based index.

§Errors

See bind_i64.

Source

pub fn bind_i16(&self, index: usize, value: i16) -> Result<(), ExtensionError>

Binds a SMALLINT at 1-based index.

§Errors

See bind_i64.

Source

pub fn bind_i32(&self, index: usize, value: i32) -> Result<(), ExtensionError>

Binds an INTEGER at 1-based index.

§Errors

See bind_i64.

Source

pub fn bind_u8(&self, index: usize, value: u8) -> Result<(), ExtensionError>

Binds a UTINYINT at 1-based index.

§Errors

See bind_i64.

Source

pub fn bind_u16(&self, index: usize, value: u16) -> Result<(), ExtensionError>

Binds a USMALLINT at 1-based index.

§Errors

See bind_i64.

Source

pub fn bind_u32(&self, index: usize, value: u32) -> Result<(), ExtensionError>

Binds a UINTEGER at 1-based index.

§Errors

See bind_i64.

Source

pub fn bind_u64(&self, index: usize, value: u64) -> Result<(), ExtensionError>

Binds a UBIGINT at 1-based index.

§Errors

See bind_i64.

Source

pub fn bind_f32(&self, index: usize, value: f32) -> Result<(), ExtensionError>

Binds a FLOAT at 1-based index.

§Errors

See bind_i64.

Source

pub fn bind_i128(&self, index: usize, value: i128) -> Result<(), ExtensionError>

Binds a HUGEINT at 1-based index.

§Errors

See bind_i64.

Source

pub fn bind_u128(&self, index: usize, value: u128) -> Result<(), ExtensionError>

Binds a UHUGEINT at 1-based index.

§Errors

See bind_i64.

Source

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.

Source

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.

Source

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).

Source

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.

Source

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.

Source

pub fn bind_interval( &self, index: usize, value: DuckInterval, ) -> Result<(), ExtensionError>

Binds an INTERVAL at 1-based index.

§Errors

See bind_i64.

Source

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

Source

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());
}
Source

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

Source

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

Source

pub fn parameter_count(&self) -> usize

Number of ? / $name parameters in the statement.

Source

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", ….

Source

pub fn parameter_index(&self, name: &str) -> Option<usize>

1-based index of the named parameter, or None if there is no such parameter.

Source

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 DuckDB 1.5.x, the other statement runs and invalidates the stream; the next next_chunk returns 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 an Appender’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.

Source

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.

Source

pub fn execute(&self) -> Result<QueryResult, ExtensionError>

Executes the statement with its current bindings.

§Errors

Returns ExtensionError carrying DuckDB’s message if execution fails.

Source

pub const fn as_raw(&self) -> duckdb_prepared_statement

Returns the raw duckdb_prepared_statement.

Do not destroy it — this value still owns it.

Source

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();
Source

pub const fn into_raw(self) -> duckdb_prepared_statement

Gives up ownership and returns the raw statement, which the caller must destroy (duckdb_destroy_prepare) or hand back to from_raw.

Trait Implementations§

Source§

impl Debug for PreparedStatement

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Drop for PreparedStatement

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

fn pin_drop(self: Pin<&mut Self>)

🔬This is a nightly-only experimental API. (pin_ergonomics)
Execute the destructor for this type, but different to Drop::drop, it requires self to be pinned. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.