Skip to main content

Query

Struct Query 

Source
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:

Typeexec() producesCreated 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>

Source

pub fn unit() -> Query<T>

Create an empty unit query that returns no records.

§Examples
let q = Query::<()>::unit();
Source

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

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

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

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

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

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

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

pub fn offset(self, n: usize) -> Query<T>

Skip the first n records. Requires a prior call to limit.

§Panics

Panics if no limit has been set on this query.

§Examples
use toasty::stmt::{List, Query};

let q = Query::<List<User>>::all().limit(10).offset(20);
Source

pub fn delete(self) -> Delete<()>

Convert this query into a Delete statement that removes all matching records.

The returned Delete<()> does not return the removed records.

§Examples
use toasty::stmt::{List, Query};

let delete = Query::<List<User>>::all().filter(User::fields().name().eq("Alice"))
    .delete();
Source

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

Source

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

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,

Source

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>> returns Vec<M>.
  • Query<M> returns M (errors if no row matches).
  • Query<Option<M>> returns Option<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>>

Source

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

pub fn select<E, T>(self, projection: E) -> Query<List<T>>
where E: IntoExpr<T>, T: Load,

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

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

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<T> Clone for Query<T>

Source§

fn clone(&self) -> Query<T>

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<T> Debug for Query<T>

Source§

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

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

impl<M> From<Query<List<M>>> for Paginate<M>

Source§

fn from(value: Query<List<M>>) -> Paginate<M>

Converts to this type from the input type.
Source§

impl<M> From<Query<M>> for Statement<M>

Source§

fn from(value: Query<M>) -> Statement<M>

Converts to this type from the input type.
Source§

impl<M> IntoScope<M> for Query<List<M>>

Source§

fn into_scope(self) -> Statement<List<M>>

Lower self into a Statement<List<M>> for use as an insert scope.
Source§

impl<M> IntoScope<M> for Query<Option<M>>

Source§

fn into_scope(self) -> Statement<List<M>>

Lower self into a Statement<List<M>> for use as an insert scope.
Source§

impl<M> IntoScope<M> for Query<M>

Source§

fn into_scope(self) -> Statement<List<M>>

Lower self into a Statement<List<M>> for use as an insert scope.
Source§

impl<T> IntoStatement for Query<T>

Source§

type Returning = T

The type this statement produces when executed.
Source§

fn into_statement(self) -> Statement<T>

Consume self and produce the Statement.
Source§

impl<T> IntoStatement for &Query<T>

Source§

type Returning = T

The type this statement produces when executed.
Source§

fn into_statement(self) -> Statement<T>

Consume self and produce the Statement.

Auto Trait Implementations§

§

impl<T> Freeze for Query<T>
where PhantomData<T>: Freeze,

§

impl<T> RefUnwindSafe for Query<T>

§

impl<T> Send for Query<T>
where PhantomData<T>: Send,

§

impl<T> Sync for Query<T>
where PhantomData<T>: Sync,

§

impl<T> Unpin for Query<T>
where PhantomData<T>: Unpin,

§

impl<T> UnsafeUnpin for Query<T>

§

impl<T> UnwindSafe for Query<T>

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

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

Source§

type Error = !

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

fn try_from(value: U) -> Result<T, !>

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.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more