Skip to main content

Query

Struct Query 

Source
pub struct Query<M> { /* private fields */ }
Expand description

A query for records of M. Build it up, then .await it for a Vec<M>, or finish with .first(), .one(), .count(), .exists() or .delete_all().

Implementations§

Source§

impl<M: Model> Query<M>

Source

pub fn new() -> Self

All records, with the model’s default scope (default_scope … in .glacier) applied, as every query starts.

Source

pub fn unscoped() -> Self

All records, ignoring the model’s default scope.

Source

pub fn with_trashed(self) -> Self

Soft-deleted records too (soft_deletes).

Source

pub fn only_trashed(self) -> Self

Only soft-deleted records.

Source

pub fn owned_by(self, access: &dyn Access) -> Self

Only the rows access owns: each of the model’s owner columns equal to the access’s value for it. When the access has no value for one (a user’s access, for an org’s rows), nothing matches.

Source

pub async fn find(self, id: impl ToValue) -> Result<M>

The record with this primary key among the query’s, or 404 Not Found: Post.for(access).find(params[:id])! finds another org’s post no more than a missing one.

Source

pub fn build_with(&self, change: impl FnOnce(&mut M)) -> M
where M: Default,

A new record with change setting its fields, and the query’s owner columns set: Note.for(access).build(title: "…") in .glacier.

Source

pub fn build(&self, params: impl Into<Params>) -> M
where M: Default,

A new record from params, with the query’s owner columns set (the org’s id), as Rails’ current_org.posts.build(params).

Source

pub fn filter(self, condition: impl FnOnce(&M::Columns) -> Expr) -> Self

Adds a condition; several filter calls are combined with AND.

Source

pub fn where_sql( self, sql: &str, values: impl IntoIterator<Item = Value>, ) -> Self

Adds a condition in SQL, ? for each of values, as Rails’ where("…", …): Post.where_sql("NOT EXISTS (SELECT 1 FROM comments WHERE comments.post_id = posts.id)", []).

Source

pub fn order(self, order: impl FnOnce(&M::Columns) -> Order) -> Self

Adds an ordering; earlier order calls take precedence.

Source

