Skip to main content

Query

Struct Query 

Source
pub struct Query<M> { /* private fields */ }
Expand description

A query on a model’s table, built with chained filters.

let products = Product::query()
    .where_eq("category", "coffee")
    .where_op("price", "<", 25_000)
    .order_by("name")
    .paginate(&db, page, 20)
    .await?;

Column names are checked against the model; an unknown column or operator makes the query return an error instead of running.

Implementations§

Source§

impl<M: Model> Query<M>

Source

pub fn where_eq(self, column: &str, value: impl ToDbValue) -> Self

Filters on column = value.

Source

pub fn where_(self, condition: Condition<M>) -> Self

Filters on a typed Condition made by a Col, like Product::PRICE.lt(20_000).

Source

pub fn order_by_json(self, path: JsonPath<M>) -> Self

Sorts by a key of a JSON column, ascending, like Party::EXTRA.json("segment").

Source

pub fn order_by_json_desc(self, path: JsonPath<M>) -> Self

Sorts by a key of a JSON column, descending.

Source

pub async fn with_custom_fields(self, db: &Db) -> Result<Self>

Checks the JSON keys of the query’s conditions and ordering against the active custom field definitions of the model (its table name), and compares numbers and booleans as such on PostgreSQL. A key without a definition makes the query return an error. A key whose definition is sensitive (its values are sealed) cannot be filtered or sorted on: this returns DbError::sealed_custom_field (400 in a response), whatever the stored rows hold. The definitions are cached (CustomField::for_model), so calling this on every query is cheap.

Source

pub fn where_op(self, column: &str, op: &str, value: impl ToDbValue) -> Self

Filters with a comparison: =, !=, <>, <, <=, >, >=, like, not like. like ignores ASCII case on both databases (ILIKE on PostgreSQL, as SQLite’s LIKE already does).

Source

pub fn where_like(self, column: &str, pattern: impl ToDbValue) -> Self

Filters on column LIKE pattern, ignoring ASCII case (% and _ are wildcards).

Source

pub fn where_null(self, column: &str) -> Self

Filters on column IS NULL.

Source

pub fn where_not_null(self, column: &str) -> Self

Filters on column IS NOT NULL.

Source

pub fn where_in<V: ToDbValue>( self, column: &str, values: impl IntoIterator<Item = V>, ) -> Self

Filters on column IN (…); an empty list matches no rows.

Source

pub fn where_not_in<V: ToDbValue>( self, column: &str, values: impl IntoIterator<Item = V>, ) -> Self

Filters on column NOT IN (…); an empty list matches every row.

Source

pub fn where_between( self, column: &str, low: impl ToDbValue, high: impl ToDbValue, ) -> Self

low <= column <= high.

Source

pub fn where_in_query<N: Model>( self, column: &str, sub: Query<N>, sub_column: &str, ) -> Self

Rows whose column is among sub_column’s values in another model’s query, e.g. products in active categories:

let products = Product::query()
    .where_in_query("category_id", Category::where_eq("active", true), "id")
    .get(&db)
    .await?;
Source

pub fn where_not_in_query<N: Model>( self, column: &str, sub: Query<N>, sub_column: &str, ) -> Self

Like where_in_query, keeping the rows whose column is not among the sub-query’s values.

Source

pub fn where_has<N: Model>(self, children: Query<N>, foreign_key: &str) -> Self

Rows that have at least one related row in children, joined by the children’s foreign_key column to this model’s id (EXISTS): products with a 5-star review.

let loved = Product::query()
    .where_has(Review::where_eq("stars", 5), "product_id")
    .get(&db)
    .await?;
let unreviewed = Product::query().where_doesnt_have(Review::query(), "product_id").count(&db).await?;
Source

pub fn where_doesnt_have<N: Model>( self, children: Query<N>, foreign_key: &str, ) -> Self

Rows without any related row in children (NOT EXISTS).

