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>
impl<M: Model> Query<M>
Sourcepub fn new() -> Self
pub fn new() -> Self
All records, with the model’s default scope (default_scope … in
.glacier) applied, as every query starts.
Sourcepub fn with_trashed(self) -> Self
pub fn with_trashed(self) -> Self
Soft-deleted records too (soft_deletes).
Sourcepub fn only_trashed(self) -> Self
pub fn only_trashed(self) -> Self
Only soft-deleted records.
Sourcepub fn owned_by(self, access: &dyn Access) -> Self
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.
Sourcepub async fn find(self, id: impl ToValue) -> Result<M>
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.
Sourcepub fn build_with(&self, change: impl FnOnce(&mut M)) -> Mwhere
M: Default,
pub fn build_with(&self, change: impl FnOnce(&mut M)) -> Mwhere
M: Default,
A new record with change setting its fields, and the query’s owner
columns set: Note.for(access).build(title: "…") in .glacier.
Sourcepub fn build(&self, params: impl Into<Params>) -> Mwhere
M: Default,
pub fn build(&self, params: impl Into<Params>) -> Mwhere
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).
Sourcepub fn filter(self, condition: impl FnOnce(&M::Columns) -> Expr) -> Self
pub fn filter(self, condition: impl FnOnce(&M::Columns) -> Expr) -> Self
Adds a condition; several filter calls are combined with AND.
Sourcepub fn where_sql(
self,
sql: &str,
values: impl IntoIterator<Item = Value>,
) -> Self
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)", []).
Sourcepub fn order(self, order: impl FnOnce(&M::Columns) -> Order) -> Self
pub fn order(self, order: impl FnOnce(&M::Columns) -> Order) -> Self
Adds an ordering; earlier order calls take precedence.
Sourcepub fn sort(
self,
params: &Params,
allowed: impl AsRef<[&'static str]>,
) -> Result<Self>
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(¶ms, ["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.
Sourcepub fn order_raw(self, sql: impl Into<String>) -> Self
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.
pub fn limit(self, limit: u64) -> Self
pub fn offset(self, offset: u64) -> Self
Sourcepub fn page(self, page: Page) -> Self
pub fn page(self, page: Page) -> Self
One page of the results: Post.order(id: :desc).page(page).
Sourcepub fn on(self, conn: impl Into<Connection>) -> Self
pub fn on(self, conn: impl Into<Connection>) -> Self
Runs on conn instead of the ambient connection.
Sourcepub fn preload<P: Into<Preload<M>>>(
self,
association: impl FnOnce(&M::Columns) -> P,
) -> Self
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.
Sourcepub fn with_count<C>(
self,
association: impl FnOnce(&M::Columns) -> Association<M, C>,
) -> Selfwhere
M: 'static,
pub fn with_count<C>(
self,
association: impl FnOnce(&M::Columns) -> Association<M, C>,
) -> Selfwhere
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).
Sourcepub async fn cursor(self, page: CursorPage) -> Result<Cursored<M>>
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.
Sourcepub fn batches(self, size: u64) -> Batches<M>
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? { … }Sourcepub async fn estimated_count(self) -> Result<i64>
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.
Sourcepub fn join<C: Model>(
self,
association: impl FnOnce(&M::Columns) -> Association<M, C>,
condition: impl FnOnce(&C::Columns) -> Expr,
) -> Self
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.
Sourcepub fn where_has<C: Model>(
self,
association: impl FnOnce(&M::Columns) -> Association<M, C>,
inner: impl FnOnce(Query<C>) -> Query<C>,
) -> Self
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.
Sourcepub fn without<C: Model>(
self,
association: impl FnOnce(&M::Columns) -> Association<M, C>,
) -> Self
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).
Sourcepub fn joins<C: Model>(
self,
association: impl FnOnce(&M::Columns) -> Association<M, C>,
) -> Self
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).
Sourcepub fn to_sql(&self, dialect: Dialect) -> (String, Vec<Value>)
pub fn to_sql(&self, dialect: Dialect) -> (String, Vec<Value>)
The SQL this query would run, for debugging and tests.
pub async fn all(self) -> Result<Vec<M>>
Sourcepub async fn first(self) -> Result<Option<M>>
pub async fn first(self) -> Result<Option<M>>
The first match (by primary key unless ordered otherwise).
Sourcepub async fn last(self) -> Result<Option<M>>
pub async fn last(self) -> Result<Option<M>>
The last match: the ordering reversed, or the highest primary key.
Sourcepub async fn pluck<T: FromColumn>(
self,
column: impl FnOnce(&M::Columns) -> Col<M, T>,
) -> Result<Vec<T>>
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>.
Sourcepub async fn update_all<I>(
self,
assignments: impl FnOnce(&M::Columns) -> I,
) -> Result<u64>where
I: IntoIterator<Item = Assign>,
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)]).
Sourcepub fn distinct(self) -> Self
pub fn distinct(self) -> Self
Only distinct rows, as Rails’ distinct: with pluck, each value
once (Post::all().distinct().pluck(|p| p.status)).
Sourcepub fn sum<T: Summable>(
self,
column: impl FnOnce(&M::Columns) -> Col<M, T>,
) -> impl Future<Output = Result<T::Sum>> + Send
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.
Sourcepub fn average<T: Summable>(
self,
column: impl FnOnce(&M::Columns) -> Col<M, T>,
) -> impl Future<Output = Result<Option<f64>>> + Send
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).
Sourcepub fn minimum<T: Aggregable>(
self,
column: impl FnOnce(&M::Columns) -> Col<M, T>,
) -> impl Future<Output = Result<Option<T::Value>>> + Send
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.
Sourcepub fn maximum<T: Aggregable>(
self,
column: impl FnOnce(&M::Columns) -> Col<M, T>,
) -> impl Future<Output = Result<Option<T::Value>>> + Send
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.
Sourcepub fn group<K: FromColumn>(
self,
column: impl FnOnce(&M::Columns) -> Col<M, K>,
) -> Grouped<M, K>
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.
Sourcepub async fn find_by(
self,
condition: impl FnOnce(&M::Columns) -> Expr,
) -> Result<Option<M>>
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: …).
pub async fn count(self) -> Result<i64>
pub async fn exists(self) -> Result<bool>
Sourcepub async fn destroy_all(self) -> Result<u64>
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.
Sourcepub async fn delete_all(self) -> Result<u64>
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.
Sourcepub async fn force_delete_all(self) -> Result<u64>
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: Model> IntoFuture for Query<M>
impl<M: Model> IntoFuture for Query<M>
Source§type IntoFuture = Pin<Box<dyn Future<Output = Result<Vec<M>, Error>> + Send>>
type IntoFuture = Pin<Box<dyn Future<Output = Result<Vec<M>, Error>> + Send>>
Source§fn into_future(self) -> Self::IntoFuture
fn into_future(self) -> Self::IntoFuture
Auto Trait Implementations§
impl<M> !RefUnwindSafe for Query<M>
impl<M> !UnwindSafe for Query<M>
impl<M> Freeze for Query<M>
impl<M> Send for Query<M>
impl<M> Sync for Query<M>
impl<M> Unpin for Query<M>
impl<M> UnsafeUnpin for Query<M>
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
Source§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
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 moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
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