pub struct SelectQuery<'db, M: Model, Out = M, I = ()> { /* private fields */ }Expand description
A typed SELECT query.
Not Debug: the executor behind it is a trait object, and requiring
Debug on Executor would exclude perfectly good executors for no gain.
Use to_sql to inspect a query instead — that is the
representation anyone debugging actually wants.
Implementations§
Source§impl<'db, M> SelectQuery<'db, M, M, ()>where
M: Model,
impl<'db, M> SelectQuery<'db, M, M, ()>where
M: Model,
Source§impl<'db, M, Out, I> SelectQuery<'db, M, Out, I>where
M: Model,
impl<'db, M, Out, I> SelectQuery<'db, M, Out, I>where
M: Model,
Sourcepub fn or_filter_if(self, f: Option<Filter<M>>) -> Self
pub fn or_filter_if(self, f: Option<Filter<M>>) -> Self
Adds a filter (OR) only if f is Some.
Sourcepub fn filter_type<V: Encodable>(
self,
col: Column<M, V>,
value: impl Into<V>,
) -> Self
pub fn filter_type<V: Encodable>( self, col: Column<M, V>, value: impl Into<V>, ) -> Self
Filters rows by discriminator column value for Single Table Inheritance (STI) and polymorphic models.
Sourcepub fn order_by_if(self, o: Option<OrderBy<M>>) -> Self
pub fn order_by_if(self, o: Option<OrderBy<M>>) -> Self
Adds an ordering only if o is Some.
Sourcepub fn after<V: Ordered>(
self,
col: Column<M, V>,
value: impl Into<V>,
n: u64,
) -> Self
pub fn after<V: Ordered>( self, col: Column<M, V>, value: impl Into<V>, n: u64, ) -> Self
Returns the first n rows after a cursor value (exclusive).
Sourcepub fn before<V: Ordered>(
self,
col: Column<M, V>,
value: impl Into<V>,
n: u64,
) -> Self
pub fn before<V: Ordered>( self, col: Column<M, V>, value: impl Into<V>, n: u64, ) -> Self
Returns the first n rows before a cursor value (exclusive).
Sourcepub fn cache(self, _ttl: Duration) -> Self
👎Deprecated since 1.5.2: has no effect: the query cache is not wired to execution; use InMemoryCache directly
pub fn cache(self, _ttl: Duration) -> Self
has no effect: the query cache is not wired to execution; use InMemoryCache directly
Does nothing. The argument is discarded and the query is not cached.
Query execution never reads or writes a QueryCache.
To cache results, call InMemoryCache (or your own
QueryCache) around the query yourself. This method will be implemented or
removed in 2.0.
Sourcepub fn cache_key(self, _key: impl Into<String>) -> Self
👎Deprecated since 1.5.2: has no effect: the query cache is not wired to execution; use InMemoryCache directly
pub fn cache_key(self, _key: impl Into<String>) -> Self
has no effect: the query cache is not wired to execution; use InMemoryCache directly
Does nothing. See SelectQuery::cache.
Sourcepub fn cache_tag(self, _tag: impl Into<String>) -> Self
👎Deprecated since 1.5.2: has no effect: the query cache is not wired to execution; use InMemoryCache directly
pub fn cache_tag(self, _tag: impl Into<String>) -> Self
has no effect: the query cache is not wired to execution; use InMemoryCache directly
Does nothing. See SelectQuery::cache.
Sourcepub fn use_primary(self) -> Self
👎Deprecated since 1.5.2: has no effect: build the query on RoutedPool::primary() instead
pub fn use_primary(self) -> Self
has no effect: build the query on RoutedPool::primary() instead
Does nothing. The query runs on whatever executor it was built with.
For a read that must see the primary, build the query on
RoutedPool::primary() instead. This method
will be implemented or removed in 2.0.
Sourcepub fn use_replica(self) -> Self
👎Deprecated since 1.5.2: has no effect: build the query on a RoutedPool or RoutedPool::select_replica()
pub fn use_replica(self) -> Self
has no effect: build the query on a RoutedPool or RoutedPool::select_replica()
Does nothing. The query runs on whatever executor it was built with.
To read from a replica, build the query on a
RoutedPool (reads are routed to replicas) or on
RoutedPool::select_replica().
Sourcepub fn with<Q: Into<CteQuery>>(self, name: &'static str, query: Q) -> Self
pub fn with<Q: Into<CteQuery>>(self, name: &'static str, query: Q) -> Self
Adds a non-recursive common table expression (CTE).
query can be any SelectQuery; it is compiled and emitted as
WITH <name> AS (...).
Sourcepub fn with_recursive<A: Into<CteQuery>, R: Into<CteQuery>>(
self,
name: &'static str,
anchor: A,
recursive: R,
) -> Self
pub fn with_recursive<A: Into<CteQuery>, R: Into<CteQuery>>( self, name: &'static str, anchor: A, recursive: R, ) -> Self
Adds a recursive common table expression (CTE).
The body is (anchor) UNION ALL (recursive), with placeholders
renumbered across the union. The CTE is emitted as
WITH RECURSIVE <name> AS (...).
Sourcepub fn inner_join<J: Model>(
self,
on: impl Into<JoinOn>,
) -> SelectQuery<'db, M, Join2<M, J>, I>
pub fn inner_join<J: Model>( self, on: impl Into<JoinOn>, ) -> SelectQuery<'db, M, Join2<M, J>, I>
Adds an inner join to another model.
Sourcepub fn left_join<J: Model>(
self,
on: impl Into<JoinOn>,
) -> SelectQuery<'db, M, LeftJoin2<M, J>, I>
pub fn left_join<J: Model>( self, on: impl Into<JoinOn>, ) -> SelectQuery<'db, M, LeftJoin2<M, J>, I>
Adds a left join to another model.
Sourcepub fn right_join<J: Model>(
self,
on: impl Into<JoinOn>,
) -> SelectQuery<'db, M, Join2<Maybe<M>, J>, I>
pub fn right_join<J: Model>( self, on: impl Into<JoinOn>, ) -> SelectQuery<'db, M, Join2<Maybe<M>, J>, I>
Adds a right join to another model.
Sourcepub fn full_join<J: Model>(
self,
on: impl Into<JoinOn>,
) -> SelectQuery<'db, M, Join2<Maybe<M>, Maybe<J>>, I>
pub fn full_join<J: Model>( self, on: impl Into<JoinOn>, ) -> SelectQuery<'db, M, Join2<Maybe<M>, Maybe<J>>, I>
Adds a full join to another model.
Sourcepub fn inner_join_aliased<J: Model>(
self,
alias: &'static str,
on: impl Into<JoinOn>,
) -> SelectQuery<'db, M, Join2<M, J>, I>
pub fn inner_join_aliased<J: Model>( self, alias: &'static str, on: impl Into<JoinOn>, ) -> SelectQuery<'db, M, Join2<M, J>, I>
Adds an aliased inner join to another model.
Use Column::aliased in the ON condition so the right-hand side is
qualified by the alias. This is the fully-typed way to write self-joins:
User::query().inner_join_aliased::<User>("u2", User::id.on(User::manager_id.aliased("u2")))Sourcepub fn left_join_aliased<J: Model>(
self,
alias: &'static str,
on: impl Into<JoinOn>,
) -> SelectQuery<'db, M, LeftJoin2<M, J>, I>
pub fn left_join_aliased<J: Model>( self, alias: &'static str, on: impl Into<JoinOn>, ) -> SelectQuery<'db, M, LeftJoin2<M, J>, I>
Adds an aliased left join to another model.
Sourcepub fn right_join_aliased<J: Model>(
self,
alias: &'static str,
on: impl Into<JoinOn>,
) -> SelectQuery<'db, M, Join2<Maybe<M>, J>, I>
pub fn right_join_aliased<J: Model>( self, alias: &'static str, on: impl Into<JoinOn>, ) -> SelectQuery<'db, M, Join2<Maybe<M>, J>, I>
Adds an aliased right join to another model.
Sourcepub fn full_join_aliased<J: Model>(
self,
alias: &'static str,
on: impl Into<JoinOn>,
) -> SelectQuery<'db, M, Join2<Maybe<M>, Maybe<J>>, I>
pub fn full_join_aliased<J: Model>( self, alias: &'static str, on: impl Into<JoinOn>, ) -> SelectQuery<'db, M, Join2<Maybe<M>, Maybe<J>>, I>
Adds an aliased full join to another model.
Sourcepub fn with_deleted(self) -> Self
pub fn with_deleted(self) -> Self
Includes soft-deleted rows in the query results (disables default WHERE deleted_at IS NULL).
Sourcepub fn only_deleted(self) -> Self
pub fn only_deleted(self) -> Self
Queries only soft-deleted rows (WHERE deleted_at IS NOT NULL).
Sourcepub fn aggregate<R, A>(self, set: A) -> AggregateQuery<'db, M, R>where
R: RowDecode,
A: AggregateSet<M, R>,
pub fn aggregate<R, A>(self, set: A) -> AggregateQuery<'db, M, R>where
R: RowDecode,
A: AggregateSet<M, R>,
Switches the query to return aggregate results rather than rows.
The output type is a tuple, e.g. (Option<i64>, i64) for
aggregate((User::age.sum(), User::id.count())).
Sourcepub fn group_by<G: GroupBy<M>>(self, g: G) -> GroupedQuery<'db, M, Out, I>
pub fn group_by<G: GroupBy<M>>(self, g: G) -> GroupedQuery<'db, M, Out, I>
Groups the query by one or more columns.
Returns a GroupedQuery that supports having and aggregate.
Sourcepub fn include<J: IncludeSet<M>>(
self,
include: J,
) -> SelectQuery<'db, M, Out, J>
pub fn include<J: IncludeSet<M>>( self, include: J, ) -> SelectQuery<'db, M, Out, J>
Includes a related model, loaded in a second batched query.
Sourcepub fn columns<P: Projection<M>>(self, p: P) -> SelectQuery<'db, M, P::Output>
pub fn columns<P: Projection<M>>(self, p: P) -> SelectQuery<'db, M, P::Output>
Restricts the selected columns and changes the output type.
Sourcepub fn to_sql(&self) -> Result<CompiledSql, Error>
pub fn to_sql(&self) -> Result<CompiledSql, Error>
Compiles the query to SQL and binds.
§Errors
Returns Error::Message if the query uses a RIGHT JOIN or
FULL OUTER JOIN that the target dialect does not support.
Sourcepub fn union<M2, I2>(
self,
other: SelectQuery<'db, M2, Out, I2>,
) -> SetOpQuery<'db, Out>where
M2: Model,
pub fn union<M2, I2>(
self,
other: SelectQuery<'db, M2, Out, I2>,
) -> SetOpQuery<'db, Out>where
M2: Model,
Combines this query with another using UNION.
The output shape of both sides must match exactly; this is enforced at
compile time by the shared Out type parameter.
Sourcepub fn union_all<M2, I2>(
self,
other: SelectQuery<'db, M2, Out, I2>,
) -> SetOpQuery<'db, Out>where
M2: Model,
pub fn union_all<M2, I2>(
self,
other: SelectQuery<'db, M2, Out, I2>,
) -> SetOpQuery<'db, Out>where
M2: Model,
Combines this query with another using UNION ALL.
Sourcepub fn intersect<M2, I2>(
self,
other: SelectQuery<'db, M2, Out, I2>,
) -> SetOpQuery<'db, Out>where
M2: Model,
pub fn intersect<M2, I2>(
self,
other: SelectQuery<'db, M2, Out, I2>,
) -> SetOpQuery<'db, Out>where
M2: Model,
Combines this query with another using INTERSECT.
Sourcepub fn except<M2, I2>(
self,
other: SelectQuery<'db, M2, Out, I2>,
) -> SetOpQuery<'db, Out>where
M2: Model,
pub fn except<M2, I2>(
self,
other: SelectQuery<'db, M2, Out, I2>,
) -> SetOpQuery<'db, Out>where
M2: Model,
Combines this query with another using EXCEPT.
Sourcepub async fn count(self) -> Result<i64, Error>
pub async fn count(self) -> Result<i64, Error>
Returns the number of rows the query would return.
ORDER BY, LIMIT and OFFSET are ignored for the count: counting the
matching rows is independent of ordering or pagination.
§Errors
Returns Error::Sqlx for database errors.
Sourcepub async fn exists(self) -> Result<bool, Error>
pub async fn exists(self) -> Result<bool, Error>
Whether any row matches.
Compiles to SELECT 1 ... LIMIT 1 rather than counting: the database
can stop at the first match, which on a large table is the difference
between an index probe and a full scan.
§Errors
Returns Error::Sqlx for database errors.
Source§impl<'db, M, Out> SelectQuery<'db, M, Out, ()>where
M: Model,
impl<'db, M, Out> SelectQuery<'db, M, Out, ()>where
M: Model,
Sourcepub fn prepare(self) -> Result<PreparedSelect<'db, M, Out>, Error>
pub fn prepare(self) -> Result<PreparedSelect<'db, M, Out>, Error>
Prepares a reusable compiled statement.
The SQL is compiled once; bind values can be swapped with
PreparedSelect::bind and the statement can be executed repeatedly
without rebuilding the query string.
Sourcepub async fn fetch_all(self) -> Result<Vec<Out>, Error>
pub async fn fetch_all(self) -> Result<Vec<Out>, Error>
Executes the query and returns all matching rows.
Only available when the query has no .include(...): fetching all rows
without loading declared includes would silently return the wrong data.
Use exec for include-aware execution.
§Errors
Returns Error::Sqlx for database errors.
Sourcepub fn stream(self) -> Result<RowStream<'db, Out>, Error>
pub fn stream(self) -> Result<RowStream<'db, Out>, Error>
Streams matching rows instead of collecting them.
Only available when the query has no .include(...): a stream without
loaded includes would silently return the wrong data. Use
exec for include-aware execution.
Rows are decoded one at a time as the stream is polled. The underlying
fetch is currently buffered by both executors (see
Executor::stream_raw), so this bounds decode cost rather than peak
memory; the buffering lives behind the executor so it can be replaced
with a true cursor without touching this API.
Sourcepub fn stream_unbuffered(self) -> Result<RowStream<'db, Out>, Error>
pub fn stream_unbuffered(self) -> Result<RowStream<'db, Out>, Error>
Streams matching rows without buffering the whole result set.
Only available when the query has no .include(...): a stream without
loaded includes would silently return the wrong data. Use
exec for include-aware execution.
For sqlx backends the rows are produced incrementally by the driver,
which keeps peak memory proportional to the number of in-flight rows
rather than the total result size. The postgres-tokio-postgres backend
uses an unbuffered server-side portal.
Sourcepub async fn page(self, size: u64) -> Result<Page<Out>, Error>
pub async fn page(self, size: u64) -> Result<Page<Out>, Error>
Fetches one page, reporting whether another page follows.
Fetches size + 1 rows and discards the extra, so has_next is exact
rather than inferred from a full page. The model’s primary key is
appended to ORDER BY so the total order is deterministic — without a
unique tiebreaker, rows sharing an ordering value can repeat across
pages or be skipped entirely.
§Errors
Returns Error::Sqlx for database errors.
Sourcepub async fn fetch_optional(self) -> Result<Option<Out>, Error>
pub async fn fetch_optional(self) -> Result<Option<Out>, Error>
Executes the query and returns the first row, if any.
Only available when the query has no .include(...): fetching a single
row without loading declared includes would silently return the wrong
data. Use exec_optional for include-aware
execution.
§Errors
Returns Error::Sqlx for database errors.
Source§impl<'db, M, I> SelectQuery<'db, M, M, I>where
M: Model,
I: IncludeSet<M>,
impl<'db, M, I> SelectQuery<'db, M, M, I>where
M: Model,
I: IncludeSet<M>,
Sourcepub async fn exec(self) -> Result<Vec<M>, Error>
pub async fn exec(self) -> Result<Vec<M>, Error>
Executes the query, then loads any requested includes.
§Errors
Returns Error::Sqlx for database errors.
Sourcepub async fn exec_optional(self) -> Result<Option<M>, Error>
pub async fn exec_optional(self) -> Result<Option<M>, Error>
Executes the query, loads any requested includes, and returns the first row if one matches.
A single-row fetch is never a full-table scan, so the full-table include fast path is disabled for this call.
§Errors
Returns Error::Sqlx for database errors.
Trait Implementations§
Source§impl<'db, M, T, I> From<SelectQuery<'db, M, (T,), I>> for Subquery<T>where
M: Model,
impl<'db, M, T, I> From<SelectQuery<'db, M, (T,), I>> for Subquery<T>where
M: Model,
Source§fn from(query: SelectQuery<'db, M, (T,), I>) -> Self
fn from(query: SelectQuery<'db, M, (T,), I>) -> Self
Source§impl<'db, M, Out, I> From<SelectQuery<'db, M, Out, I>> for ExistsSubquerywhere
M: Model,
impl<'db, M, Out, I> From<SelectQuery<'db, M, Out, I>> for ExistsSubquerywhere
M: Model,
Source§fn from(query: SelectQuery<'db, M, Out, I>) -> Self
fn from(query: SelectQuery<'db, M, Out, I>) -> Self
Source§impl<'db, M, Out, I> From<SelectQuery<'db, M, Out, I>> for CteQuerywhere
M: Model,
impl<'db, M, Out, I> From<SelectQuery<'db, M, Out, I>> for CteQuerywhere
M: Model,
Source§fn from(query: SelectQuery<'db, M, Out, I>) -> Self
fn from(query: SelectQuery<'db, M, Out, I>) -> Self
Auto Trait Implementations§
impl<'db, M, Out = M, I = ()> !RefUnwindSafe for SelectQuery<'db, M, Out, I>
impl<'db, M, Out = M, I = ()> !UnwindSafe for SelectQuery<'db, M, Out, I>
impl<'db, M, Out, I> Freeze for SelectQuery<'db, M, Out, I>
impl<'db, M, Out, I> Send for SelectQuery<'db, M, Out, I>
impl<'db, M, Out, I> Sync for SelectQuery<'db, M, Out, I>
impl<'db, M, Out, I> Unpin for SelectQuery<'db, M, Out, I>
impl<'db, M, Out, I> UnsafeUnpin for SelectQuery<'db, M, Out, I>where
Filter<M>: UnsafeUnpin,
Vec<OrderBy<M>>: UnsafeUnpin,
I: UnsafeUnpin,
PhantomData<fn() -> Out>: UnsafeUnpin,
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