pub struct Select<M> { /* private fields */ }Expand description
A SELECT query over model M, created with Model::query or Model::filter.
Builders are cheap, cloneable values: nothing touches the database until
one of the async terminal methods (all, first, count, …) is awaited.
Implementations§
Source§impl<M> Select<M>where
M: Model,
impl<M> Select<M>where
M: Model,
Source§impl<M> Select<M>where
M: Model,
impl<M> Select<M>where
M: Model,
Sourcepub fn filter(self, expr: Expr<M>) -> Select<M>
pub fn filter(self, expr: Expr<M>) -> Select<M>
Add a WHERE condition. Multiple calls are combined with AND.
Sourcepub fn all_tenants(self) -> Select<M>
pub fn all_tenants(self) -> Select<M>
Query every tenant’s rows of a #[rok(tenant)] model, ignoring the
current tenant scope (for admin tools and background jobs).
Sourcepub fn on_primary(self) -> Select<M>
pub fn on_primary(self) -> Select<M>
Run on the primary even when read replicas are configured, e.g. to read your own writes without replication lag.
Sourcepub fn scope(self, scope: impl FnOnce(Select<M>) -> Select<M>) -> Select<M>
pub fn scope(self, scope: impl FnOnce(Select<M>) -> Select<M>) -> Select<M>
Apply a reusable query fragment (“named scope”):
fn active(q: Select<User>) -> Select<User> { q.filter(User::ACTIVE.eq(true)) }
fn newest(q: Select<User>) -> Select<User> { q.order_by(User::ID.desc()) }
User::query().scope(active).scope(newest).limit(10)Sourcepub fn unscoped(self) -> Select<M>
pub fn unscoped(self) -> Select<M>
Drop the model’s default scope (#[rok(default_scope = …)]) for this
query. Soft-delete filtering is controlled separately with
with_trashed.
Sourcepub fn with_trashed(self) -> Select<M>
pub fn with_trashed(self) -> Select<M>
Include soft-deleted rows (models with #[rok(soft_delete)] exclude
them by default). No effect on other models.
Sourcepub fn only_trashed(self) -> Select<M>
pub fn only_trashed(self) -> Select<M>
Only soft-deleted rows. No effect on models without soft deletes.
Sourcepub fn filter_if(
self,
condition: bool,
expr: impl FnOnce() -> Expr<M>,
) -> Select<M>
pub fn filter_if( self, condition: bool, expr: impl FnOnce() -> Expr<M>, ) -> Select<M>
Add a condition only when condition is true.
Sourcepub fn filter_opt<T>(
self,
value: Option<T>,
expr: impl FnOnce(T) -> Expr<M>,
) -> Select<M>
pub fn filter_opt<T>( self, value: Option<T>, expr: impl FnOnce(T) -> Expr<M>, ) -> Select<M>
Add a condition built from an optional value, e.g. a search parameter.
User::query().filter_opt(params.role, |r| User::ROLE.eq(r))Sourcepub fn order_by(self, order: impl Into<Order<M>>) -> Select<M>
pub fn order_by(self, order: impl Into<Order<M>>) -> Select<M>
Append an ORDER BY term. Pass a column for ascending order, or
column.desc().
Sourcepub fn group_by(self, column: Column<M>) -> Select<M>
pub fn group_by(self, column: Column<M>) -> Select<M>
Append a GROUP BY column; combine with select.
Sourcepub fn having(self, expr: Expr<M>) -> Select<M>
pub fn having(self, expr: Expr<M>) -> Select<M>
Add a HAVING condition, typically on an aggregate
(User::AGE.avg().gt(30)). Multiple calls are combined with AND.
Sourcepub fn for_update(self) -> Select<M>
pub fn for_update(self) -> Select<M>
Lock selected rows with FOR UPDATE (use inside a transaction).
Lock selected rows with FOR SHARE (use inside a transaction).
Sourcepub fn select(self, projections: impl IntoProjections<M>) -> Projected<M>
pub fn select(self, projections: impl IntoProjections<M>) -> Projected<M>
Select specific columns or aggregates instead of whole models.
let emails: Vec<(i64, String)> = User::query()
.select((User::ID, User::EMAIL))
.fetch_all(&db)
.await?;Sourcepub fn memoize(self, ttl: Duration) -> Memoized<M>
pub fn memoize(self, ttl: Duration) -> Memoized<M>
Cache this query’s results for ttl in the pool’s
QueryCache.
Writes made through rok-db invalidate the cached results of the
table. When the executor has no cache (it wasn’t enabled with
DbBuilder::query_cache, or a plain
sqlx pool or connection is used) the query simply runs every time.
Sourcepub async fn all<'e, E>(self, executor: E) -> Result<Vec<M>, Error>where
E: Executor<'e>,
pub async fn all<'e, E>(self, executor: E) -> Result<Vec<M>, Error>where
E: Executor<'e>,
Fetch every matching row.
Sourcepub async fn first<'e, E>(self, executor: E) -> Result<Option<M>, Error>where
E: Executor<'e>,
pub async fn first<'e, E>(self, executor: E) -> Result<Option<M>, Error>where
E: Executor<'e>,
Fetch the first matching row, or None.
Sourcepub async fn one<'e, E>(self, executor: E) -> Result<M, Error>where
E: Executor<'e>,
pub async fn one<'e, E>(self, executor: E) -> Result<M, Error>where
E: Executor<'e>,
Fetch the first matching row, failing with Error::NotFound.
Sourcepub fn stream<'e, E>(
self,
executor: E,
) -> Pin<Box<dyn Stream<Item = Result<M, Error>> + Send + 'e>>where
E: Executor<'e> + 'e,
pub fn stream<'e, E>(
self,
executor: E,
) -> Pin<Box<dyn Stream<Item = Result<M, Error>> + Send + 'e>>where
E: Executor<'e> + 'e,
Stream matching rows one at a time instead of loading them all into
memory. Consume it with futures::TryStreamExt (re-exported in the
rok-db prelude):
let mut users = User::query().stream(&db);
while let Some(user) = users.try_next().await? {
// …
}Sourcepub async fn count<'e, E>(self, executor: E) -> Result<i64, Error>where
E: Executor<'e>,
pub async fn count<'e, E>(self, executor: E) -> Result<i64, Error>where
E: Executor<'e>,
Count the matching rows (ignores ordering, limit and offset).
Sourcepub async fn exists<'e, E>(self, executor: E) -> Result<bool, Error>where
E: Executor<'e>,
pub async fn exists<'e, E>(self, executor: E) -> Result<bool, Error>where
E: Executor<'e>,
true if at least one row matches.
Sourcepub async fn sum<'e, E>(
self,
executor: E,
column: Column<M>,
) -> Result<Option<i64>, Error>where
E: Executor<'e>,
pub async fn sum<'e, E>(
self,
executor: E,
column: Column<M>,
) -> Result<Option<i64>, Error>where
E: Executor<'e>,
SUM(column) over the matching rows as BIGINT (None when no
rows match). Use select with
Projection::cast for other result types.
Sourcepub async fn avg<'e, E>(
self,
executor: E,
column: Column<M>,
) -> Result<Option<f64>, Error>where
E: Executor<'e>,
pub async fn avg<'e, E>(
self,
executor: E,
column: Column<M>,
) -> Result<Option<f64>, Error>where
E: Executor<'e>,
AVG(column) over the matching rows as DOUBLE PRECISION.
Sourcepub async fn min<'e, T, E>(
self,
executor: E,
column: Column<M>,
) -> Result<Option<T>, Error>
pub async fn min<'e, T, E>( self, executor: E, column: Column<M>, ) -> Result<Option<T>, Error>
MIN(column) over the matching rows.
Sourcepub async fn max<'e, T, E>(
self,
executor: E,
column: Column<M>,
) -> Result<Option<T>, Error>
pub async fn max<'e, T, E>( self, executor: E, column: Column<M>, ) -> Result<Option<T>, Error>
MAX(column) over the matching rows.
Sourcepub async fn paginate<'e, E>(
self,
executor: E,
page: u64,
per_page: u64,
) -> Result<Page<M>, Error>where
E: Executor<'e>,
pub async fn paginate<'e, E>(
self,
executor: E,
page: u64,
per_page: u64,
) -> Result<Page<M>, Error>where
E: Executor<'e>,
Fetch one page of results together with the total number of matches,
in a single round trip. page is 1-based.
Sourcepub async fn delete<'e, E>(self, executor: E) -> Result<u64, Error>where
E: Executor<'e>,
pub async fn delete<'e, E>(self, executor: E) -> Result<u64, Error>where
E: Executor<'e>,
Delete every matching row and return how many were deleted.
For models with soft deletes this sets deleted_at = now() instead;
use force_delete to remove rows for good.
Sourcepub fn delete_sql(&self) -> Sql
pub fn delete_sql(&self) -> Sql
Render the statement delete would run.
Sourcepub async fn force_delete<'e, E>(self, executor: E) -> Result<u64, Error>where
E: Executor<'e>,
pub async fn force_delete<'e, E>(self, executor: E) -> Result<u64, Error>where
E: Executor<'e>,
DELETE every matching row, even for models with soft deletes.
Soft-deleted rows are only matched with
with_trashed or only_trashed.
Sourcepub async fn restore<'e, E>(self, executor: E) -> Result<u64, Error>where
E: Executor<'e>,
pub async fn restore<'e, E>(self, executor: E) -> Result<u64, Error>where
E: Executor<'e>,
Restore every matching soft-deleted row (deleted_at = NULL) and
return how many were restored.
Sourcepub async fn cursor_paginate<'e, E>(
self,
executor: E,
after: Option<&Cursor>,
limit: u64,
) -> Result<CursorPage<M>, Error>where
E: Executor<'e>,
pub async fn cursor_paginate<'e, E>(
self,
executor: E,
after: Option<&Cursor>,
limit: u64,
) -> Result<CursorPage<M>, Error>where
E: Executor<'e>,
Keyset (“cursor”) pagination: fetch up to limit rows after
cursor, following the query’s ORDER BY (the primary key is added
as a tiebreaker). Unlike paginate, the cost
doesn’t grow with the page number and rows aren’t skipped or repeated
when data changes between requests.
Sort keys (columns or expressions) must be NOT NULL; expression
orders and joined queries paginate over a wrapped subquery. Pass
None for the first page,
then page.next for the following ones:
let page = Post::order_by(Post::CREATED_AT.desc())
.cursor_paginate(&db, None, 20)
.await?;
let token = page.next.map(|c| c.to_string()); // hand to the client
let cursor: Cursor = token.unwrap().parse()?;
let page2 = Post::order_by(Post::CREATED_AT.desc())
.cursor_paginate(&db, Some(&cursor), 20)
.await?;Trait Implementations§
Auto Trait Implementations§
impl<M> !RefUnwindSafe for Select<M>
impl<M> !UnwindSafe for Select<M>
impl<M> Freeze for Select<M>
impl<M> Send for Select<M>
impl<M> Sync for Select<M>
impl<M> Unpin for Select<M>
impl<M> UnsafeUnpin for Select<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,
impl<M> InScope<(M, ()), Here> for M
impl<M, Rest, N> InScope<(M, (Rest, N)), Last> for N
impl<X, M, Rest, N, I> InScope<(M, (Rest, N)), There<I>> for X
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