Skip to main content

SelectQuery

Struct SelectQuery 

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

Source

pub fn new(exec: &'db dyn Executor) -> Self

Creates a new query.

Accepts anything that can execute SQL, so the same query runs against a pool or inside a transaction. &Pool and &Tx both coerce here.

Source§

impl<'db, M, Out, I> SelectQuery<'db, M, Out, I>
where M: Model,

Source

pub fn filter(self, f: Filter<M>) -> Self

Adds a filter (AND).

Source

pub fn or_filter(self, f: Filter<M>) -> Self

Adds a filter (OR).

Source

pub fn filter_if(self, f: Option<Filter<M>>) -> Self

Adds a filter (AND) only if f is Some.

Source

pub fn or_filter_if(self, f: Option<Filter<M>>) -> Self

Adds a filter (OR) only if f is Some.

Source

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.

Source

pub fn order_by(self, o: OrderBy<M>) -> Self

Adds an ordering.

Source

pub fn order_by_if(self, o: Option<OrderBy<M>>) -> Self

Adds an ordering only if o is Some.

Source

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

Sets the limit.

Source

pub fn limit_if(self, n: Option<u64>) -> Self

Sets the limit only if n is Some.

Source

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

Sets the offset.

Source

pub fn offset_if(self, n: Option<u64>) -> Self

Sets the offset only if n is Some.

Source

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

Source

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

Source

pub fn distinct(self) -> Self

Makes the query SELECT DISTINCT.

Source

pub 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

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.

Source

pub 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

Does nothing. See SelectQuery::cache.

Source

pub 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

Does nothing. See SelectQuery::cache.

Source

pub fn use_primary(self) -> Self

👎Deprecated since 1.5.2:

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.

Source

pub fn use_replica(self) -> Self

👎Deprecated since 1.5.2:

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().

Source

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 (...).

Source

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 (...).

Source

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.

Source

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.

Source

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.

Source

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.

Source

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

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.

Source

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.

Source

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.

Source

pub fn with_deleted(self) -> Self

Includes soft-deleted rows in the query results (disables default WHERE deleted_at IS NULL).

Source

pub fn only_deleted(self) -> Self

Queries only soft-deleted rows (WHERE deleted_at IS NOT NULL).

Source

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())).

Source

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.

Source

pub fn include<J: IncludeSet<M>>( self, include: J, ) -> SelectQuery<'db, M, Out, J>

Includes a related model, loaded in a second batched query.

Source

pub fn columns<P: Projection<M>>(self, p: P) -> SelectQuery<'db, M, P::Output>

Restricts the selected columns and changes the output type.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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,

Source

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.

Source

pub async fn fetch_all(self) -> Result<Vec<Out>, Error>
where Out: Send + Unpin + RowDecode,

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.

Source

pub async fn all(self) -> Result<Vec<Out>, Error>
where Out: Send + Unpin + RowDecode,

Alias for fetch_all.

Source

pub fn stream(self) -> Result<RowStream<'db, Out>, Error>
where Out: Send + Unpin + RowDecode,

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.

Source

pub fn stream_unbuffered(self) -> Result<RowStream<'db, Out>, Error>
where Out: Send + Unpin + RowDecode,

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.

Source

pub async fn page(self, size: u64) -> Result<Page<Out>, Error>
where Out: Send + Unpin + RowDecode,

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.

Source

pub async fn fetch_optional(self) -> Result<Option<Out>, Error>
where Out: Send + Unpin + RowDecode,

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

pub async fn fetch_one(self) -> Result<Out, Error>
where Out: Send + Unpin + RowDecode,

Executes the query and returns exactly one row.

Only available when the query has no .include(...). Use exec_one when includes are requested.

§Errors

Returns Error::Sqlx for database errors, including the case where no row matches.

Source§

impl<'db, M, I> SelectQuery<'db, M, M, I>
where M: Model, I: IncludeSet<M>,

Source

pub async fn exec(self) -> Result<Vec<M>, Error>

Executes the query, then loads any requested includes.

§Errors

Returns Error::Sqlx for database errors.

Source

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.

Source

pub async fn exec_one(self) -> Result<M, Error>

Executes the query, loads any requested includes, and returns exactly one row.

§Errors

Returns Error::Sqlx for database errors, including the case where no row matches.

Trait Implementations§

Source§

impl<'db, M: Clone + Model, Out: Clone, I: Clone> Clone for SelectQuery<'db, M, Out, I>

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

Converts to this type from the input type.
Source§

impl<'db, M, Out, I> From<SelectQuery<'db, M, Out, I>> for ExistsSubquery
where M: Model,

Source§

fn from(query: SelectQuery<'db, M, Out, I>) -> Self

Converts to this type from the input type.
Source§

impl<'db, M, Out, I> From<SelectQuery<'db, M, Out, I>> for CteQuery
where M: Model,

Source§

fn from(query: SelectQuery<'db, M, Out, I>) -> Self

Converts to this type from the input type.

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>
where Filter<M>: Freeze, Vec<OrderBy<M>>: Freeze, I: Freeze, PhantomData<fn() -> Out>: Freeze,

§

impl<'db, M, Out, I> Send for SelectQuery<'db, M, Out, I>
where Filter<M>: Send, Vec<OrderBy<M>>: Send, I: Send, PhantomData<fn() -> Out>: Send,

§

impl<'db, M, Out, I> Sync for SelectQuery<'db, M, Out, I>
where Filter<M>: Sync, Vec<OrderBy<M>>: Sync, I: Sync, PhantomData<fn() -> Out>: Sync,

§

impl<'db, M, Out, I> Unpin for SelectQuery<'db, M, Out, I>
where Filter<M>: Unpin, Vec<OrderBy<M>>: Unpin, I: Unpin, PhantomData<fn() -> Out>: Unpin,

§

impl<'db, M, Out, I> UnsafeUnpin for SelectQuery<'db, M, Out, I>

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