pub struct Query<T> { /* private fields */ }Expand description
A typed query that selects records from the database.
The type parameter T is the returning type — it encodes what
exec() produces, not just which model is being queried. A Query starts
as Query<List<M>> (returns Vec<M>) and can be narrowed:
| Type | exec() produces | Created by |
|---|---|---|
Query<List<M>> | Vec<M> | Query::all, Query::filter |
Query<M> | M (errors if missing) | .one() |
Query<Option<M>> | Option<M> | .first() |
§Building queries
Start with a generated finder (e.g., User::filter_by_name("Alice")) or
use Query::all and chain filter:
use toasty::stmt::{List, Query};
// All users
let q = Query::<List<User>>::all();
// Filtered
let q = Query::<List<User>>::all().filter(User::fields().age().gt(18));
// Chained
let q = Query::<List<User>>::all()
.filter(User::fields().name().eq("Alice"))
.limit(10);§Execution
Pass the query to Db::exec or convert it with
IntoStatement for batch use.
Implementations§
Source§impl<T> Query<T>
impl<T> Query<T>
Sourcepub fn from_expr(expr: Expr<T>) -> Query<T>
pub fn from_expr(expr: Expr<T>) -> Query<T>
Convert a model expression to a query.
§Examples
let expr = Expr::<i64>::from_untyped(core_stmt::Expr::Value(
core_stmt::Value::from(42_i64),
));
let _q = Query::from_expr(expr);Sourcepub fn filter(self, filter: Expr<bool>) -> Query<T>
pub fn filter(self, filter: Expr<bool>) -> Query<T>
Add an additional filter, combined with AND, to this query.
Returns self for method chaining.
§Examples
use toasty::stmt::{List, Query};
let q = Query::<List<User>>::all()
.filter(User::fields().name().eq("Alice"));Sourcepub fn set_filter(&mut self, filter: Expr<bool>) -> &mut Query<T>
pub fn set_filter(&mut self, filter: Expr<bool>) -> &mut Query<T>
Sets the filter, combined with AND, for this query overwriting existing ones.
§Examples
use toasty::stmt::{List, Query};
let mut q = Query::<List<User>>::all();
q.set_filter(User::fields().name().eq("Alice"));Sourcepub fn include(self, path: impl Into<Path>) -> Query<T>
pub fn include(self, path: impl Into<Path>) -> Query<T>
Eagerly load a related association when this query executes.
path identifies the relation to include (e.g., a has-many or
belongs-to field). The related records are loaded in the same
round-trip and attached to the parent model.
A multi-step (via) relation can also be included. Its targets are
reached through the relation path and grouped under each parent, with
duplicate targets collapsed so each one appears once. Including a via
relation is supported on SQL backends (SQLite, PostgreSQL, MySQL); it
is not yet available on DynamoDB.
§Examples
use toasty::stmt::{List, Query};
use toasty::schema::Model;
// Include the field at index 1 (name)
let q = Query::<List<User>>::all().include(User::path_field::<String>(1));Sourcepub fn order_by(self, order_by: impl Into<OrderBy>) -> Query<T>
pub fn order_by(self, order_by: impl Into<OrderBy>) -> Query<T>
Add a sort order to this query.
Pass an OrderByExpr obtained from
Path::asc or Path::desc, or a tuple of them to sort by several
fields at once. Calling order_by multiple times appends each
expression to the existing order, so later calls act as tie-breakers
for earlier ones.
§Examples
use toasty::stmt::{List, Query};
let q = Query::<List<User>>::all()
.order_by((User::fields().age().desc(), User::fields().name().asc()));Sourcepub fn set_order_by(&mut self, order_by: impl Into<OrderBy>) -> &mut Query<T>
pub fn set_order_by(&mut self, order_by: impl Into<OrderBy>) -> &mut Query<T>
Sets the sort order for this query overwriting existing ones.
Pass an OrderByExpr obtained from
Path::asc or Path::desc, or a tuple of them to sort by several
fields at once. Calling order_by multiple times appends each
expression to the existing order, so later calls act as tie-breakers
for earlier ones.
§Examples
use toasty::stmt::{List, Query};
let mut q = Query::<List<User>>::all();
q.set_order_by(User::fields().name().desc());Sourcepub fn limit(self, n: usize) -> Query<T>
pub fn limit(self, n: usize) -> Query<T>
Limit the number of records returned.
n is an upper bound, not a guarantee. The limit is applied to the
database query, but Toasty may apply additional filtering to the rows
the database returns. When that happens, the final result can have
fewer than n records even if more than n rows match the filter
expression.
§Examples
use toasty::stmt::{List, Query};
let q = Query::<List<User>>::all().limit(10);Sourcepub fn to_list(self) -> Query<List<T>>
pub fn to_list(self) -> Query<List<T>>
Widen a single-row query back into a list query.
This is the inverse of first or one.
Panics if the query is not currently in single-row mode.
§Panics
Panics if this query is not a single-row query.
§Examples
use toasty::stmt::{List, Query};
let q: Query<User> = Query::<List<User>>::all().one();
let _list_q: Query<List<User>> = q.to_list();Source§impl<T> Query<List<T>>
impl<T> Query<List<T>>
Sourcepub fn first(self) -> Query<Option<T>>
pub fn first(self) -> Query<Option<T>>
Narrow this list query to return at most one record, wrapped in
Option.
The resulting Query<Option<T>> returns Some(record) if at least one
row matches, or None if no rows match.
This applies LIMIT 1 to the database query. Toasty may then filter
the returned row, so None does not always mean that no rows in the
table match the filter expression.
§Examples
use toasty::stmt::{List, Query};
let q: Query<Option<User>> = Query::<List<User>>::all().first();Sourcepub fn one(self) -> Query<T>
pub fn one(self) -> Query<T>
Narrow this list query to return exactly one record.
The resulting Query<T> returns the record directly. If no rows match,
execution returns an error.
This applies LIMIT 1 to the database query. If Toasty filters the
returned row out, execution returns the same error as when the database
returns no rows.
§Examples
use toasty::stmt::{List, Query};
let q: Query<User> = Query::<List<User>>::all().one();Source§impl<T> Query<T>where
T: Load,
impl<T> Query<T>where
T: Load,
Sourcepub async fn exec(
self,
executor: &mut dyn Executor,
) -> Result<<T as Load>::Output, Error>
pub async fn exec( self, executor: &mut dyn Executor, ) -> Result<<T as Load>::Output, Error>
Execute this query against the given executor and return the result.
The return type depends on the query’s type parameter T:
Query<List<M>>returnsVec<M>.Query<M>returnsM(errors if no row matches).Query<Option<M>>returnsOption<M>.
§Examples
use toasty::stmt::{List, Query};
let users: Vec<User> = Query::<List<User>>::all()
.exec(&mut db)
.await
.unwrap();Source§impl<M> Query<List<M>>where
M: Model,
Methods for list queries: Query<List<M>>
impl<M> Query<List<M>>where
M: Model,
Methods for list queries: Query<List<M>>
Sourcepub fn count(self) -> Query<u64>
pub fn count(self) -> Query<u64>
Convert this list query into a count query that returns the number of
matching records as a u64.
The returned Query<u64> wraps a SELECT COUNT(*) query.
§Examples
use toasty::stmt::{List, Query};
let q: Query<u64> = Query::<List<User>>::all().count();Sourcepub fn select<E, T>(self, projection: E) -> Query<List<T>>
pub fn select<E, T>(self, projection: E) -> Query<List<T>>
Project this list query onto an expression, narrowing the returned
shape from M to T.
projection can be any expression source: a single field path
(returning Vec<T> for the field’s Rust type), a tuple of field paths
(returning Vec of a tuple), or any other type that implements
IntoExpr<T>. The default model projection is replaced wholesale by
the columns the projection expression references.
A multi-step (via) relation can be projected as well: a has_many
via yields a Vec of the distinct targets reached through the path
per row, and a single (has_one) via yields one target (or None).
This is supported on SQL backends (SQLite, PostgreSQL, MySQL); it is
not yet available on DynamoDB.
§Examples
use toasty::stmt::{List, Query};
// Single-field projection: returns `Vec<String>`.
let names: Vec<String> = Query::<List<User>>::all()
.select(User::fields().name())
.exec(&mut db)
.await
.unwrap();
// Tuple projection: returns `Vec<(i64, String)>`.
let pairs: Vec<(i64, String)> = Query::<List<User>>::all()
.select((User::fields().id(), User::fields().name()))
.exec(&mut db)
.await
.unwrap();Sourcepub fn all() -> Query<List<M>>
pub fn all() -> Query<List<M>>
Create a query that selects all records of M.
§Examples
use toasty::stmt::{List, Query};
let q = Query::<List<User>>::all();Sourcepub fn latest_by<U>(self, field: Path<M, U>) -> Query<List<M>>
pub fn latest_by<U>(self, field: Path<M, U>) -> Query<List<M>>
Sort this query so the most recently inserted records on field
appear first.
Convenience for order_by with Path::desc.
field must be a path rooted at this query’s model M.
§Examples
use toasty::stmt::{List, Query};
let q = Query::<List<User>>::all().latest_by(User::fields().id());Trait Implementations§
Source§impl<M> IntoScope<M> for Query<List<M>>
impl<M> IntoScope<M> for Query<List<M>>
Source§fn into_scope(self) -> Statement<List<M>>
fn into_scope(self) -> Statement<List<M>>
self into a Statement<List<M>> for use as an insert scope.Source§impl<M> IntoScope<M> for Query<Option<M>>
impl<M> IntoScope<M> for Query<Option<M>>
Source§fn into_scope(self) -> Statement<List<M>>
fn into_scope(self) -> Statement<List<M>>
self into a Statement<List<M>> for use as an insert scope.Source§impl<M> IntoScope<M> for Query<M>
impl<M> IntoScope<M> for Query<M>
Source§fn into_scope(self) -> Statement<List<M>>
fn into_scope(self) -> Statement<List<M>>
self into a Statement<List<M>> for use as an insert scope.