pub fn sort( self, params: &Params, allowed: impl AsRef<[&'static str]>, ) -> Result<Self>

Orders by the request’s sort param, as JSON:API has it: ?sort=-inserted_at,title sorts by inserted_at descending, then title. Only the columns in allowed can be named; anything else is a 400 Bad Request. Given, it replaces the query’s own order; absent or empty, the query keeps it:

ⓘ
let books = Book::order(|b| b.title.asc())
    .sort(&params, ["title", "inserted_at"])?
    .await?;
§Errors

400 Bad Request naming the column that can’t be sorted by.

§Panics

If allowed names a column the model doesn’t have.

Source

pub fn order_raw(self, sql: impl Into<String>) -> Self

Orders by raw SQL, as Rails’ .order("first_name ASC, last_name ASC"), after any typed orders. Never pass it user input: build it from fixed choices.

Source

pub fn limit(self, limit: u64) -> Self

Source

pub fn offset(self, offset: u64) -> Self

Source

pub fn page(self, page: Page) -> Self

One page of the results: Post.order(id: :desc).page(page).

Source

pub fn on(self, conn: impl Into<Connection>) -> Self

Runs on conn instead of the ambient connection.

Source

pub fn preload<P: Into<Preload<M>>>( self, association: impl FnOnce(&M::Columns) -> P, ) -> Self

Loads an association for every record with one extra query.

Source

pub fn with_count<C>( self, association: impl FnOnce(&M::Columns) -> Association<M, C>, ) -> Self
where M: 'static,

Counts a has_many association for each record loaded, without loading its records: Author.with_count(:books), then author.books.count(), in one grouped query.

§Panics

For an association that isn’t a has_many (without through).

Source

pub async fn cursor(self, page: CursorPage) -> Result<Cursored<M>>

One page of the matches by cursor (keyset) pagination, in the query’s order with the primary key as the tie-breaker: Post::order(|p| p.inserted_at.desc()).cursor(page).await?. Fast at any depth, and no row is skipped or repeated when rows change between pages. Order by columns that are never NULL; order_raw can’t be paged this way.

Source

pub fn batches(self, size: u64) -> Batches<M>

The matches in batches of size, by the same keyset paging as cursor (so rows changing meanwhile are neither skipped nor repeated), as Rails’ in_batches/find_each:

ⓘ
let mut batches = Post::all().batches(1000);
while let Some(posts) = batches.next().await? { … }
Source

pub async fn estimated_count(self) -> Result<i64>

How many rows match, cheaply: for a whole Postgres table, the planner’s estimate (from its statistics, so approximate); otherwise an exact count.

Source

pub fn join<C: Model>( self, association: impl FnOnce(&M::Columns) -> Association<M, C>, condition: impl FnOnce(&C::Columns) -> Expr, ) -> Self

Joins an association’s table, keeping the matches with a related record that meets condition, as Rails’ joins(:author).where(users: {…}): Post::all().join(|p| p.author, |a| a.name.eq("Ada")). A has_many join gives a match per related record; add distinct().

Through a join table (has_many :tags, through: :book_tags), it joins that table, then the other model’s.

Source

pub fn where_has<C: Model>( self, association: impl FnOnce(&M::Columns) -> Association<M, C>, inner: impl FnOnce(Query<C>) -> Query<C>, ) -> Self

The records with at least one associated record matching inner, as Laravel’s whereHas: Author.where_has(:books, published: true) in .glacier. One EXISTS subquery, so each record comes once, and the associated model’s default scope (and soft deletes) apply.

Source

pub fn without<C: Model>( self, association: impl FnOnce(&M::Columns) -> Association<M, C>, ) -> Self

The records with no associated record at all, as Laravel’s doesntHave: Author.without(:books).

Source

pub fn joins<C: Model>( self, association: impl FnOnce(&M::Columns) -> Association<M, C>, ) -> Self

Joins an association’s table: the matches with at least one related record, as Rails’ joins(:comments).

Source

pub fn to_sql(&self, dialect: Dialect) -> (String, Vec<Value>)

The SQL this query would run, for debugging and tests.

Source

pub async fn all(self) -> Result<Vec<M>>

Source

pub async fn first(self) -> Result<Option<M>>

The first match (by primary key unless ordered otherwise).

Source

pub async fn last(self) -> Result<Option<M>>

The last match: the ordering reversed, or the highest primary key.

Source

pub async fn take(self, n: u64) -> Result<Vec<M>>

The first n matches.

Source

pub async fn pluck<T: FromColumn>( self, column: impl FnOnce(&M::Columns) -> Col<M, T>, ) -> Result<Vec<T>>

One column of every match, without loading records: Post::all().pluck(|p| p.title).await? → Vec<String>.

Source

pub async fn ids(self) -> Result<Vec<i64>>

The primary keys of every match.

Source

pub async fn update_all<I>( self, assignments: impl FnOnce(&M::Columns) -> I, ) -> Result<u64>
where I: IntoIterator<Item = Assign>,

Sets columns on every match in one statement, returning how many changed. Like Rails’ update_all, it skips validations and callbacks: Post::filter(…).update_all(|p| [p.published.to(false)]).

Source

pub fn distinct(self) -> Self

Only distinct rows, as Rails’ distinct: with pluck, each value once (Post::all().distinct().pluck(|p| p.status)).

Source

pub fn sum<T: Summable>( self, column: impl FnOnce(&M::Columns) -> Col<M, T>, ) -> impl Future<Output = Result<T::Sum>> + Send

The sum of a numeric column over the matches, 0 when there are none, as Rails’ sum: Post::all().sum(|p| p.views). Integer columns sum to an i64.

Source

pub fn average<T: Summable>( self, column: impl FnOnce(&M::Columns) -> Col<M, T>, ) -> impl Future<Output = Result<Option<f64>>> + Send

The mean of a numeric column, None without matches. A float, whatever the column (Rails returns a BigDecimal).

Source

pub fn minimum<T: Aggregable>( self, column: impl FnOnce(&M::Columns) -> Col<M, T>, ) -> impl Future<Output = Result<Option<T::Value>>> + Send

The smallest value of a column, None without matches.

Source

pub fn maximum<T: Aggregable>( self, column: impl FnOnce(&M::Columns) -> Col<M, T>, ) -> impl Future<Output = Result<Option<T::Value>>> + Send

The largest value of a column, None without matches.

Source

pub fn group<K: FromColumn>( self, column: impl FnOnce(&M::Columns) -> Col<M, K>, ) -> Grouped<M, K>

Groups the matches by a column, to count or total each group: Post::all().group(|p| p.status).count() → [("draft", 3), …], in the order of the column’s values.

Source

pub async fn find_by( self, condition: impl FnOnce(&M::Columns) -> Expr, ) -> Result<Option<M>>

The first match that also meets condition, or None: a scope’s find_by, as User.active().find_by(email_address: …).

Source

pub async fn one(self) -> Result<M>

Like first, but a missing record is a 404 Not Found.

Source

pub async fn count(self) -> Result<i64>

Source

pub async fn exists(self) -> Result<bool>

Source

pub async fn destroy_all(self) -> Result<u64>

Destroys every matching record one by one, running each one’s destroy callbacks (and dependent children), as Rails’ destroy_all; returns how many. delete_all is one DELETE.

Source

pub async fn delete_all(self) -> Result<u64>

Deletes every matching record, returning how many there were. For a soft_deletes model it sets their deleted_at instead; force_delete_all deletes them.

Source

pub async fn force_delete_all(self) -> Result<u64>

Deletes every matching record for good, even a soft_deletes model’s.

Trait Implementations§

Source§

impl<M> Clone for Query<M>

A query can be reused: count it, then fetch a page of it.

Source§

fn clone(&self) -> Self

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<M: Model> Default for Query<M>

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl<M: Model> IntoFuture for Query<M>

Source§

type Output = Result<Vec<M>, Error>

The output that the future will produce on completion.
Source§

type IntoFuture = Pin<Box<dyn Future<Output = Result<Vec<M>, Error>> + Send>>

Which kind of future are we turning this into?
Source§

fn into_future(self) -> Self::IntoFuture

Creates a future from a value. Read more

Auto Trait Implementations§

§

impl<M> !RefUnwindSafe for Query<M>

§

impl<M> !UnwindSafe for Query<M>

§

impl<M> Freeze for Query<M>
where Vec<Preload<M>>: Freeze, PhantomData<fn() -> M>: Freeze,

§

impl<M> Send for Query<M>
where Vec<Preload<M>>: Send, PhantomData<fn() -> M>: Send,

§

impl<M> Sync for Query<M>
where Vec<Preload<M>>: Sync, PhantomData<fn() -> M>: Sync,

§

impl<M> Unpin for Query<M>
where Vec<Preload<M>>: Unpin, PhantomData<fn() -> M>: Unpin,

§

impl<M> UnsafeUnpin for Query<M>

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<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> IntoField<Option<T>> for T

Source§

fn into_field(self) -> Option<T>

Source§

impl<T> IntoField<T> for T

Source§

fn into_field(self) -> T

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

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<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

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