Source

pub fn where_any(self, group: impl FnOnce(Self) -> Self) -> Self

Any of the conditions group adds must hold (OR), in parentheses: .where_any(|q| q.where_eq("status", "new").where_op("total", ">", 100)).

Source

pub fn where_all(self, group: impl FnOnce(Self) -> Self) -> Self

All of the conditions group adds must hold, in parentheses; useful inside where_any: .where_any(|q| q.where_eq("a", 1).where_all(|q| …)).

Source

pub fn when(self, condition: bool, add: impl FnOnce(Self) -> Self) -> Self

Applies add only when condition holds, e.g. an optional search: .when(!q.is_empty(), |query| query.where_like("name", format!("%{q}%"))).

Source

pub fn search(self, words: &str) -> Self

The rows matching a full-text search, best matches first (as where_search then order_by_relevance); more order_by calls break ties. The model needs #[model(search = "…")] and its index: see renox::db::search. A text without any word changes nothing.

#[derive(Model, serde::Serialize, Default)]
#[model(table = "posts", search = "title, body", soft_deletes)]
struct Post {
    id: i64,
    title: String,
    body: String,
    author_id: i64,
    deleted_at: Option<DateTime>,
}

let page = Post::query()
    .where_eq("author_id", 7)
    .search(&q)
    .order_by_desc("id")
    .paginate(&db, 1, 20)
    .await?;

Keeps the rows matching a full-text search (every word, as a word or the start of one), without ordering them. User input is safe here: only its words reach the database, bound as a value.

Source

pub fn order_by_relevance(self, words: &str) -> Self

Sorts by how well rows match a full-text search, best first (rows that don’t match last); call order_by after it to break ties.

Source

pub fn order_by(self, column: impl IntoColumn<M>) -> Self

Sorts by column, ascending; call again to add tie-breakers.

Source

pub fn order_by_desc(self, column: impl IntoColumn<M>) -> Self

Sorts by column, descending; call again to add tie-breakers.

Source

pub fn latest(self) -> Self

Newest first, by created_at when the model has it, otherwise by id.

Source

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

At most limit rows (a limit past i64::MAX means no limit).

Source

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

Skips the first offset rows.

Source

pub fn where_raw<V: ToDbValue>( self, sql: &str, values: impl IntoIterator<Item = V>, ) -> Self

A condition in SQL, for what the builder doesn’t cover (dates, JSON, full-text search, …), with ? for each value. Column names are yours to quote; never build sql from user input.

let today = Order::query()
    .where_raw("DATE(created_at) = DATE(?)", [renox::db::now()])
    .order_by_raw("total DESC, id")
    .get(&db)
    .await?;
Source

pub fn order_by_raw(self, sql: &str) -> Self

An ORDER BY term in SQL, e.g. "total DESC, id" (no values; never from user input).

Source

pub fn group_by(self, column: &str) -> Self

Groups rows by column, for select_as and count: .group_by("user_id").select_as::<(i64, i64), _>(&db, "user_id, COUNT(*)").

Source

pub fn group_by_raw(self, sql: &str) -> Self

Groups rows by a SQL expression (written by the app, never from a request): .group_by_raw("CAST(\"price\" / 100 AS INTEGER)").

Source

pub fn having_raw<V: ToDbValue>( self, sql: &str, values: impl IntoIterator<Item = V>, ) -> Self

A condition on the groups, in SQL with ? for each value: .having_raw("COUNT(*) > ?", [2]).

Source

pub fn lock_for_update(self) -> Self

Locks the matching rows until the transaction ends (FOR UPDATE), e.g. to read a balance and write it back safely. Use it on &mut tx. PostgreSQL only: on SQLite a write transaction already holds the whole database, so start it with db.begin_immediate() instead.

Source

pub fn shared_lock(self) -> Self

Like lock_for_update, but others may still read-lock (FOR SHARE).

Source

