Skip to main content

Statement

Struct Statement 

Source
pub struct Statement<'c> { /* private fields */ }
Expand description

A prepared statement bound to a specific connection lifetime.

SQLR-23 — Statement carries the parsed AST (parsed exactly once at prepare time), not just the raw SQL. query / run execute against the cached AST; query_with_params / execute_with_params clone the AST and substitute ? placeholders before dispatch.

Implementations§

Source§

impl<'c> Statement<'c>

Source

pub fn parameter_count(&self) -> usize

Number of ? placeholders detected in the source SQL. Strict arity validation: passing a slice of a different length to query_with_params / execute_with_params returns a typed error.

Source

pub fn run(&mut self) -> Result<String>

Executes a prepared non-query statement. Equivalent to Connection::execute — included for parity with the typed-row query() so callers who want Statement::run / Statement::query symmetry get it.

Errors if the prepared SQL contains ? placeholders — use Statement::execute_with_params for those.

Source

pub fn execute_with_params(&mut self, params: &[Value]) -> Result<String>

SQLR-23 — executes a prepared non-SELECT statement after binding ? placeholders to params (positional, in source order).

Use this for parameterized INSERT / UPDATE / DELETE — the substitution clones the cached AST, fills in the ? slots from params, and dispatches without re-running sqlparser. For SELECT, prefer Statement::query_with_params.

Source

pub fn query(&self) -> Result<Rows>

Runs a SELECT and returns a Rows iterator over typed rows. Errors if the prepared statement isn’t a SELECT.

SQLR-23 — uses the SELECT narrowing cached at prepare time; no per-call sqlparser walk. Errors if the prepared SQL contains ? placeholders — use Statement::query_with_params for those.

Examples found in repository?
examples/hybrid-retrieval/hybrid_retrieval.rs (line 127)
125fn print_top(conn: &mut Connection, sql: &str) -> Result<()> {
126    let stmt = conn.prepare(sql)?;
127    let mut rows = stmt.query()?;
128    let mut rank = 1;
129    while let Some(row) = rows.next()? {
130        let name: String = row.get_by_name("name")?;
131        let body: String = row.get_by_name("body")?;
132        println!("  {rank}. {name}  \"{body}\"");
133        rank += 1;
134    }
135    println!();
136    Ok(())
137}
More examples
Hide additional examples
examples/rust/concurrent_writers.rs (line 77)
75fn print_balances(conn: &mut Connection) -> Result<()> {
76    let stmt = conn.prepare("SELECT id, holder, balance FROM accounts ORDER BY id")?;
77    let mut rows = stmt.query()?;
78    while let Some(row) = rows.next()? {
79        let id: i64 = row.get_by_name("id")?;
80        let holder: String = row.get_by_name("holder")?;
81        let balance: i64 = row.get_by_name("balance")?;
82        println!("  account {id} ({holder}): {balance}");
83    }
84    Ok(())
85}
examples/rust/quickstart.rs (line 24)
14fn main() -> Result<()> {
15    let mut conn = Connection::open_in_memory()?;
16
17    conn.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER);")?;
18    conn.execute("INSERT INTO users (name, age) VALUES ('alice', 30);")?;
19    conn.execute("INSERT INTO users (name, age) VALUES ('bob', 25);")?;
20    conn.execute("INSERT INTO users (name, age) VALUES ('charlie', 40);")?;
21
22    println!("All users:");
23    let stmt = conn.prepare("SELECT id, name, age FROM users;")?;
24    let mut rows = stmt.query()?;
25    while let Some(row) = rows.next()? {
26        let id: i64 = row.get_by_name("id")?;
27        let name: String = row.get_by_name("name")?;
28        // `Option<i64>` wraps NULL cleanly — `age` is declared
29        // nullable so the typed accessor surfaces None when absent.
30        let age: Option<i64> = row.get_by_name("age")?;
31        println!(
32            "  {} — {} ({})",
33            id,
34            name,
35            age.map(|a| a.to_string())
36                .unwrap_or_else(|| "NULL".to_string())
37        );
38    }
39
40    // Transactions: BEGIN + INSERT + ROLLBACK leaves the table untouched.
41    conn.execute("BEGIN;")?;
42    conn.execute("INSERT INTO users (name, age) VALUES ('will_vanish', 99);")?;
43    println!("\nMid-transaction row count: {}", count_users(&mut conn)?);
44    conn.execute("ROLLBACK;")?;
45    println!(
46        "Post-rollback row count:   {} (unchanged)",
47        count_users(&mut conn)?
48    );
49
50    Ok(())
51}
52
53fn count_users(conn: &mut Connection) -> Result<usize> {
54    let stmt = conn.prepare("SELECT id FROM users;")?;
55    let rows = stmt.query()?.collect_all()?;
56    Ok(rows.len())
57}
Source

pub fn query_with_params(&self, params: &[Value]) -> Result<Rows>

SQLR-23 — runs a SELECT and returns a Rows iterator after binding ? placeholders to params. Positional, source-order indexing — params[0] is ?1, params[1] is ?2, etc.

Vector parameters (Value::Vector(...)) substitute as the in-band bracket-array shape the executor recognizes, so a bound query vector still triggers the HNSW probe optimizer (Phase 7d.2 KNN shortcut).

Source

pub fn column_names(&self) -> Option<Vec<String>>

Column names this statement will produce, in projection order. None for non-SELECT statements.

Trait Implementations§

Source§

impl Debug for Statement<'_>

Source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<'c> Freeze for Statement<'c>

§

impl<'c> RefUnwindSafe for Statement<'c>

§

impl<'c> Send for Statement<'c>

§

impl<'c> Sync for Statement<'c>

§

impl<'c> Unpin for Statement<'c>

§

impl<'c> UnsafeUnpin for Statement<'c>

§

impl<'c> !UnwindSafe for Statement<'c>

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.