Struct Statement

Source
pub struct Statement { /* private fields */ }
Expand description

A prepared statement.

The basic method for accessing data using sqlite3_ext is:

  1. Create a Statement using Connection::prepare.
  2. Bind parameters (if necessary) using Statement::query.
  3. Retrieve results using Statement::map or Statement::next.

Statement objects can be reused for multiple executions. A call to query resets the bound parameters and restarts the query. This also applies to methods that call query internally, like execute and query_row.

Results can be accessed in an imperative or functional style. The imperative style looks like this:

use sqlite3_ext::*;

fn pages_imperative(conn: &Connection, user_id: i64) -> Result<Vec<(i64, String)>> {
    let mut stmt = conn.prepare("SELECT id, name FROM pages WHERE owner_id = ?")?;
    stmt.query([user_id])?;
    let mut results = Vec::new();
    while let Some(row) = stmt.next()? {
        results.push((
            row[0].get_i64(),
            row[1].get_str()?.to_owned(),
        ));
    }
    Ok(results)
}

The functional style makes use of FallibleIterator methods.

use sqlite3_ext::*;

fn pages_functional(conn: &Connection, user_id: i64) -> Result<Vec<(i64, String)>> {
    let results: Vec<(i64, String)> = conn
        .prepare("SELECT id, name FROM pages WHERE owner_id = ?")?
        .query([user_id])?
        .map(|row| {
            Ok((
                row[0].get_i64(),
                row[1].get_str()?.to_owned(),
            ))
        })
        .collect()?;
    Ok(results)
}

Implementations§

Source§

impl Statement

Source

pub unsafe fn as_ptr(&self) -> *mut sqlite3_stmt

Return the underlying sqlite3_stmt pointer.

§Safety

This method is unsafe because applying SQLite methods to the sqlite3_stmt pointer returned by this method may violate invariants of other methods on this statement.

Source

pub fn query<P: Params>(&mut self, params: P) -> Result<&mut Self>

Bind the provided parameters to the query. If the query was previously used, it is reset and existing parameters are cleared.

This method is not necessary to call on the first execution of a query where there are no parameters to bind (e.g. on a single-use hard-coded query).

Source

pub fn query_row<P, R, F>(&mut self, params: P, f: F) -> Result<R>
where P: Params, F: FnOnce(&mut QueryResult) -> Result<R>,

Execute a query which is expected to return only a single row.

This method will fail with SQLITE_EMPTY if the query does not return any rows. If the query has multiple rows, only the first will be returned.

If you are not storing this Statement for later reuse, Connection::query_row is a shortcut for this method.

Source

pub fn execute<P: Params>(&mut self, params: P) -> Result<i64>

Execute a query that is expected to return no results (such as an INSERT, UPDATE, or DELETE).

If this query returns rows, this method will fail with SQLITE_MISUSE (use query for a query which returns rows).

If you are not storing this Statement for later reuse, Connection::execute is a shortcut for this method.

Source

pub fn insert<P: Params>(&mut self, params: P) -> Result<i64>

Execute a query that is expected to be an INSERT, then return the inserted rowid.

This method will fail with SQLITE_MISUSE if this method returns rows, but there are no other verifications that the executed statement is actually an INSERT. If this Statement is not an INSERT, the return value of this function is meaningless.

Source

pub fn sql(&self) -> Result<&str>

Returns the original text of the prepared statement.

Source

pub fn parameter_count(&self) -> i32

Returns the number of parameters which should be bound to the query. Valid parameter positions are 1..=self.parameter_count().

Source

pub fn parameter_name(&self, position: i32) -> Option<&str>

Returns the name of the parameter at the given position. Note that the first parameter has a position of 1, not 0.

Source

pub fn parameter_position(&self, name: impl Into<Vec<u8>>) -> Option<NonZeroI32>

Return the position of the parameter with the provided name.

Source

pub fn column_count(&self) -> usize

Returns the number of columns in the result set returned by this query.

Source

pub fn current_result(&self) -> Option<&QueryResult>

Returns the current result, without advancing the cursor. This method returns None if the query has already run to completion, or if the query has not been started using query.

Source

pub fn current_result_mut(&mut self) -> Option<&mut QueryResult>

Mutable version of current_result.

Source

pub unsafe fn db<'a>(&self) -> &'a Connection

Returns a handle to the Connection associated with this statement.

§Safety

The returned reference’s lifetime is not tied to the lifetime of this Statement. It is the responsibility of the caller to ensure that the Connection reference is not improperly used.

Trait Implementations§

Source§

impl Debug for Statement

Source§

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

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

impl Drop for Statement

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

impl FallibleIteratorMut for Statement

Source§

type Item = QueryResult

The type of item being iterated.
Source§

type Error = Error

The type of error that can be returned by this iterator.
Source§

fn next(&mut self) -> Result<Option<&mut Self::Item>>

Works like FallibleIterator::next, except instead of returning Self::Item, it returns &mut Self::Item.
Source§

fn size_hint(&self) -> (usize, Option<usize>)

Source§

fn map<F, B>(&mut self, f: F) -> Map<'_, Self, F>
where Self: Sized, F: FnMut(&mut Self::Item) -> Result<B, Self::Error>,

Convert this iterator into a FallibleIterator by applying a function to each element.

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.