pub fn none(self) -> Self

Matches no rows at all, e.g. a default scope when no tenant is set.

Source

pub fn with_trashed(self) -> Self

Include soft-deleted rows.

Source

pub fn only_trashed(self) -> Self

Only soft-deleted rows.

Source

pub fn to_sql(&self, dialect: Dialect) -> Result<(String, Vec<DbValue>)>

The SELECT this query runs and its values, e.g. to log or debug it.

Source

pub async fn select_as<'c, T: FromRow, E: Executor<'c>>( self, db: E, columns: &str, ) -> Result<Vec<T>>

Selects columns (SQL, e.g. "user_id, COUNT(*) AS orders") of the matching rows, with group_by/having_raw, read into a #[derive(FromRow)] struct or a tuple:

let big_spenders: Vec<(i64, i64)> = Order::where_eq("status", "paid")
    .group_by("user_id")
    .having_raw("SUM(total) > ?", [1_000_000])
    .order_by_raw("2 DESC")
    .select_as(&db, "user_id, CAST(SUM(total) AS BIGINT)")
    .await?;
Source

pub async fn sum<'c, T: Number, E: Executor<'c>>( self, db: E, column: &str, ) -> Result<T>

The sum of column, 0 without rows: sum::<i64>(…) for whole numbers (money in its smallest unit), sum::<Quantity<S>>(…) for a Quantity column, sum::<f64>(…) for measures.

Source

pub async fn avg<'c, E: Executor<'c>>( self, db: E, column: &str, ) -> Result<Option<f64>>

The average of column, or None without rows.

Source

pub async fn min<'c, T: FromDb, E: Executor<'c>>( self, db: E, column: &str, ) -> Result<Option<T>>
where Option<T>: FromDb,

The smallest value of column, or None without rows.

Source

pub async fn max<'c, T: FromDb, E: Executor<'c>>( self, db: E, column: &str, ) -> Result<Option<T>>
where Option<T>: FromDb,

The largest value of column, or None without rows.

Source

pub async fn pluck<'c, T: FromDb, E: Executor<'c>>( self, db: E, column: impl IntoColumn<M>, ) -> Result<Vec<T>>

One column of the matching rows, in the query’s order: Product::query().order_by("name").pluck::<String, _>(&db, "name").

Source

pub async fn update<'c, E: Executor<'c>>( self, db: E, values: &[(&str, &(dyn ToDbValue + Sync))], ) -> Result<u64>

Sets columns on every matching row (and updated_at when the model has it); returns how many changed.

Order::where_eq("status", "pending")
    .update(&db, &[("status", &"paid"), ("paid_at", &renox::db::now())])
    .await?;
Source

pub async fn increment<'c, E: Executor<'c>>( self, db: E, column: &str, by: i64, ) -> Result<u64>

Adds by to column on every matching row (negative to subtract), in the database, so concurrent changes aren’t lost: Product::where_eq("id", id).increment(&db, "stock", -1).

Source

pub async fn first_or_404<'c, E: Executor<'c>>(self, db: E) -> Result<M>

Like first, but no row becomes a 404 response.

Source

pub fn first_or_create<'a>( self, db: &'a Db, make: impl FnOnce() -> M + Send + 'a, ) -> impl Future<Output = Result<M>> + Send + 'a

The first matching row, or make() saved as a new one. If another request creates it at the same moment (a unique index stops the second insert), the row it created is returned.

Source

pub async fn chunk<F, Fut>(self, db: &Db, size: u64, each: F) -> Result<u64>
where F: FnMut(Vec<M>) -> Fut, Fut: Future<Output = Result>,

Runs each on the matching rows size at a time, in id order, so a large table never sits in memory at once. (The query’s own order and limit don’t apply.)

Source

pub async fn get<'c, E: Executor<'c>>(self, db: E) -> Result<Vec<M>>

Runs the query and returns every matching row.

Source

