Struct yatt_orm::sqlite::SQLITEStatement
source · [−]pub struct SQLITEStatement<'conn> { /* private fields */ }
Expand description
A prepared statement.
Implementations
sourceimpl<'_> Statement<'_>
impl<'_> Statement<'_>
sourcepub fn column_names(&self) -> Vec<&str, Global>
pub fn column_names(&self) -> Vec<&str, Global>
Get all the column names in the result set of the prepared statement.
sourcepub fn column_count(&self) -> usize
pub fn column_count(&self) -> usize
Return the number of columns in the result set returned by the prepared statement.
sourcepub fn column_name(&self, col: usize) -> Result<&str, Error>
pub fn column_name(&self, col: usize) -> Result<&str, Error>
Returns the name assigned to a particular column in the result set returned by the prepared statement.
Failure
Returns an Error::InvalidColumnIndex
if idx
is outside the valid
column range for this row.
Panics when column name is not valid UTF-8.
sourcepub fn column_index(&self, name: &str) -> Result<usize, Error>
pub fn column_index(&self, name: &str) -> Result<usize, Error>
Returns the column index in the result set for a given column name.
If there is no AS clause then the name of the column is unspecified and may change from one release of SQLite to the next.
Failure
Will return an Error::InvalidColumnName
when there is no column with
the specified name
.
sourceimpl<'_> Statement<'_>
impl<'_> Statement<'_>
sourcepub fn execute<P>(&mut self, params: P) -> Result<usize, Error> where
P: IntoIterator,
<P as IntoIterator>::Item: ToSql,
pub fn execute<P>(&mut self, params: P) -> Result<usize, Error> where
P: IntoIterator,
<P as IntoIterator>::Item: ToSql,
Execute the prepared statement.
On success, returns the number of rows that were changed or inserted or
deleted (via sqlite3_changes
).
Example
fn update_rows(conn: &Connection) -> Result<()> {
let mut stmt = conn.prepare("UPDATE foo SET bar = 'baz' WHERE qux = ?")?;
stmt.execute(&[1i32])?;
stmt.execute(&[2i32])?;
Ok(())
}
Failure
Will return Err
if binding parameters fails, the executed statement
returns rows (in which case query
should be used instead), or the
underlying SQLite call fails.
sourcepub fn execute_named(
&mut self,
params: &[(&str, &dyn ToSql)]
) -> Result<usize, Error>
pub fn execute_named(
&mut self,
params: &[(&str, &dyn ToSql)]
) -> Result<usize, Error>
Execute the prepared statement with named parameter(s). If any
parameters that were in the prepared statement are not included in
params
, they will continue to use the most-recently bound value
from a previous call to execute_named
, or NULL
if they have
never been bound.
On success, returns the number of rows that were changed or inserted or
deleted (via sqlite3_changes
).
Example
fn insert(conn: &Connection) -> Result<usize> {
let mut stmt = conn.prepare("INSERT INTO test (name) VALUES (:name)")?;
stmt.execute_named(&[(":name", &"one")])
}
Note, the named_params
macro is provided for syntactic convenience,
and so the above example could also be written as:
fn insert(conn: &Connection) -> Result<usize> {
let mut stmt = conn.prepare("INSERT INTO test (name) VALUES (:name)")?;
stmt.execute_named(named_params!{":name": "one"})
}
Failure
Will return Err
if binding parameters fails, the executed statement
returns rows (in which case query
should be used instead), or the
underlying SQLite call fails.
sourcepub fn insert<P>(&mut self, params: P) -> Result<i64, Error> where
P: IntoIterator,
<P as IntoIterator>::Item: ToSql,
pub fn insert<P>(&mut self, params: P) -> Result<i64, Error> where
P: IntoIterator,
<P as IntoIterator>::Item: ToSql,
Execute an INSERT and return the ROWID.
Note
This function is a convenience wrapper around execute()
intended for
queries that insert a single item. It is possible to misuse this
function in a way that it cannot detect, such as by calling it on a
statement which updates a single
item rather than inserting one. Please don’t do that.
Failure
Will return Err
if no row is inserted or many rows are inserted.
sourcepub fn query<P>(&mut self, params: P) -> Result<Rows<'_>, Error> where
P: IntoIterator,
<P as IntoIterator>::Item: ToSql,
pub fn query<P>(&mut self, params: P) -> Result<Rows<'_>, Error> where
P: IntoIterator,
<P as IntoIterator>::Item: ToSql,
Execute the prepared statement, returning a handle to the resulting rows.
Due to lifetime restricts, the rows handle returned by query
does not
implement the Iterator
trait. Consider using query_map
or
query_and_then
instead, which do.
Example
fn get_names(conn: &Connection) -> Result<Vec<String>> {
let mut stmt = conn.prepare("SELECT name FROM people")?;
let mut rows = stmt.query(NO_PARAMS)?;
let mut names = Vec::new();
while let Some(row) = rows.next()? {
names.push(row.get(0)?);
}
Ok(names)
}
Failure
Will return Err
if binding parameters fails.
sourcepub fn query_named(
&mut self,
params: &[(&str, &dyn ToSql)]
) -> Result<Rows<'_>, Error>
pub fn query_named(
&mut self,
params: &[(&str, &dyn ToSql)]
) -> Result<Rows<'_>, Error>
Execute the prepared statement with named parameter(s), returning a
handle for the resulting rows. If any parameters that were in the
prepared statement are not included in params
, they will continue
to use the most-recently bound value from a previous
call to query_named
, or NULL
if they have never been bound.
Example
fn query(conn: &Connection) -> Result<()> {
let mut stmt = conn.prepare("SELECT * FROM test where name = :name")?;
let mut rows = stmt.query_named(&[(":name", &"one")])?;
while let Some(row) = rows.next()? {
// ...
}
Ok(())
}
Note, the named_params!
macro is provided for syntactic convenience,
and so the above example could also be written as:
fn query(conn: &Connection) -> Result<()> {
let mut stmt = conn.prepare("SELECT * FROM test where name = :name")?;
let mut rows = stmt.query_named(named_params!{ ":name": "one" })?;
while let Some(row) = rows.next()? {
// ...
}
Ok(())
}
Failure
Will return Err
if binding parameters fails.
sourcepub fn query_map<T, P, F>(
&mut self,
params: P,
f: F
) -> Result<MappedRows<'_, F>, Error> where
P: IntoIterator,
F: FnMut(&Row<'_>) -> Result<T, Error>,
<P as IntoIterator>::Item: ToSql,
pub fn query_map<T, P, F>(
&mut self,
params: P,
f: F
) -> Result<MappedRows<'_, F>, Error> where
P: IntoIterator,
F: FnMut(&Row<'_>) -> Result<T, Error>,
<P as IntoIterator>::Item: ToSql,
Executes the prepared statement and maps a function over the resulting rows, returning an iterator over the mapped function results.
Example
fn get_names(conn: &Connection) -> Result<Vec<String>> {
let mut stmt = conn.prepare("SELECT name FROM people")?;
let rows = stmt.query_map(NO_PARAMS, |row| row.get(0))?;
let mut names = Vec::new();
for name_result in rows {
names.push(name_result?);
}
Ok(names)
}
Failure
Will return Err
if binding parameters fails.
sourcepub fn query_map_named<T, F>(
&mut self,
params: &[(&str, &dyn ToSql)],
f: F
) -> Result<MappedRows<'_, F>, Error> where
F: FnMut(&Row<'_>) -> Result<T, Error>,
pub fn query_map_named<T, F>(
&mut self,
params: &[(&str, &dyn ToSql)],
f: F
) -> Result<MappedRows<'_, F>, Error> where
F: FnMut(&Row<'_>) -> Result<T, Error>,
Execute the prepared statement with named parameter(s), returning an
iterator over the result of calling the mapping function over the
query’s rows. If any parameters that were in the prepared statement
are not included in params
, they will continue to use the
most-recently bound value from a previous call to query_named
,
or NULL
if they have never been bound.
Example
fn get_names(conn: &Connection) -> Result<Vec<String>> {
let mut stmt = conn.prepare("SELECT name FROM people WHERE id = :id")?;
let rows = stmt.query_map_named(&[(":id", &"one")], |row| row.get(0))?;
let mut names = Vec::new();
for name_result in rows {
names.push(name_result?);
}
Ok(names)
}
Failure
Will return Err
if binding parameters fails.
sourcepub fn query_and_then<T, E, P, F>(
&mut self,
params: P,
f: F
) -> Result<AndThenRows<'_, F>, Error> where
P: IntoIterator,
E: From<Error>,
F: FnMut(&Row<'_>) -> Result<T, E>,
<P as IntoIterator>::Item: ToSql,
pub fn query_and_then<T, E, P, F>(
&mut self,
params: P,
f: F
) -> Result<AndThenRows<'_, F>, Error> where
P: IntoIterator,
E: From<Error>,
F: FnMut(&Row<'_>) -> Result<T, E>,
<P as IntoIterator>::Item: ToSql,
Executes the prepared statement and maps a function over the resulting
rows, where the function returns a Result
with Error
type
implementing std::convert::From<Error>
(so errors can be unified).
Failure
Will return Err
if binding parameters fails.
sourcepub fn query_and_then_named<T, E, F>(
&mut self,
params: &[(&str, &dyn ToSql)],
f: F
) -> Result<AndThenRows<'_, F>, Error> where
E: From<Error>,
F: FnMut(&Row<'_>) -> Result<T, E>,
pub fn query_and_then_named<T, E, F>(
&mut self,
params: &[(&str, &dyn ToSql)],
f: F
) -> Result<AndThenRows<'_, F>, Error> where
E: From<Error>,
F: FnMut(&Row<'_>) -> Result<T, E>,
Execute the prepared statement with named parameter(s), returning an
iterator over the result of calling the mapping function over the
query’s rows. If any parameters that were in the prepared statement
are not included in
params
, they will
continue to use the most-recently bound value from a previous call
to query_named
, or NULL
if they have never been bound.
Example
struct Person {
name: String,
};
fn name_to_person(name: String) -> Result<Person> {
// ... check for valid name
Ok(Person { name: name })
}
fn get_names(conn: &Connection) -> Result<Vec<Person>> {
let mut stmt = conn.prepare("SELECT name FROM people WHERE id = :id")?;
let rows =
stmt.query_and_then_named(&[(":id", &"one")], |row| name_to_person(row.get(0)?))?;
let mut persons = Vec::new();
for person_result in rows {
persons.push(person_result?);
}
Ok(persons)
}
Failure
Will return Err
if binding parameters fails.
sourcepub fn exists<P>(&mut self, params: P) -> Result<bool, Error> where
P: IntoIterator,
<P as IntoIterator>::Item: ToSql,
pub fn exists<P>(&mut self, params: P) -> Result<bool, Error> where
P: IntoIterator,
<P as IntoIterator>::Item: ToSql,
Return true
if a query in the SQL statement it executes returns one
or more rows and false
if the SQL returns an empty set.
sourcepub fn query_row<T, P, F>(&mut self, params: P, f: F) -> Result<T, Error> where
P: IntoIterator,
F: FnOnce(&Row<'_>) -> Result<T, Error>,
<P as IntoIterator>::Item: ToSql,
pub fn query_row<T, P, F>(&mut self, params: P, f: F) -> Result<T, Error> where
P: IntoIterator,
F: FnOnce(&Row<'_>) -> Result<T, Error>,
<P as IntoIterator>::Item: ToSql,
Convenience method to execute a query that is expected to return a single row.
If the query returns more than one row, all rows except the first are ignored.
Returns Err(QueryReturnedNoRows)
if no results are returned. If the
query truly is optional, you can call .optional()
on the result of
this to get a Result<Option<T>>
.
Failure
Will return Err
if the underlying SQLite call fails.
sourcepub fn query_row_named<T, F>(
&mut self,
params: &[(&str, &dyn ToSql)],
f: F
) -> Result<T, Error> where
F: FnOnce(&Row<'_>) -> Result<T, Error>,
pub fn query_row_named<T, F>(
&mut self,
params: &[(&str, &dyn ToSql)],
f: F
) -> Result<T, Error> where
F: FnOnce(&Row<'_>) -> Result<T, Error>,
Convenience method to execute a query with named parameter(s) that is expected to return a single row.
If the query returns more than one row, all rows except the first are ignored.
Returns Err(QueryReturnedNoRows)
if no results are returned. If the
query truly is optional, you can call .optional()
on the result of
this to get a Result<Option<T>>
.
Failure
Will return Err
if sql
cannot be converted to a C-compatible string
or if the underlying SQLite call fails.
sourcepub fn finalize(self) -> Result<(), Error>
pub fn finalize(self) -> Result<(), Error>
Consumes the statement.
Functionally equivalent to the Drop
implementation, but allows
callers to see any errors that occur.
Failure
Will return Err
if the underlying SQLite call fails.
sourcepub fn parameter_index(&self, name: &str) -> Result<Option<usize>, Error>
pub fn parameter_index(&self, name: &str) -> Result<Option<usize>, Error>
Return the (one-based) index of an SQL parameter given its name.
Note that the initial “:” or “$” or “@” or “?” used to specify the parameter is included as part of the name.
fn example(conn: &Connection) -> Result<()> {
let stmt = conn.prepare("SELECT * FROM test WHERE name = :example")?;
let index = stmt.parameter_index(":example")?;
assert_eq!(index, Some(1));
Ok(())
}
Failure
Will return Err if name
is invalid. Will return Ok(None) if the name
is valid but not a bound parameter of this statement.
sourcepub fn parameter_count(&self) -> usize
pub fn parameter_count(&self) -> usize
Return the number of parameters that can be bound to this statement.
sourcepub fn raw_bind_parameter<T>(
&mut self,
one_based_col_index: usize,
param: T
) -> Result<(), Error> where
T: ToSql,
pub fn raw_bind_parameter<T>(
&mut self,
one_based_col_index: usize,
param: T
) -> Result<(), Error> where
T: ToSql,
Low level API to directly bind a parameter to a given index.
Note that the index is one-based, that is, the first parameter index is
1 and not 0. This is consistent with the SQLite API and the values given
to parameters bound as ?NNN
.
The valid values for one_based_col_index
begin at 1
, and end at
Statement::parameter_count
, inclusive.
Caveats
This should not generally be used, but is available for special cases such as:
- binding parameters where a gap exists.
- binding named and positional parameters in the same query.
- separating parameter binding from query execution.
Statements that have had their parameters bound this way should be
queried or executed by Statement::raw_query
or
Statement::raw_execute
. Other functions are not guaranteed to work.
Example
fn query(conn: &Connection) -> Result<()> {
let mut stmt = conn.prepare("SELECT * FROM test WHERE name = :name AND value > ?2")?;
let name_index = stmt.parameter_index(":name")?.expect("No such parameter");
stmt.raw_bind_parameter(name_index, "foo")?;
stmt.raw_bind_parameter(2, 100)?;
let mut rows = stmt.raw_query();
while let Some(row) = rows.next()? {
// ...
}
Ok(())
}
sourcepub fn raw_execute(&mut self) -> Result<usize, Error>
pub fn raw_execute(&mut self) -> Result<usize, Error>
Low level API to execute a statement given that all parameters were
bound explicitly with the Statement::raw_bind_parameter
API.
Caveats
Any unbound parameters will have NULL
as their value.
This should not generally be used outside of special cases, and
functions in the Statement::execute
family should be preferred.
Failure
Will return Err
if the executed statement returns rows (in which case
query
should be used instead), or the underlying SQLite call fails.
sourcepub fn raw_query(&mut self) -> Rows<'_>
pub fn raw_query(&mut self) -> Rows<'_>
Low level API to get Rows
for this query given that all parameters
were bound explicitly with the Statement::raw_bind_parameter
API.
Caveats
Any unbound parameters will have NULL
as their value.
This should not generally be used outside of special cases, and
functions in the Statement::query
family should be preferred.
Note that if the SQL does not return results, Statement::raw_execute
should be used instead.
sourcepub fn expanded_sql(&self) -> Option<String>
pub fn expanded_sql(&self) -> Option<String>
Returns a string containing the SQL text of prepared statement with bound parameters expanded.
sourcepub fn get_status(&self, status: StatementStatus) -> i32
pub fn get_status(&self, status: StatementStatus) -> i32
Get the value for one of the status counters for this statement.
sourcepub fn reset_status(&self, status: StatementStatus) -> i32
pub fn reset_status(&self, status: StatementStatus) -> i32
Reset the value of one of the status counters for this statement, returning the value it had before resetting.
Trait Implementations
Auto Trait Implementations
impl<'conn> !RefUnwindSafe for Statement<'conn>
impl<'conn> !Send for Statement<'conn>
impl<'conn> !Sync for Statement<'conn>
impl<'conn> Unpin for Statement<'conn>
impl<'conn> !UnwindSafe for Statement<'conn>
Blanket Implementations
sourceimpl<T> BorrowMut<T> for T where
T: ?Sized,
impl<T> BorrowMut<T> for T where
T: ?Sized,
const: unstable · sourcefn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more