Skip to main content

Select

Struct Select 

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

Source

pub fn join<R, I>(self, join: R) -> Joined<M, ((), <R as IntoJoin>::To)>
where R: IntoJoin, <R as IntoJoin>::From: InScope<(M, ()), I>,

INNER JOIN a related model (see join).

Source

pub fn left_join<R, I>(self, join: R) -> Joined<M, ((), <R as IntoJoin>::To)>
where R: IntoJoin, <R as IntoJoin>::From: InScope<(M, ()), I>,

LEFT JOIN a related model: root rows without a match are kept, with NULLs for the joined model’s columns.

Source§

impl<M> Select<M>
where M: Model,

Source

pub fn new() -> Select<M>

A SELECT over every row of M’s table.

Source

pub fn filter(self, expr: Expr<M>) -> Select<M>

Add a WHERE condition. Multiple calls are combined with AND.

Source

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

Source

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.

Source

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

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.

Source

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.

Source

pub fn only_trashed(self) -> Select<M>

Only soft-deleted rows. No effect on models without soft deletes.

Source

pub fn filter_if( self, condition: bool, expr: impl FnOnce() -> Expr<M>, ) -> Select<M>

Add a condition only when condition is true.

Source

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

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

Source

pub fn group_by(self, column: Column<M>) -> Select<M>

Append a GROUP BY column; combine with select.

Source

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.

Source

pub fn limit(self, limit: u64) -> Select<M>

Limit the number of returned rows.

Source

pub fn offset(self, offset: u64) -> Select<M>

Skip the first offset rows.

Source

pub fn for_update(self) -> Select<M>

Lock selected rows with FOR UPDATE (use inside a transaction).

Source

pub fn for_share(self) -> Select<M>

Lock selected rows with FOR SHARE (use inside a transaction).

Source

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?;
Source

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.

Source

pub fn update(self) -> Update<M>

Turn this query into a bulk UPDATE with the same filters.

Source

pub fn to_sql(&self) -> Sql

Render the SELECT statement.

Source

pub async fn all<'e, E>(self, executor: E) -> Result<Vec<M>, Error>
where E: Executor<'e>,

Fetch every matching row.

Source

pub async fn first<'e, E>(self, executor: E) -> Result<Option<M>, Error>
where E: Executor<'e>,

Fetch the first matching row, or None.

Source

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.

Source

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? {
    // …
}
Source

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

Source

pub async fn exists<'e, E>(self, executor: E) -> Result<bool, Error>
where E: Executor<'e>,

true if at least one row matches.

Source

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.

Source

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.

Source

pub async fn min<'e, T, E>( self, executor: E, column: Column<M>, ) -> Result<Option<T>, Error>
where T: Type<Postgres> + for<'r> Decode<'r, Postgres> + Send + Unpin, E: Executor<'e>,

MIN(column) over the matching rows.

Source

pub async fn max<'e, T, E>( self, executor: E, column: Column<M>, ) -> Result<Option<T>, Error>
where T: Type<Postgres> + for<'r> Decode<'r, Postgres> + Send + Unpin, E: Executor<'e>,

MAX(column) over the matching rows.

Source

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.

Source

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.

Source

pub fn delete_sql(&self) -> Sql

Render the statement delete would run.

Source

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.

Source

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.

Source

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§

Source§

impl<M> Clone for Select<M>

Source§

fn clone(&self) -> Select<M>

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> Debug for Select<M>
where M: Model,

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl<M> Default for Select<M>
where M: Model,

Source§

fn default() -> Select<M>

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

Auto Trait Implementations§

§

impl<M> !RefUnwindSafe for Select<M>

§

impl<M> !UnwindSafe for Select<M>

§

impl<M> Freeze for Select<M>
where Vec<Order<M>>: Freeze, PhantomData<fn() -> M>: Freeze,

§

impl<M> Send for Select<M>
where Vec<Order<M>>: Send, PhantomData<fn() -> M>: Send,

§

impl<M> Sync for Select<M>
where Vec<Order<M>>: Sync, PhantomData<fn() -> M>: Sync,

§

impl<M> Unpin for Select<M>
where Vec<Order<M>>: Unpin, PhantomData<fn() -> M>: Unpin,

§

impl<M> UnsafeUnpin for Select<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> FromRef<T> for T
where T: Clone,

Source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
Source§

impl<M> InScope<(M, ()), Here> for M

Source§

impl<M, Rest, N> InScope<(M, (Rest, N)), Last> for N

Source§

impl<X, M, Rest, N, I> InScope<(M, (Rest, N)), There<I>> for X
where X: InScope<(M, Rest), I>,

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