pub async fn first<'c, E: Executor<'c>>(self, db: E) -> Result<Option<M>>

The first matching row (in the query’s order), or None.

Source

pub async fn count<'c, E: Executor<'c>>(self, db: E) -> Result<u64>

How many rows match (with group_by: how many groups).

Source

pub async fn exists<'c, E: Executor<'c>>(self, db: E) -> Result<bool>

Whether any row matches.

Source

pub async fn paginate( self, db: &Db, page: u32, per_page: u32, ) -> Result<Paginated<M>>

One page of results plus the numbers needed to render page links. page starts at 1; per_page is capped at 1000.

Source

pub async fn simple_paginate( self, db: &Db, page: u32, per_page: u32, ) -> Result<SimplePage<M>>

One page without counting the rows (one query instead of two): for “previous / next” links on large tables. page starts at 1.

Source

pub async fn cursor_paginate( self, db: &Db, cursor: Option<&str>, per_page: u32, ) -> Result<CursorPage<M>>

The per_page newest rows after cursor (by id; the query’s own order doesn’t apply), for APIs and infinite scroll on big tables: unlike page numbers, rows added meanwhile don’t shift the pages. “Newest” is the key’s order: creation order for i64, ULIDs and UUID v7s; a String key pages in text order.

#[derive(serde::Deserialize)]
struct Params { cursor: Option<String> }

async fn events(State(db): State<Db>, Query(p): Query<Params>) -> Result<Json<renox::db::CursorPage<Event>>> {
    Ok(Json(Event::query().cursor_paginate(&db, p.cursor.as_deref(), 50).await?))
}
Source

pub async fn first_or_new( self, db: &Db, make: impl FnOnce() -> M + Send, ) -> Result<M>

The first matching row, or make() unsaved (firstOrNew).

Source

pub fn update_or_create<'a>( self, db: &'a Db, make: impl FnOnce() -> M + Send + 'a, change: impl FnOnce(&mut M) + Send + 'a, ) -> impl Future<Output = Result<M>> + Send + 'a

Changes the first matching row with change, or creates make() with change applied (updateOrCreate); returns it saved.

let theme = Setting::where_eq("user_id", 7)
    .where_eq("key", "theme")
    .update_or_create(
        &db,
        || Setting { user_id: 7, key: "theme".into(), ..Default::default() },
        |s| s.value = "dark".into(),
    )
    .await?;
Source

pub async fn delete<'c, E: Executor<'c>>(self, db: E) -> Result<u64>

Deletes every matching row (soft-deletes them for models with soft deletes).

Source

pub async fn force_delete<'c, E: Executor<'c>>(self, db: E) -> Result<u64>

Removes every matching row, even for models with soft deletes.

Trait Implementations§

Source§

impl<M> Clone for Query<M>

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

Auto Trait Implementations§

§

impl<M> Freeze for Query<M>
where PhantomData<fn() -> M>: Freeze,

§

impl<M> RefUnwindSafe for Query<M>
where PhantomData<fn() -> M>: RefUnwindSafe,

§

impl<M> Send for Query<M>
where PhantomData<fn() -> M>: Send,

§

impl<M> Sync for Query<M>
where PhantomData<fn() -> M>: Sync,

§

impl<M> Unpin for Query<M>
where PhantomData<fn() -> M>: Unpin,

§

impl<M> UnsafeUnpin for Query<M>
where PhantomData<fn() -> M>: UnsafeUnpin,

§

impl<M> UnwindSafe for Query<M>
where PhantomData<fn() -> M>: UnwindSafe,

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> Fake for T

Source§

fn fake<U>(&self) -> U
where Self: FakeBase<U>,

Source§

fn fake_with_rng<U, R>(&self, rng: &mut R) -> U
where R: RngExt + ?Sized, Self: FakeBase<U>,

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<A, B, T> HttpServerConnExec<A, B> for T
where B: Body,

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> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. 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