pub struct QuerySet<T: Model> { /* private fields */ }Expand description
A lazy builder for a SELECT over T.
Filters are kept in the order you add them. Nothing touches the schema
until compile is called, so the builder never panics on bad input.
You can mix two filter shapes freely:
Self::filter/Self::eq— string keys, checked atcompiletime.Self::where_— typed (User::id.gt(10)); the column is already resolved, socompileskips the schema lookup.
Clone is written by hand so a half-built queryset can be the base for
two different branches. The derive would add a spurious T: Clone
bound, and T is only a compile-time schema reference.
Implementations§
Source§impl<T: Model> QuerySet<T>
impl<T: Model> QuerySet<T>
Sourcepub fn using(self, alias: &str) -> UsingQuerySet<T>
pub fn using(self, alias: &str) -> UsingQuerySet<T>
Run this queryset against the connection registered under
alias.
The returned UsingQuerySet has read terminals only. Writes
stay on the explicit fetch(&pool) family so one cannot reach
a read replica by mistake.
§Panics
If alias is not registered. See pool.
Sourcepub fn routed(self) -> UsingQuerySet<T>
pub fn routed(self) -> UsingQuerySet<T>
Let the DatabaseRouter chain pick the connection. The
automatic version of Self::using.
Read terminals only, as with Self::using. For writes call
fetch(&write_pool_for(T::SCHEMA)).
§Panics
If the chosen alias is not registered. See pool.
Source§impl<T: Model> QuerySet<T>
impl<T: Model> QuerySet<T>
pub fn new() -> Self
Sourcepub fn without_global_scope(self, name: &'static str) -> Self
pub fn without_global_scope(self, name: &'static str) -> Self
Eloquent withoutGlobalScope($name). Skip one named entry from
crate::core::ModelSchema::global_scopes on this queryset.
Repeated calls add up.
Unknown names are ignored, like Eloquent, so a call site can opt out of a scope that does not exist yet.
Sourcepub fn without_global_scopes(self) -> Self
pub fn without_global_scopes(self) -> Self
Eloquent withoutGlobalScopes(). Skip every scope from
crate::core::ModelSchema::global_scopes. Useful for admin or
migration code that must see soft-deleted, unpublished or
cross-tenant rows the app normally hides.
Once set, later Self::without_global_scope calls change
nothing: everything stays disabled on this queryset.
Sourcepub fn none(self) -> Self
pub fn none(self) -> Self
A queryset that matches zero rows. Handy as a
safe base for conditional filters, such as
if !user.has_perm { qs = qs.none() }.
SELECT compiles to LIMIT 0. UPDATE / DELETE add an IS NULL
test against the NOT NULL primary key, so no row matches.
Sourcepub fn distinct(self) -> Self
pub fn distinct(self) -> Self
Emit SELECT DISTINCT .... Behaves the
same on every dialect. Add .order_by(...) to decide which row
of a duplicate group survives; without it the order is undefined.
For “first row per group”, use Self::distinct_on.
Sourcepub fn distinct_on(self, fields: &[&'static str]) -> Self
pub fn distinct_on(self, fields: &[&'static str]) -> Self
Distinct on named columns. Emits DISTINCT ON (col1, col2) on
Postgres. On MySQL / SQLite it lowers to a ROW_NUMBER() OVER (PARTITION BY cols ORDER BY <order_by>) subquery. All three give
“first row per group”, and the queryset’s ORDER BY decides
which row is first.
The columns must come first in .order_by(...).
Otherwise .compile() returns
QueryError::DistinctOnOrderByMismatch. Empty fields
returns QueryError::DistinctOnEmpty; use
Self::distinct for that instead.
Sourcepub fn select_for_update(self) -> Self
pub fn select_for_update(self) -> Self
Take a row lock. Emits SELECT … FOR UPDATE on
Postgres and MySQL 8+. SQLite has no row-lock syntax, so it is a
no-op there; a SQLite transaction locks the whole database.
Run it inside a transaction. FOR UPDATE outside one does
nothing on Postgres and errors on MySQL. Open one with
crate::sql::transaction_pool, then call
.fetch_on(&mut *tx).
The defaults (crate::core::LockMode::default) emit plain
FOR UPDATE. Use the methods below to set individual flags.
Sourcepub fn lock_for_update(self) -> Self
pub fn lock_for_update(self) -> Self
Eloquent Builder::lockForUpdate(). Alias of
Self::select_for_update, with the same rules.
Sourcepub fn skip_locked(self) -> Self
pub fn skip_locked(self) -> Self
PG / MySQL 8+: add SKIP LOCKED — the “claim the next free row”
pattern. Rows another transaction holds are skipped instead of
blocking. No effect on SQLite. Implies
Self::select_for_update.
Sourcepub fn nowait(self) -> Self
pub fn nowait(self) -> Self
PG / MySQL 8+: add NOWAIT — return a driver error at once if
any matching row is locked. The database forbids it together
with SKIP LOCKED, so if both are set the writer emits
SKIP LOCKED. Implies Self::select_for_update.
Sourcepub fn no_key(self) -> Self
pub fn no_key(self) -> Self
PG 9.3+: FOR NO KEY UPDATE instead of FOR UPDATE. A weaker
lock that does not block writers leaving the row’s PK and unique
columns alone. Good for busy update paths that never change
indexed columns. MySQL has no equivalent, so the writer falls
back to FOR UPDATE.
Sourcepub fn of(self, tables: &[&'static str]) -> Self
pub fn of(self, tables: &[&'static str]) -> Self
PG 9.3+ / MySQL 8.0.1+: FOR UPDATE OF table1, table2, … — lock
only the named tables when the query joins. Without OF the
lock covers every joined table the result touches. No-op on
SQLite.
Each call appends. Pass base table names or join aliases.
Sourcepub fn silent_on_sqlite(self) -> Self
pub fn silent_on_sqlite(self) -> Self
Stop the writer from warning that SQLite has no row locks.
SQLite has no FOR UPDATE syntax, so the lock modifiers are
dropped. The writer logs a tracing::warn! by default, so nobody
chases a phantom concurrency bug on a SQLite fixture. Call this
when SQLite’s single global write lock is enough for you.
No effect on PG / MySQL; locks emit normally there.
Sourcepub fn union(self, other: QuerySet<T>) -> Self
pub fn union(self, other: QuerySet<T>) -> Self
Combines this queryset with other
using SQL UNION, which removes duplicates. Both target model
T, so the column shape always matches.
Every .union() / .union_all() call appends another branch.
Mixing in intersection or difference is allowed; SQL
evaluates the chain left to right.
.order_by() / .limit() / .offset() called AFTER .union()
apply to the combined result. The same calls BEFORE it apply to
the first queryset only. Each
branch keeps its own clauses, because every component is wrapped
in an aliased derived table (SELECT * FROM (…) AS __rustango_bN) on all three backends.
Works on every supported backend.
§Panics
If other.compile() fails, for example on a typo’d column in
the branch. A malformed branch is a programmer error. To get a
Result instead, pre-compile the branch and pass it to
Self::with_compound.
Sourcepub fn union_all(self, other: QuerySet<T>) -> Self
pub fn union_all(self, other: QuerySet<T>) -> Self
UNION ALL — combine without removing duplicates. Cheaper than
Self::union because the database skips the DISTINCT pass.
Use it when you know the branches do not overlap.
§Panics
As Self::union.
Sourcepub fn intersection(self, other: QuerySet<T>) -> Self
pub fn intersection(self, other: QuerySet<T>) -> Self
Sourcepub fn difference(self, other: QuerySet<T>) -> Self
pub fn difference(self, other: QuerySet<T>) -> Self
Emits EXCEPT: rows in this
queryset but not in other. Postgres, SQLite and MySQL 8.0.31+.
§Panics
As Self::union.
Sourcepub fn with_compound(self, op: SetOp, branch: SelectQuery) -> Self
pub fn with_compound(self, op: SetOp, branch: SelectQuery) -> Self
Set-algebra entry point that takes an already-compiled
SelectQuery branch. Use it when building the branch may fail
and you want to handle that error yourself. The operator
argument covers union, union_all, intersection and difference.
// Caller wants to handle the branch's compile error explicitly:
let branch = Post::objects()
.filter("typo_field__lt", 100_i64) // may fail
.compile()?; // → Result
let qs = Post::objects()
.where_(Post::active.eq(true))
.with_compound(SetOp::Union, branch);Sourcepub fn order_by(self, items: &[(&str, bool)]) -> Self
pub fn order_by(self, items: &[(&str, bool)]) -> Self
Append ORDER BY columns.
Each entry is a (field_name, desc) pair naming a Rust-side
field on the model. The schema check runs at compile() time.
Calls compose: later ones append after earlier ones.
let posts = Post::objects()
.order_by(&[("published_at", true)]) // newest first
.fetch_on(conn).await?;To sort by multiple columns:
.order_by(&[("category", false), ("published_at", true)])Sourcepub fn reorder(self, items: &[(&str, bool)]) -> Self
pub fn reorder(self, items: &[(&str, bool)]) -> Self
Eloquent Builder::reorder([col, asc?]) — replace the
accumulated ORDER BY list instead of appending to it like
Self::order_by. Use it to override a default ordering that
came from a base queryset or manager:
let qs = Post::objects()
.with_default_order() // model's default
.reorder(&[("created_at", true)]); // wipes defaultPass an empty slice, .reorder(&[]), to clear every sort key,
like Eloquent’s reorder() with no arguments.
Sourcepub fn order_by_desc(self, column: &str) -> Self
pub fn order_by_desc(self, column: &str) -> Self
Shortcut for ORDER BY <col> DESC. Appends to the existing
list; call Self::reorder first to replace it.
Eloquent calls this Builder::latest($column), but rustango’s
Self::latest is the async fetcher, so the chainable form
uses this name.
Post::objects().order_by_desc("created_at").fetch(&pool).await?;
// SELECT ... FROM post ORDER BY created_at DESCSourcepub fn order_by_asc(self, column: &str) -> Self
pub fn order_by_asc(self, column: &str) -> Self
Single-column shortcut for ORDER BY <col> ASC. Appends to the
existing ORDER BY list.
Counterpart of Self::order_by_desc; mirrors Eloquent’s
Builder::oldest($column).
Post::objects().order_by_asc("created_at").fetch(&pool).await?;
// SELECT ... FROM post ORDER BY created_at ASCSourcepub fn with_default_order(self) -> Self
pub fn with_default_order(self) -> Self
Apply the schema’s default_order for T. Each entry from
#[rustango(default_order = "...")] is prepended to the pending
ORDER BY list, so a later .order_by(...) adds secondary keys.
You must opt in per query. A model’s default order is not
applied on its own; every queryset starts unsorted. This keeps
.count(), .exists() and
.delete() from paying for a sort they do not need.
A no-op when the model has no default_order, and calling it
twice does not duplicate the entries.
Sourcepub fn unordered(self) -> Self
pub fn unordered(self) -> Self
Clear every accumulated ORDER BY entry, whatever added it
(.order_by(...), .order_by_expr(...),
.with_default_order()). Use it to drop the default order of a
queryset you got from a builder helper.
Sourcepub fn order_by_with_nulls(
self,
items: &[(&'static str, bool, NullsOrder)],
) -> Self
pub fn order_by_with_nulls( self, items: &[(&'static str, bool, NullsOrder)], ) -> Self
Append ORDER BY columns and say where NULLs go. PG and SQLite
emit the NULLS … keyword. MySQL has no such syntax, so it
sorts by <col> IS NULL first instead.
use rustango::core::NullsOrder;
Post::objects()
.order_by_with_nulls(&[("published_at", true, NullsOrder::Last)])
.fetch(&pool).await?;Composes with .order_by(...): entries from both methods appear
in the ORDER BY clause in registration order.
Sourcepub fn order_by_expr(self, expr: impl Into<Expr>, desc: bool) -> Self
pub fn order_by_expr(self, expr: impl Into<Expr>, desc: bool) -> Self
Append an ORDER BY item over any Expr, such as
lower(F("title")), case(...) or F("a") + F("b").
desc = true gives DESC. NULL placement follows the dialect
default; use Self::order_by_expr_with_nulls to pin it.
Sourcepub fn order_by_distance(
self,
column: &'static str,
query: Vec<f32>,
metric: VectorMetric,
) -> Self
pub fn order_by_distance( self, column: &'static str, query: Vec<f32>, metric: VectorMetric, ) -> Self
Order rows by pgvector distance from query to the column
vector. Distance ascends, so the nearest rows come first for
every metric.
Emits ORDER BY <column> <op> $vec, where <op> is the pgvector
operator for metric (<->, <=>, <#>). PG only: the
writer raises OpNotSupportedInDialect on MySQL / SQLite. Add
.limit(k), or use Self::k_nearest, for a k-NN query. The
column should be a crate::sql::Vector field.
use rustango::core::VectorMetric;
// 5 nearest documents to `query_embedding` by cosine distance.
let hits = Doc::objects()
.order_by_distance("embedding", query_embedding, VectorMetric::Cosine)
.limit(5)
.fetch(&pool).await?;Sourcepub fn k_nearest(
self,
column: &'static str,
query: Vec<f32>,
k: i64,
metric: VectorMetric,
) -> Self
pub fn k_nearest( self, column: &'static str, query: Vec<f32>, k: i64, metric: VectorMetric, ) -> Self
k-nearest-neighbour shortcut: Self::order_by_distance plus
.limit(k). Returns the k rows closest to query under
metric. PG only.
use rustango::core::VectorMetric;
let top3 = Doc::objects()
.k_nearest("embedding", query_embedding, 3, VectorMetric::L2)
.fetch(&pool).await?;Sourcepub fn order_by_distance_to(self, column: &'static str, point: Point) -> Self
pub fn order_by_distance_to(self, column: &'static str, point: Point) -> Self
PostGIS nearest-first ordering: ORDER BY ST_Distance(<column>, <point>) ascending. Add .limit(k) for a k-nearest query.
column should be a #[rustango(geometry(...))] field.
PG / PostGIS only: MySQL and SQLite raise
OpNotSupportedInDialect at compile time.
// The 5 places nearest to `here`.
let near = Place::objects()
.order_by_distance_to("location", here)
.limit(5)
.fetch(&pool).await?;Sourcepub fn filter_dwithin(
self,
column: &'static str,
point: Point,
distance: f64,
) -> Self
pub fn filter_dwithin( self, column: &'static str, point: Point, distance: f64, ) -> Self
PostGIS “within radius” filter: WHERE ST_DWithin(<column>, <point>, <distance>). distance uses the column’s SRID units,
which is degrees for SRID 4326. For metres, cast to
::geography in raw SQL. PG / PostGIS only.
// Places within ~1km (in degrees) of `here`.
let nearby = Place::objects()
.filter_dwithin("location", here, 0.01)
.fetch(&pool).await?;Sourcepub fn order_by_expr_with_nulls(
self,
expr: impl Into<Expr>,
desc: bool,
nulls: NullsOrder,
) -> Self
pub fn order_by_expr_with_nulls( self, expr: impl Into<Expr>, desc: bool, nulls: NullsOrder, ) -> Self
Same as Self::order_by_expr, but with an explicit
NullsOrder.
Sourcepub fn order_random(self) -> Self
pub fn order_random(self) -> Self
ORDER BY RANDOM() (PG / SQLite) or ORDER BY RAND() (MySQL).
Good for “random N rows” needs
such as banner rotation or sampling.
// Three random posts.
Post::objects()
.order_random()
.limit(3)
.fetch(&pool).await?;Cost: this forces a full table scan and an in-memory sort on
a random key per row. No index can help. On tables much larger
than memory, use WHERE pk >= <random_offset> LIMIT N instead,
which can range-scan an index, and accept that the rows come out
next to each other by primary key.
It composes with other .order_by* calls: the random key only
breaks ties. Most callers want Self::replace_order_by first.
Sourcepub fn in_random_order(self) -> Self
pub fn in_random_order(self) -> Self
Eloquent Builder::inRandomOrder(). Alias of
Self::order_random, with the same cost.
// Eloquent: Post::query()->inRandomOrder()->take(5)->get();
let five = Post::objects()
.in_random_order()
.take(5)
.fetch(&pool).await?;Sourcepub fn replace_order_by(self, items: &[(&str, bool)]) -> Self
pub fn replace_order_by(self, items: &[(&str, bool)]) -> Self
Drop every pending ORDER BY item and use items instead.
Used by earliest and latest, which set their own sort.
Sourcepub fn reverse(self) -> Self
pub fn reverse(self) -> Self
Flips the direction of every pending ORDER BY entry.
Random has no direction, so it stays as it is.
No-op when no ordering is set.
// newest first
let q = Post::objects()
.order_by(&[("published_at", true)]);
// oldest first — same predicate set, flipped sort
let r = q.reverse();Sourcepub fn flip_order_by(self) -> Self
pub fn flip_order_by(self) -> Self
Flip every ordering direction in place. last uses it to take
the first row of the reversed sort, which avoids OFFSET plus
COUNT(*) and works on every dialect. It also swaps
NullsOrder::First and NullsOrder::Last, so NULLs stay at the
same logical end.
Sourcepub fn has_order_by(&self) -> bool
pub fn has_order_by(&self) -> bool
Whether any ORDER BY item is registered. The executor’s
ensure_pk_ordering uses it to spot “no ordering set” without
looking at the entry variants.
Load a ForeignKey<Parent> field with a LEFT JOIN, in the
same query. Pass the field name on T, not the
FK column or the parent table. fetch_on then returns rows
whose ForeignKey<Parent> is already Loaded, from a single
query, with no N+1.
let posts: Vec<Post> = Post::objects()
.select_related("author")
.fetch_on(conn).await?;
// post.author is ForeignKey::Loaded { pk, value }Calls compose: each adds another LEFT JOIN to the same SELECT.
The schema check — field exists, is an FK, target has a primary
key — runs at compile() time.
Sourcepub fn join(self, join: Join) -> Self
pub fn join(self, join: Join) -> Self
Append a fully specified crate::core::Join. Unlike
select_related, which builds joins from FK metadata, you
choose the join kind, alias, predicate and projected columns.
The predicate is any WhereExpr; its columns qualify against
the joined alias by default, or against another alias via
crate::core::Expr::AliasedColumn.
Calls compose; each JOIN lands after the select_related ones.
Aliases must be unique within the queryset.
use rustango::core::joins::aliased;
use rustango::core::{Join, JoinKind, Op, WhereExpr};
Post::objects()
.join(Join {
target: Comment::SCHEMA,
alias: "c",
kind: JoinKind::Inner,
on: WhereExpr::And(vec![
WhereExpr::ExprCompare {
lhs: aliased("c", "post_id"),
op: Op::Eq,
rhs: aliased("post", "id"),
},
// Filter columns inside `on` qualify to the joined
// alias (`c`) by default — no need to `aliased()` here.
Comment::is_approved.eq(true).into(),
]),
project: vec![],
})
.fetch(&pool).await?;Sourcepub fn join_sub(
self,
sub: impl Into<DerivedSource>,
alias: &'static str,
on: WhereExpr,
) -> Self
pub fn join_sub( self, sub: impl Into<DerivedSource>, alias: &'static str, on: WhereExpr, ) -> Self
INNER JOIN (<subquery>) AS <alias> ON <on> — join a derived
table, like Eloquent’s joinSub.
sub is a compiled SelectQuery. In on, name the derived
table’s columns and the outer table’s columns with
crate::core::joins::aliased. The derived table adds no
columns to the SELECT, so a typed fetch still returns the base
model. Works on PG, MySQL and SQLite.
use rustango::core::joins::aliased;
use rustango::core::{Op, WhereExpr};
// Customers who have placed at least one order.
let recent = Order::objects()
.values(&["customer_id"]) // derived table: distinct customer ids
.compile()?;
let with_orders = Customer::objects()
.join_sub(recent, "o", WhereExpr::ExprCompare {
lhs: aliased("o", "customer_id"),
op: Op::Eq,
rhs: aliased("customer", "id"),
})
.fetch(&pool).await?;Sourcepub fn left_join_sub(
self,
sub: impl Into<DerivedSource>,
alias: &'static str,
on: WhereExpr,
) -> Self
pub fn left_join_sub( self, sub: impl Into<DerivedSource>, alias: &'static str, on: WhereExpr, ) -> Self
LEFT JOIN (<subquery>) AS <alias> ON <on> — the left-join form
of Self::join_sub (Eloquent leftJoinSub).
Sourcepub fn join_lateral(
self,
sub: impl Into<DerivedSource>,
alias: &'static str,
on: WhereExpr,
) -> Self
pub fn join_lateral( self, sub: impl Into<DerivedSource>, alias: &'static str, on: WhereExpr, ) -> Self
INNER JOIN LATERAL (<subquery>) AS <alias> ON <on> — Eloquent
joinLateral. The subquery may read columns from the outer
query, which is how you get “top-N rows per group”. Put that
correlation in the subquery’s own WHERE, using
crate::core::joins::aliased against the outer table, and
pass WhereExpr::And(vec![]) as on to emit ON true.
PostgreSQL and MySQL 8.0.14+ only. SQLite has no LATERAL,
so the writer raises
crate::sql::SqlError::LateralJoinNotSupported.
Sourcepub fn left_join_lateral(
self,
sub: impl Into<DerivedSource>,
alias: &'static str,
on: WhereExpr,
) -> Self
pub fn left_join_lateral( self, sub: impl Into<DerivedSource>, alias: &'static str, on: WhereExpr, ) -> Self
LEFT JOIN LATERAL (<subquery>) AS <alias> ON <on> — the
left-join form of Self::join_lateral (Eloquent
leftJoinLateral). Keeps every outer row even when the lateral
subquery returns none, as in “latest order per customer,
including customers with no orders”. PG / MySQL only.
Sourcepub fn limit(self, n: i64) -> Self
pub fn limit(self, n: i64) -> Self
Cap the number of returned rows. A later call replaces the cap.
Sourcepub fn take(self, n: i64) -> Self
pub fn take(self, n: i64) -> Self
Eloquent Builder::take($n) — alias of Self::limit.
Cap the result to at most n rows.
Sourcepub fn skip(self, n: i64) -> Self
pub fn skip(self, n: i64) -> Self
Eloquent Builder::skip($n) — alias of Self::offset.
Sourcepub fn filter_op(
self,
field: impl Into<String>,
op: Op,
value: impl Into<SqlValue>,
) -> Self
pub fn filter_op( self, field: impl Into<String>, op: Op, value: impl Into<SqlValue>, ) -> Self
Append a WHERE field <op> value predicate with an explicit
Op. Use it when you already know the operator; for the
filter("field__lookup", value) shape see Self::filter.
field is the Rust-side field name. The column is looked up in
the schema at compile time.
Sourcepub fn filter(self, key: &str, value: impl Into<SqlValue>) -> Self
pub fn filter(self, key: &str, value: impl Into<SqlValue>) -> Self
Append a WHERE predicate. Parses a "field" or
"field__lookup" key and picks the matching Op.
| Suffix | SQL | Value treatment |
|---|---|---|
(none) / __exact | <col> = ? | as-is |
__iexact | <col> ILIKE ? | as-is (no wildcards) |
__contains | <col> LIKE ? | wrap %value% |
__icontains | <col> ILIKE ? | wrap %value% |
__startswith | <col> LIKE ? | wrap value% |
__istartswith | <col> ILIKE ? | wrap value% |
__endswith | <col> LIKE ? | wrap %value |
__iendswith | <col> ILIKE ? | wrap %value |
__like / __ilike / __not_like / __not_ilike | <col> [NOT] (I)LIKE ? | value bound verbatim — caller controls % / _ placement. Eloquent whereLike / whereNotLike parity. |
__gt / __gte / __lt / __lte | direct map | as-is |
__ne | <col> <> ? | as-is |
__in | <col> IN (...) | value must be SqlValue::List |
__not_in | <col> NOT IN (...) | value must be SqlValue::List. Eloquent whereNotIn parity. |
__isnull | <col> IS NULL / IS NOT NULL | value must be bool |
__between / __range | <col> BETWEEN ? AND ? | value must be 2-element SqlValue::List |
__not_between / __not_range | <col> NOT BETWEEN ? AND ? | value must be 2-element SqlValue::List. Eloquent whereNotBetween parity. |
__year / __month / __day / __hour / __minute / __second / __quarter / __week / __week_day | EXTRACT(<part> FROM <col>) = ? | scalar value matches the date part. Composes with a trailing __gte / __lt / etc. __quarter works on every dialect; SQLite derives it from the month. __week numbering differs per backend. |
__date | DATE(<col>) = ? | value is a chrono::NaiveDate; strips the time component before comparison. |
Post::objects()
.filter("title__icontains", "rust")
.filter("views__gt", 100_i64)
.filter("author_id__in", rustango::core::SqlValue::List(vec![
1_i64.into(), 2_i64.into(), 3_i64.into(),
]))
.fetch(&pool).await?;Unknown suffixes surface as QueryError::UnknownLookup at
compile(). A wrong value shape, such as __in with a non-list
value, surfaces as QueryError::InvalidLookupValue.
Relation-spanning keys such as author__name__icontains work on
the SELECT path: compile() adds the FK-chain JOINs for you.
They are not supported on update, delete or aggregate paths,
which error instead.
Sourcepub fn exclude(self, key: &str, value: impl Into<SqlValue>) -> Self
pub fn exclude(self, key: &str, value: impl Into<SqlValue>) -> Self
The negation of Self::filter. Each call wraps its own
predicate in NOT (…), and chained excludes AND together. The
full __lookup grammar works here too.
Post::objects().exclude("status", "draft").fetch(&pool).await?;
// with a lookup suffix:
Post::objects().exclude("views__lt", 100_i64)NULLs: NOT (col = v) also drops rows where col IS NULL,
because of SQL three-valued logic. To put one NOT over a
whole group of conditions, use where_raw(!Q(...)).
Sourcepub fn eq(self, field: impl Into<String>, value: impl Into<SqlValue>) -> Self
pub fn eq(self, field: impl Into<String>, value: impl Into<SqlValue>) -> Self
Shorthand for filter_op(field, Op::Eq, value).
Sourcepub fn where_key(self, pk: impl Into<SqlValue>) -> Self
pub fn where_key(self, pk: impl Into<SqlValue>) -> Self
Eloquent Builder::whereKey($pk). Filter on the model’s
primary key without naming the column; it comes from
T::SCHEMA.primary_key().
// Eloquent: Post::query()->whereKey(42)->first();
// rustango:
let post = Post::objects()
.where_key(42_i64)
.first(&pool).await?;Models without #[rustango(primary_key)] surface as
QueryError::UnknownField (field "<pk>") at compile time.
Sourcepub fn where_key_not(self, pk: impl Into<SqlValue>) -> Self
pub fn where_key_not(self, pk: impl Into<SqlValue>) -> Self
Eloquent Builder::whereKeyNot($pk). The opposite of
Self::where_key: matches every row whose PK is not pk.
// Eloquent: Post::query()->whereKeyNot(1)->get();
let others = Post::objects()
.where_key_not(1_i64)
.fetch(&pool).await?;Errors as Self::where_key when the model carries no PK.
Sourcepub fn where_exists(self, subquery: SelectQuery) -> Self
pub fn where_exists(self, subquery: SelectQuery) -> Self
Eloquent Builder::whereExists($closure). ANDs an
EXISTS (subquery) predicate onto this queryset’s WHERE.
subquery is an already-compiled SelectQuery. Build it from
the inner model’s objects() chain and call .compile(), so a
column typo surfaces there. Use
crate::core::subquery::outer_ref to refer to columns of the
outer model.
use rustango::core::Column as _;
use rustango::core::subquery::outer_ref;
// Authors who have at least one book.
let with_books = Book::objects()
.where_(Book::author_id.eq_expr(outer_ref("id")))
.compile()?;
let authors = Author::objects()
.where_exists(with_books)
.fetch(&pool).await?;Sugar over self.where_raw(subquery::exists(subquery)).
Sourcepub fn where_not_exists(self, subquery: SelectQuery) -> Self
pub fn where_not_exists(self, subquery: SelectQuery) -> Self
Eloquent Builder::whereNotExists($closure). ANDs a
NOT EXISTS (subquery) predicate. The inverse of
Self::where_exists, and the usual way to find rows in A with
no related row in B.
let no_books = Book::objects()
.where_(Book::author_id.eq_expr(outer_ref("id")))
.compile()?;
let empty = Author::objects()
.where_not_exists(no_books)
.fetch(&pool).await?;Sourcepub fn where_in_subquery(
self,
column: &'static str,
subquery: SelectQuery,
) -> Self
pub fn where_in_subquery( self, column: &'static str, subquery: SelectQuery, ) -> Self
Eloquent Builder::whereIn($column, $closure) with a subquery
instead of a value list. Emits <column> IN (subquery).
subquery is an already-compiled SelectQuery that should
project one column, matched against column on the outer model.
let public_cat_ids = Category::objects()
.filter("is_public", true)
.values_list_flat("id")
.compile()?;
let visible = Post::objects()
.where_in_subquery("category_id", public_cat_ids)
.fetch(&pool).await?;Sourcepub fn where_not_in_subquery(
self,
column: &'static str,
subquery: SelectQuery,
) -> Self
pub fn where_not_in_subquery( self, column: &'static str, subquery: SelectQuery, ) -> Self
Eloquent Builder::whereNotIn($column, $closure). The inverse
of Self::where_in_subquery; emits
<column> NOT IN (subquery).
Sourcepub fn where_has(self, name: &str) -> Self
pub fn where_has(self, name: &str) -> Self
Keep rows that have at least one related row through the
relation named name.
name is looked up in three relation kinds, in this order, so
the same call works however the relation is declared on T:
- reverse-FK —
EXISTS (SELECT 1 FROM <child> WHERE <child_fk> = <outer>.<pk>). - many-to-many — the same
EXISTSover the junction table. - generic-FK — the same
EXISTSover the polymorphic child, AND-ed with a content-type check so only children pointing at this model match.
All three emit the same way on PG, MySQL and SQLite. An unknown
relation name surfaces as QueryError::UnknownField at
compile() time.
// Authors with at least one book (reverse-FK relation "books").
let with_books = Author::objects()
.where_has("books")
.fetch(&pool).await?;Sourcepub fn where_doesnt_have(self, name: &str) -> Self
pub fn where_doesnt_have(self, name: &str) -> Self
The opposite of Self::where_has: keep rows that have no
related row. Emits NOT EXISTS (subquery). Same relation lookup
and same errors.
// Authors with zero books.
let empty = Author::objects()
.where_doesnt_have("books")
.fetch(&pool).await?;Sourcepub fn where_has_filter(self, name: &str, inner: SelectQuery) -> Self
pub fn where_has_filter(self, name: &str, inner: SelectQuery) -> Self
Keep rows with at least one related row through the named
reverse-FK relation and matching your inner predicate.
Eloquent Builder::whereHas($rel, fn ($q) => …).
inner is a compiled SelectQuery on the child model, usually
Child::objects().filter(...).compile()?. Its WHERE is ANDed
with the correlation <child_fk_column> = <outer>.<self_pk>,
and the result is wrapped in EXISTS (…).
inner.model must be the relation’s child model. A mismatch
surfaces as QueryError::UnknownField at compile time.
// Eloquent: Author::whereHas('books', fn ($q) => $q->where('published', true))->get();
let inner = Book::objects().filter("published", true).compile()?;
let authors = Author::objects()
.where_has_filter("books", inner)
.fetch(&pool).await?;Sourcepub fn where_doesnt_have_filter(self, name: &str, inner: SelectQuery) -> Self
pub fn where_doesnt_have_filter(self, name: &str, inner: SelectQuery) -> Self
whereDoesntHave($rel, fn ($q) => …), the counterpart of
Self::where_has_filter. Keeps rows with no related row
matching the inner predicate, using NOT EXISTS (…).
Sourcepub fn where_has_count(self, name: &str, op: Op, n: i64) -> Self
pub fn where_has_count(self, name: &str, op: Op, n: i64) -> Self
Keep rows whose count of related rows satisfies
<count> <op> n.
Emits a correlated aggregate subquery in the WHERE clause:
(SELECT COUNT(*) FROM <child> WHERE <child_fk> = <outer>.<self_pk>) <op> n. It runs the same on PG, MySQL and
SQLite.
op must be a comparison: Op::Eq, Op::Ne, Op::Lt,
Op::Lte, Op::Gt or Op::Gte. Anything else errors at
compile time. For “has at least one” or “has none”, prefer
Self::where_has / Self::where_doesnt_have, which emit a
cheaper EXISTS.
An unknown relation name surfaces as
QueryError::UnknownField, as in Self::where_has.
// Eloquent: Author::has('books', '>', 3)->get();
let prolific = Author::objects()
.where_has_count("books", Op::Gt, 3)
.fetch(&pool).await?;Sourcepub fn annotate_count(self, name: &str) -> AggregateBuilder<T>
pub fn annotate_count(self, name: &str) -> AggregateBuilder<T>
Add the count of related rows as a <name>_count column.
This turns the queryset into an AggregateBuilder, whose rows
are Vec<HashMap<String, SqlValue>>, like every other
QuerySet::annotate path: a typed T has no field for the
derived column. Each row carries every scalar column of T plus
the <name>_count key.
The count comes from a correlated subquery, not a JOIN, so it
never double-counts and causes no N+1.
An unknown relation name surfaces as
QueryError::UnknownField at compile() time.
// Eloquent: Author::withCount('books')->get();
let rows = Author::objects()
.annotate_count("books")
.fetch(&pool).await?;
// rows[0]["books_count"] => SqlValue::I64(n)Sourcepub fn annotate_sum(
self,
name: &str,
column: &'static str,
) -> AggregateBuilder<T>
pub fn annotate_sum( self, name: &str, column: &'static str, ) -> AggregateBuilder<T>
Add SUM(<column>) over related rows as <name>_sum_<column>.
Eloquent withSum('orders', 'total'). column belongs to the
child model and is checked at compile() time. See
Self::annotate_count for the return shape.
Sourcepub fn annotate_avg(
self,
name: &str,
column: &'static str,
) -> AggregateBuilder<T>
pub fn annotate_avg( self, name: &str, column: &'static str, ) -> AggregateBuilder<T>
Add AVG(<column>) over related rows as <name>_avg_<column>.
Eloquent withAvg('orders', 'total'). See
Self::annotate_sum.
Sourcepub fn annotate_max(
self,
name: &str,
column: &'static str,
) -> AggregateBuilder<T>
pub fn annotate_max( self, name: &str, column: &'static str, ) -> AggregateBuilder<T>
Add MAX(<column>) over related rows as <name>_max_<column>.
Eloquent withMax('orders', 'total'). See
Self::annotate_sum.
Sourcepub fn annotate_min(
self,
name: &str,
column: &'static str,
) -> AggregateBuilder<T>
pub fn annotate_min( self, name: &str, column: &'static str, ) -> AggregateBuilder<T>
Add MIN(<column>) over related rows as <name>_min_<column>.
Eloquent withMin('orders', 'total'). See
Self::annotate_sum.
Sourcepub fn annotate_exists(self, name: &str) -> AggregateBuilder<T>
pub fn annotate_exists(self, name: &str) -> AggregateBuilder<T>
Add a <name>_exists column saying whether any related row
exists.
Emits CASE WHEN EXISTS (…) THEN 1 ELSE 0 END, which is cheaper
than Self::annotate_count when you only need presence,
because EXISTS stops at the first matching child row. The
column decodes as SqlValue::I64(1) or I64(0) on all three
backends; integer literals keep the value the same everywhere.
See Self::annotate_count for the return shape.
An unknown relation name surfaces as
QueryError::UnknownField at compile() time.
Sourcepub fn where_column(self, col1: &'static str, col2: &'static str) -> Self
pub fn where_column(self, col1: &'static str, col2: &'static str) -> Self
Eloquent Builder::whereColumn($col1, $col2). Emits
<col1> = <col2>, comparing two columns instead of a column
and a literal. For any other operator, see
Self::where_column_op.
Both column names are checked against the schema at
compile() time, through
WhereExpr::ExprCompare.
// Eloquent: User::whereColumn('first_name', 'last_name');
User::objects()
.where_column("first_name", "last_name")
.fetch(&pool).await?;Sourcepub fn where_column_op(
self,
col1: &'static str,
op: Op,
col2: &'static str,
) -> Self
pub fn where_column_op( self, col1: &'static str, op: Op, col2: &'static str, ) -> Self
Eloquent Builder::whereColumn($col1, $op, $col2). Compares
two columns with an explicit operator. Use the shorter
Self::where_column when the operator is Eq.
use rustango::core::Op;
// start_date < end_date — Eloquent: whereColumn('start_date', '<', 'end_date')
Reservation::objects()
.where_column_op("start_date", Op::Lt, "end_date")
.fetch(&pool).await?;Sourcepub fn where_raw(self, expr: WhereExpr) -> Self
pub fn where_raw(self, expr: WhereExpr) -> Self
AND a raw WhereExpr into the accumulated WHERE clause. Use
it when the model has no derived typed columns, so
Self::where_ is unavailable, and you need OR / NOT / nested
predicates that the string-keyed Self::filter cannot reach.
The expression is checked against T::SCHEMA at compile()
time. An unknown column or a wrong-typed value returns
QueryError::UnknownField or QueryError::TypeMismatch,
as on the typed paths.
Sourcepub fn when<F>(self, condition: bool, f: F) -> Selfwhere
F: FnOnce(Self) -> Self,
pub fn when<F>(self, condition: bool, f: F) -> Selfwhere
F: FnOnce(Self) -> Self,
Eloquent Builder::when($condition, $callback). Applies f to
self only when condition is true, and otherwise returns
self unchanged. It keeps a conditional filter inside the
chain:
let qs = Post::objects()
.when(only_active, |qs| qs.filter("active", true))
.when(category_id.is_some(), |qs| {
qs.filter("category_id", category_id.unwrap())
});Equivalent to:
let mut qs = Post::objects();
if only_active { qs = qs.filter("active", true); }
if let Some(id) = category_id { qs = qs.filter("category_id", id); }The closure form keeps the chain readable when the condition is
an inline expression rather than a plain bool.
Sourcepub fn unless<F>(self, condition: bool, f: F) -> Selfwhere
F: FnOnce(Self) -> Self,
pub fn unless<F>(self, condition: bool, f: F) -> Selfwhere
F: FnOnce(Self) -> Self,
Eloquent Builder::unless($condition, $callback). The inverse
of Self::when: applies f only when condition is false.
Use it when the guard reads better stated negatively, such as
qs.unless(is_admin, |q| q.filter("public", true)).
Sourcepub fn tap<F>(self, f: F) -> Selfwhere
F: FnOnce(&Self),
pub fn tap<F>(self, f: F) -> Selfwhere
F: FnOnce(&Self),
Eloquent Builder::tap($callback). Runs a callback against the
queryset and returns it unchanged, so you can add logging,
metrics or a debug print without breaking the chain:
let rows = Post::objects()
.filter("active", true)
.tap(|qs| tracing::debug!(?qs, "about to fetch"))
.fetch(&pool).await?;Sourcepub fn active(self) -> Self
pub fn active(self) -> Self
Keep only rows that are NOT soft-deleted.
When T has #[rustango(soft_delete)] on a nullable
DateTime<Utc> column, this ANDs <col> IS NULL into the WHERE
clause. Models without a soft-delete column get a no-op, so
generic code can call .active() on any model. See
crate::soft_delete::active_filter.
Sourcepub fn only_trashed(self) -> Self
pub fn only_trashed(self) -> Self
Keep ONLY soft-deleted rows — the mirror of Self::active,
for trash pages and restore flows. A no-op when the model has
no soft-delete column. Eloquent onlyTrashed.
Sourcepub fn with_trashed(self) -> Self
pub fn with_trashed(self) -> Self
Eloquent withTrashed. A no-op marker that states intent: a
QuerySet already includes trashed rows unless you call
Self::active or the model declares a global scope that
filters them out.
Sourcepub fn where_<E: Into<TypedExpr<T>>>(self, predicate: E) -> Self
pub fn where_<E: Into<TypedExpr<T>>>(self, predicate: E) -> Self
Append a typed predicate or boolean expression built with the
Column API. Takes a single
TypedFilter (User::id.gt(10)) or
a composed TypedExpr (User::id.eq(1).or(User::id.eq(2))).
Every call ANDs its argument into the WHERE clause.
Sourcepub fn compile(self) -> Result<SelectQuery, QueryError>
pub fn compile(self) -> Result<SelectQuery, QueryError>
Validate the accumulated filters against T::SCHEMA and lower to
the dialect-neutral SelectQuery IR.
§Errors
Returns QueryError::UnknownField if a filter names a field not
present on the model, and QueryError::TypeMismatch if the bound
value’s type does not match the field’s declared type.
Sourcepub fn values_dict(self, cols: &[&'static str]) -> ValuesQuerySet<T>
pub fn values_dict(self, cols: &[&'static str]) -> ValuesQuerySet<T>
Project to Vec<HashMap<String, SqlValue>> — named columns
only, no typed model. Returns a ValuesQuerySet whose
.fetch(&pool) decodes rows into a HashMap keyed by column
name.
It skips the typed Model decode. Use it for a few fields off
a wide table, or when the result feeds code that wants dynamic
column access, such as templates, JSON or CSV export. For
GROUP BY, use QuerySet::values instead, which promotes to
AggregateBuilder.
Columns are checked against the schema at .compile() time. A
typo gives QueryError::UnknownField, and empty cols gives
QueryError::EmptyValuesProjection.
Sourcepub fn values_list(self, cols: &[&'static str]) -> ValuesListQuerySet<T>
pub fn values_list(self, cols: &[&'static str]) -> ValuesListQuerySet<T>
Project to Vec<Vec<SqlValue>>. Same as Self::values_dict,
but each row is an ordered Vec<SqlValue> matching the cols
order instead of a HashMap.
Sourcepub fn values_list_flat(self, col: &'static str) -> ValuesFlatQuerySet<T>
pub fn values_list_flat(self, col: &'static str) -> ValuesFlatQuerySet<T>
Single-column projection, flattened. Returns a
ValuesFlatQuerySet whose .fetch::<U>(&pool) decodes the
column into Vec<U> through sqlx’s query_scalar.
U must decode from the column’s SQL type on every dialect the
binary targets. Usually i64, i32, String, bool or f64.
Sourcepub fn only(self, cols: &[&'static str]) -> ValuesQuerySet<T>
pub fn only(self, cols: &[&'static str]) -> ValuesQuerySet<T>
Project only the listed columns.
Same behaviour as Self::values_dict:
the SQL is SELECT cols FROM … and each row is a
HashMap<String, SqlValue> keyed by column name. The separate
name just reads better at the call site.
Columns are checked at .compile() time. A typo gives
QueryError::UnknownField, and an empty list gives
QueryError::EmptyValuesProjection.
You get a HashMap rather than a partly filled Model: there
are no lazy-loading field descriptors, so a half-built struct
would silently read as zeroed.
Sourcepub fn defer(self, cols: &[&'static str]) -> ValuesQuerySet<T>
pub fn defer(self, cols: &[&'static str]) -> ValuesQuerySet<T>
Project every scalar column EXCEPT the listed ones — the
inverse of Self::only. The SELECT leaves
out the named columns, which saves IO on wide tables.
Same return shape as Self::only.
A column that does not exist on the model gives
QueryError::UnknownField at .compile() time, as it would
in .only(...). An empty list returns every scalar column.
Sourcepub fn compile_delete(self) -> Result<DeleteQuery, QueryError>
pub fn compile_delete(self) -> Result<DeleteQuery, QueryError>
Lower this queryset to a DeleteQuery — same WHERE clause, no projection.
limit / offset / order_by bound it by primary key.
§Errors
As QuerySet::compile, plus QueryError::BoundedDmlUnsupported
when a limit or offset cannot be bounded.
Sourcepub fn update(self) -> UpdateBuilder<T>
pub fn update(self) -> UpdateBuilder<T>
Start an UpdateBuilder carrying this queryset’s filters as the WHERE clause.
Sourcepub fn aggregate(self) -> AggregateBuilder<T>
pub fn aggregate(self) -> AggregateBuilder<T>
Start an AggregateBuilder carrying this queryset’s filters as the
WHERE clause. Chain .group_by, .annotate, .having, .order_by,
.limit, .offset then call .compile() to get an AggregateQuery.
Sourcepub fn values(self, columns: &[&'static str]) -> AggregateBuilder<T>
pub fn values(self, columns: &[&'static str]) -> AggregateBuilder<T>
Group by the named columns.
Switches the queryset into aggregate mode and records the
projection columns. Followed by .annotate("alias", aggregate),
it emits SELECT cols, AGGR(...) FROM t GROUP BY cols; the
GROUP BY comes from the values list.
This is shape 2 in the cheat-sheet on Self::annotate.
The same IR gives equivalent SQL on Postgres, MySQL and SQLite.
// "Posts per author".
Post::objects()
.values(&["author_id"])
.annotate("n", count_all().into())
.compile()?;
// → SELECT "author_id", COUNT(*) AS "n" FROM "post" GROUP BY "author_id"Filtering by an .annotate() alias routes to HAVING; filtering
by a model column routes to WHERE:
// Authors with > 5 published posts.
Post::objects()
.values(&["author_id"])
.annotate("n", count_all().into())
.filter("status", Op::Eq, "published") // → WHERE
.filter("n", Op::Gt, 5_i64) // → HAVING
.compile()?;Calling .values() without a subsequent aggregating .annotate(...)
is shape 1 — a pure projection, with no GROUP BY emitted.
Sourcepub fn annotate(
self,
alias: &'static str,
expr: AggregateExpr,
) -> AggregateBuilder<T>
pub fn annotate( self, alias: &'static str, expr: AggregateExpr, ) -> AggregateBuilder<T>
Add a derived column without calling .aggregate().
Promotes to an AggregateBuilder. If the annotation
aggregates rows (Count, Sum, Avg, …) and you did not call
.values(), compile() fills GROUP BY with every
non-aggregate scalar column. This is shape 3: each row plus
a derived aggregate over its children.
// "Each author + their post count" — every column of `Author`
// ends up in the SELECT list AND in GROUP BY.
Author::objects()
.annotate("post_count", count_all().into())
.compile()?;§Projection cheat-sheet
| Shape | Call site | GROUP BY |
|---|---|---|
| 1 | .values_dict(&[cols]) | (none) |
| 2 | .values(&[cols]).annotate(alias, agg) | the values cols |
| 3 | .annotate(alias, agg) (alone) | every scalar |
Sourcepub fn annotate_subquery(
self,
alias: &'static str,
inner: SelectQuery,
) -> AggregateBuilder<T>
pub fn annotate_subquery( self, alias: &'static str, inner: SelectQuery, ) -> AggregateBuilder<T>
Project a correlated scalar subquery under alias, promoting to
an AggregateBuilder.
Shorthand for Self::annotate with
crate::core::subquery::scalar_subquery. inner must return
one column and at most one row. Correlate it with
crate::core::subquery::outer_ref.
Source§impl<T: Model> QuerySet<T>
impl<T: Model> QuerySet<T>
Sourcepub fn dates(self, field: &'static str, kind: DateKind) -> DatesQuerySet<T>
pub fn dates(self, field: &'static str, kind: DateKind) -> DatesQuerySet<T>
The distinct date values of field, truncated to kind.
Output is ascending by default, oldest first. Chain
DatesQuerySet::order_desc for newest first.
Filters, joins and limits on the queryset still apply, so
.filter(...).dates(...) only sees matching rows.
Sourcepub fn datetimes(
self,
field: &'static str,
kind: DateTimeKind,
) -> DateTimesQuerySet<T>
pub fn datetimes( self, field: &'static str, kind: DateTimeKind, ) -> DateTimesQuerySet<T>
The distinct datetime values of field, truncated to kind.
Finer than Self::dates: as well as Year, Month and
Day, it takes Hour, Minute and Second. Each value is a
DateTime<Utc> at the truncated instant.
Source§impl<T: Model> QuerySet<T>
impl<T: Model> QuerySet<T>
Sourcepub async fn pluck<U>(
self,
col: &'static str,
pool: &Pool,
) -> Result<Vec<U>, ExecError>where
U: FlatScalar,
pub async fn pluck<U>(
self,
col: &'static str,
pool: &Pool,
) -> Result<Vec<U>, ExecError>where
U: FlatScalar,
Read one column from the matching rows into a Vec<U>.
let titles: Vec<String> = Post::objects()
.filter("published", true)
.pluck::<String>("title", &pool).await?;U is a FlatScalar: i64, String, bool, f64 and the
like, or Option<_> of one for a nullable column. Unlike Model::pluck, this respects the queryset’s
filters, ordering and limits.
§Errors
Sourcepub async fn pks<K>(self, pool: &Pool) -> Result<Vec<K>, ExecError>where
K: FlatScalar,
pub async fn pks<K>(self, pool: &Pool) -> Result<Vec<K>, ExecError>where
K: FlatScalar,
Self::pluck of the primary key, whose name comes from the
model’s schema so the call site need not repeat it.
let ids: Vec<i64> = Post::objects()
.filter("published", true)
.pks::<i64>(&pool).await?;§Errors
[ExecError::Query(QueryError::UnknownField)] when the model
has no primary key, otherwise as Self::pluck.
Sourcepub async fn pluck_pairs<K, V>(
self,
key_col: &'static str,
value_col: &'static str,
pool: &Pool,
) -> Result<Vec<(K, V)>, ExecError>where
K: FlatScalar,
V: FlatScalar,
pub async fn pluck_pairs<K, V>(
self,
key_col: &'static str,
value_col: &'static str,
pool: &Pool,
) -> Result<Vec<(K, V)>, ExecError>where
K: FlatScalar,
V: FlatScalar,
Read two columns from the matching rows into Vec<(K, V)>.
Collect it into a map at the call site if you want lookups.
The key column comes first, matching the tuple.
let pairs: Vec<(i64, String)> = Post::objects()
.filter("published", true)
.pluck_pairs::<i64, String>("id", "title", &pool).await?;
let map: std::collections::BTreeMap<_, _> = pairs.into_iter().collect();§Errors
As crate::sql::FetcherPool::fetch, plus a decode error
when K or V does not match its column’s type.
Sourcepub async fn value<U>(
self,
col: &'static str,
pool: &Pool,
) -> Result<Option<U>, ExecError>where
U: FlatScalar,
pub async fn value<U>(
self,
col: &'static str,
pool: &Pool,
) -> Result<Option<U>, ExecError>where
U: FlatScalar,
Read one column from the first matching row, or None when
nothing matches. The query carries LIMIT 1, so the database
does not build rows you will not read.
let email: Option<String> = User::objects()
.filter("id", 1_i64)
.value::<String>("email", &pool).await?;Unlike Model::value, this respects the queryset’s filters
and ordering when picking the row.
§Errors
Sourcepub fn to_sql(self, pool: &Pool) -> Result<String, ExecError>
pub fn to_sql(self, pool: &Pool) -> Result<String, ExecError>
Render this queryset to SQL in the pool’s dialect, without running it. Handy for debugging, logging and snapshot tests.
The string holds placeholders, not the bound values. Use
Self::to_compiled when you need those too.
let sql = Post::objects()
.filter("published", true)
.order_by(&[("created_at", true)])
.limit(10)
.to_sql(&pool)?;
// -> "SELECT … FROM \"post\" WHERE \"published\" = $1 …"§Errors
ExecError::Query when the queryset fails to compile, and
ExecError::Sql from the dialect’s writer.
Sourcepub async fn sum<U>(
self,
col: &str,
pool: &Pool,
) -> Result<Option<U>, ExecError>
pub async fn sum<U>( self, col: &str, pool: &Pool, ) -> Result<Option<U>, ExecError>
SELECT SUM(col) over the matching rows, or Ok(None) when
none match. Model::sum is this over the default queryset.
§Errors
As crate::sql::fetch_aggregate_pool, plus
[ExecError::Query(QueryError::UnknownField)] when the model
has no such column.
Sourcepub async fn paginate(
self,
page: i64,
per_page: i64,
pool: &Pool,
) -> Result<(Vec<T>, i64), ExecError>where
T: Model + MaybePgFromRow + MaybeMyFromRow + MaybeSqliteFromRow + LoadRelated + MaybeMyLoadRelated + MaybeSqliteLoadRelated + Send + Unpin,
pub async fn paginate(
self,
page: i64,
per_page: i64,
pool: &Pool,
) -> Result<(Vec<T>, i64), ExecError>where
T: Model + MaybePgFromRow + MaybeMyFromRow + MaybeSqliteFromRow + LoadRelated + MaybeMyLoadRelated + MaybeSqliteLoadRelated + Send + Unpin,
Fetch one page of rows and the matching total, as
(rows, total). Unlike Model::paginate, the total counts
only rows the queryset’s filters match.
It runs two queries, a COUNT(*) and the page itself, both
with the same WHERE clause.
page starts at 1, so paginate(1, 10) gives the first ten
rows and paginate(2, 10) the next ten. An unordered queryset
pages in PK order.
§Errors
As crate::sql::CounterPool::count and
crate::sql::FetcherPool::fetch.
Sourcepub fn to_compiled(self, pool: &Pool) -> Result<CompiledStatement, ExecError>
pub fn to_compiled(self, pool: &Pool) -> Result<CompiledStatement, ExecError>
Self::to_sql plus the bound parameters, as a
crate::sql::CompiledStatement.
§Errors
As Self::to_sql.
Source§impl<T> QuerySet<T>where
T: Model + Send + Unpin + MaybePgFromRow + MaybeMyFromRow + MaybeSqliteFromRow + LoadRelated + MaybeMyLoadRelated + MaybeSqliteLoadRelated,
impl<T> QuerySet<T>where
T: Model + Send + Unpin + MaybePgFromRow + MaybeMyFromRow + MaybeSqliteFromRow + LoadRelated + MaybeMyLoadRelated + MaybeSqliteLoadRelated,
Sourcepub async fn increment(
self,
col: &str,
by: i64,
pool: &Pool,
) -> Result<u64, ExecError>
pub async fn increment( self, col: &str, by: i64, pool: &Pool, ) -> Result<u64, ExecError>
UPDATE … SET col = col + by over the matching rows.
Returns the number of rows affected. Unlike
Model::increment_each, this respects the queryset’s
filters, so you can bump a counter on some rows only.
A negative by subtracts; Self::decrement reads better
at the call site.
Post::objects()
.filter("published", true)
.increment("views", 1, &pool)
.await?;§Errors
As UpdaterPool::execute_pool,
plus ExecError::Query with QueryError::UnknownField when
col is not a declared field on T.
Source§impl<T> QuerySet<T>where
T: Model + MaybePgFromRow + MaybeMyFromRow + MaybeSqliteFromRow + LoadRelated + MaybeMyLoadRelated + MaybeSqliteLoadRelated + Send + Unpin,
impl<T> QuerySet<T>where
T: Model + MaybePgFromRow + MaybeMyFromRow + MaybeSqliteFromRow + LoadRelated + MaybeMyLoadRelated + MaybeSqliteLoadRelated + Send + Unpin,
Sourcepub async fn get_or_create<F, Fut>(
self,
create_fn: F,
pool: &Pool,
) -> Result<(T, bool), ExecError>
pub async fn get_or_create<F, Fut>( self, create_fn: F, pool: &Pool, ) -> Result<(T, bool), ExecError>
Chainable form of get_or_create. Sugar for
get_or_create(self, create_fn, pool) so call sites read as
Post::objects().filter(...).get_or_create(|pool| ..., &pool).
Returns (row, created) where created is true when the
closure was invoked.
§Errors
As get_or_create.
Sourcepub async fn first_or_create<F, Fut>(
self,
create_fn: F,
pool: &Pool,
) -> Result<(T, bool), ExecError>
pub async fn first_or_create<F, Fut>( self, create_fn: F, pool: &Pool, ) -> Result<(T, bool), ExecError>
Eloquent Model::firstOrCreate($attributes, $values) alias
for Self::get_or_create. Identical semantics; the
separate name keeps Laravel muscle-memory call sites
readable.
§Errors
Sourcepub async fn update_or_create<UF, UFut, CF, CFut>(
self,
update_fn: UF,
create_fn: CF,
pool: &Pool,
) -> Result<(T, bool), ExecError>
pub async fn update_or_create<UF, UFut, CF, CFut>( self, update_fn: UF, create_fn: CF, pool: &Pool, ) -> Result<(T, bool), ExecError>
Chainable form of update_or_create. Sugar for
update_or_create(self, update_fn, create_fn, pool).
Returns (row, created) where created is true when the
create_fn closure was invoked (i.e. no row matched the
queryset).
§Errors
As update_or_create.
Source§impl<T> QuerySet<T>
impl<T> QuerySet<T>
Sourcepub async fn fetch_on<'c, E>(self, executor: E) -> Result<Vec<T>, ExecError>
pub async fn fetch_on<'c, E>(self, executor: E) -> Result<Vec<T>, ExecError>
Like FetcherPool::fetch but takes any sqlx executor:
&PgPool, &mut PgConnection, or a Transaction.
Use this for tenant-scoped queries. Schema-mode tenants share
the registry pool and rely on a per-checkout SET search_path,
so a plain &PgPool would quietly read the wrong schema.
Get a connection from TenantPools::acquire(&org) instead.
§Errors
Sourcepub async fn fetch_paginated_on<'c, E>(
self,
executor: E,
) -> Result<Page<T>, ExecError>
pub async fn fetch_paginated_on<'c, E>( self, executor: E, ) -> Result<Page<T>, ExecError>
Fetch a page of rows and the total matching count in one
round trip. COUNT(*) OVER () returns the pre-LIMIT total on
every row, so there is no second SELECT COUNT(*).
let page: Page<Post> = Post::objects()
.where_(Post::published.eq(true))
.limit(20).offset(40)
.fetch_paginated_on(tenant.conn()).await?;
assert!(page.total >= page.rows.len() as i64);SQL emitted (abridged):
SELECT id, title, ..., COUNT(*) OVER () AS "__rustango_total"
FROM post WHERE ...
ORDER BY ... LIMIT 20 OFFSET 40An empty result gives Page { rows: vec![], total: 0 }.
§Errors
As Self::fetch_on.
Sourcepub async fn in_bulk_on<'c, E, C, K, I, F>(
self,
column: C,
ids: I,
extract: F,
executor: E,
) -> Result<HashMap<K, T>, ExecError>
pub async fn in_bulk_on<'c, E, C, K, I, F>( self, column: C, ids: I, extract: F, executor: E, ) -> Result<HashMap<K, T>, ExecError>
QuerySet::in_bulk against any sqlx executor, so schema-mode
tenant queries can use the connection that holds their
SET search_path.
§Errors
As Self::fetch_on.
Source§impl<T: Model + Send> QuerySet<T>
impl<T: Model + Send> QuerySet<T>
Sourcepub async fn count_on<'c, E>(self, executor: E) -> Result<i64, ExecError>
pub async fn count_on<'c, E>(self, executor: E) -> Result<i64, ExecError>
Count rows matching this queryset’s filters. Takes any sqlx
executor, like Self::fetch_on.
§Errors
Returns ExecError for schema, SQL-writing, or driver failures.
Sourcepub async fn explain(self, pool: &PgPool) -> Result<Vec<String>, ExecError>
pub async fn explain(self, pool: &PgPool) -> Result<Vec<String>, ExecError>
Run EXPLAIN on this queryset and return the plan, one line
per Vec entry. Runs against a pool with the default options:
plain EXPLAIN, no ANALYZE, so the query itself is not run.
Use Self::explain_on to pick the executor and options.
use rustango::sql::ExplainOptions;
let plan = Post::objects()
.where_(Post::author_id.eq(7_i64))
.explain(&pool)
.await?;
for line in plan { println!("{line}"); }§Errors
SQL-writing or driver failures from the EXPLAIN.
Sourcepub async fn explain_on<'c, E>(
self,
executor: E,
options: ExplainOptions,
) -> Result<Vec<String>, ExecError>
pub async fn explain_on<'c, E>( self, executor: E, options: ExplainOptions, ) -> Result<Vec<String>, ExecError>
Self::explain with your own executor and ExplainOptions.
analyze = true really runs the query, side effects included,
so it is opt-in.
§Errors
As Self::explain.
Source§impl<T: Model + Send> QuerySet<T>
impl<T: Model + Send> QuerySet<T>
Source§impl<T> QuerySet<T>where
T: Model + MaybePgFromRow + MaybeMyFromRow + MaybeSqliteFromRow + LoadRelated + MaybeMyLoadRelated + MaybeSqliteLoadRelated + Send + Unpin,
impl<T> QuerySet<T>where
T: Model + MaybePgFromRow + MaybeMyFromRow + MaybeSqliteFromRow + LoadRelated + MaybeMyLoadRelated + MaybeSqliteLoadRelated + Send + Unpin,
Sourcepub async fn first(self, pool: &Pool) -> Result<Option<T>, ExecError>
pub async fn first(self, pool: &Pool) -> Result<Option<T>, ExecError>
Fetch the first row by the current ordering, or None when
nothing matches. With no order_by, it sorts by primary key
ASC, so the result is stable.
§Errors
Sourcepub async fn last(self, pool: &Pool) -> Result<Option<T>, ExecError>
pub async fn last(self, pool: &Pool) -> Result<Option<T>, ExecError>
Fetch the last row by the current ordering, or None when
nothing matches. It flips every sort direction and takes the
first row, so no OFFSET COUNT(*) - 1 is needed. With no
order_by, it sorts by primary key DESC.
§Errors
Sourcepub async fn earliest(
self,
field: &str,
pool: &Pool,
) -> Result<Option<T>, ExecError>
pub async fn earliest( self, field: &str, pool: &Pool, ) -> Result<Option<T>, ExecError>
Fetch the smallest row by field, or None when nothing
matches. It replaces any order_by already set.
§Errors
Sourcepub async fn latest(
self,
field: &str,
pool: &Pool,
) -> Result<Option<T>, ExecError>
pub async fn latest( self, field: &str, pool: &Pool, ) -> Result<Option<T>, ExecError>
Fetch the largest row by field, or None when nothing
matches. It replaces any order_by already set.
§Errors
Sourcepub async fn find(
self,
pk: impl Into<SqlValue>,
pool: &Pool,
) -> Result<Option<T>, ExecError>
pub async fn find( self, pk: impl Into<SqlValue>, pool: &Pool, ) -> Result<Option<T>, ExecError>
Fetch the row with this PK that also matches the queryset’s
filters, or None. Unlike Model::find(pk, &pool), the
filters already on the queryset still apply.
let post = Post::objects()
.filter("published", true)
.find(42_i64, &pool).await?;
// Some(post) only when row 42 is also published.A model with no primary key gives
[ExecError::Query(QueryError::UnknownField)].
§Errors
Sourcepub async fn first_or_fail(self, pool: &Pool) -> Result<T, ExecError>
pub async fn first_or_fail(self, pool: &Pool) -> Result<T, ExecError>
Self::first, but an empty result is an error instead of
None. The queryset’s filters still apply, so it fails only
when nothing matches them.
§Errors
As Self::first; additionally
[ExecError::Driver(sqlx::Error::RowNotFound)] when the
queryset returns no rows.
Sourcepub async fn find_or_fail(
self,
pk: impl Into<SqlValue>,
pool: &Pool,
) -> Result<T, ExecError>
pub async fn find_or_fail( self, pk: impl Into<SqlValue>, pool: &Pool, ) -> Result<T, ExecError>
Self::find, but a miss is an error instead of None.
let post = Post::objects()
.filter("published", true)
.find_or_fail(42_i64, &pool).await?;
// -> Ok(post) when row 42 is published;
// Err(RowNotFound) when missing or not published.§Errors
Sourcepub async fn sole(self, pool: &Pool) -> Result<T, ExecError>
pub async fn sole(self, pool: &Pool) -> Result<T, ExecError>
Fetch the one row matching this queryset. It is an error if
no row matches (sqlx::Error::RowNotFound) or if more than
one does (ExecError::MultipleRowsReturned). Uses LIMIT 2,
so it does not scan the whole result.
let post = Post::objects()
.filter("slug", "hello-world".to_string())
.sole(&pool).await?;§Errors
As FetcherPool::fetch; additionally
[ExecError::Driver(sqlx::Error::RowNotFound)] on empty
result, ExecError::MultipleRowsReturned on >1 matches.
Sourcepub async fn latest_default(self, pool: &Pool) -> Result<Option<T>, ExecError>
pub async fn latest_default(self, pool: &Pool) -> Result<Option<T>, ExecError>
The largest row by the column in
#[rustango(get_latest_by = "<col>")]. Use Self::latest
to name the field yourself.
§Errors
As FetcherPool::fetch; also an error when the model does
not declare get_latest_by.
Sourcepub fn iterator(self, chunk_size: i64) -> Result<ChunkedIter<T>, QueryError>
pub fn iterator(self, chunk_size: i64) -> Result<ChunkedIter<T>, QueryError>
Read the results
chunk_size rows at a time with LIMIT N OFFSET M, so a huge
export never has to fit in memory. The queryset is compiled
here, so a schema error surfaces before the first chunk.
// Two iteration styles, both work:
let mut iter = Post::objects()
.where_(Post::published.eq(true))
.order_by(&[("id", false)])
.iterator(2_000)?;
// 1. Whole-chunk loop:
while let Some(chunk) = iter.next_chunk(&pool).await? {
for post in chunk { /* … */ }
}
// 2. Row-by-row loop (buffer one chunk internally):
while let Some(post) = iter.next_row(&pool).await? {
/* … */
}Set an order. Without a stable sort, OFFSET returns
unpredictable rows across chunks. Call
.order_by(&[("pk", …)]) first. This is not enforced, since
some drains do not care about order.
Cost. Each chunk re-runs the query with a larger offset,
and the database scans the skipped rows every time, so deep
paging does O(n²) work. For real streaming on Postgres, use
transaction() with sqlx’s fetch(...) Stream API. This
chunker is the simple option that works on every backend.
Writes can skew the result. Each chunk is its own query,
so a row inserted ahead of the offset can be missed, and a
delete can shift a row into the next chunk and return it
twice. The chunker only takes a &Pool, never a transaction.
On a table other writers touch, write the LIMIT/OFFSET loop
yourself against select_rows_on inside a repeatable-read
transaction. Read-only or append-only tables are fine.
select_for_update() is lost. Each chunk runs in its own
implicit transaction, so row locks are released between
chunks. For a locked drain, either use .fetch_on(&mut *tx)
when the result fits in memory, or run your own LIMIT/OFFSET
loop inside the transaction.
§Errors
QueryError if the queryset fails
to compile.
§Panics
If chunk_size <= 0. Such a size would silently yield no
rows, which is almost always a bug.
Sourcepub async fn in_bulk<C, K, I, F>(
self,
column: C,
ids: I,
extract: F,
pool: &Pool,
) -> Result<HashMap<K, T>, ExecError>
pub async fn in_bulk<C, K, I, F>( self, column: C, ids: I, extract: F, pool: &Pool, ) -> Result<HashMap<K, T>, ExecError>
Fetch rows
by a list of column values and return them in a HashMap
keyed by that column.
column is a typed crate::core::Column, so the compiler
checks it against the model. The SQL becomes
… WHERE <column> IN (…). extract reads the key off each
fetched row, which also lets you choose how to unwrap
Auto<T> or ForeignKey<T, K>.
An empty ids returns an empty map and runs no SQL.
use std::collections::HashMap;
use rustango::sql::Auto;
// Keyed by the Auto<i64> PK. A fetched row is always Set.
let books: HashMap<i64, Book> = Book::objects()
.in_bulk(Book::id, [1_i64, 2, 3], |b| match b.id {
Auto::Set(v) => v,
Auto::Unset => unreachable!("fetched row has PK"),
}, &pool)
.await?;
// Or key by any other unique column.
let books_by_isbn: HashMap<String, Book> = Book::objects()
.in_bulk(Book::isbn, ["isbn-1", "isbn-2"], |b| b.isbn.clone(), &pool)
.await?;If two rows share a key, which only happens on a non-unique column, the later row wins. Prefer a unique column.
§Errors
Trait Implementations§
Source§impl<T: Model + Send> ExistsPool<T> for QuerySet<T>
impl<T: Model + Send> ExistsPool<T> for QuerySet<T>
Source§async fn exists(self, pool: &Pool) -> Result<bool, ExecError>
async fn exists(self, pool: &Pool) -> Result<bool, ExecError>
Ok(true) when at least one row matches the queryset’s
filters. Read moreSource§async fn is_empty(self, pool: &Pool) -> Result<bool, ExecError>
async fn is_empty(self, pool: &Pool) -> Result<bool, ExecError>
Ok(true) when the queryset matches no rows. The inverse of
Self::exists, easier to read than !qs.exists(..).await?. Read moreSource§impl<T> FetcherPool<T> for QuerySet<T>where
T: Model + MaybePgFromRow + MaybeMyFromRow + MaybeSqliteFromRow + LoadRelated + MaybeMyLoadRelated + MaybeSqliteLoadRelated + Send + Unpin,
impl<T> FetcherPool<T> for QuerySet<T>where
T: Model + MaybePgFromRow + MaybeMyFromRow + MaybeSqliteFromRow + LoadRelated + MaybeMyLoadRelated + MaybeSqliteLoadRelated + Send + Unpin,
Source§impl<T> FetcherTx<T> for QuerySet<T>where
T: Model + MaybePgFromRow + MaybeMyFromRow + MaybeSqliteFromRow + LoadRelated + MaybeMyLoadRelated + MaybeSqliteLoadRelated + Send + Unpin,
impl<T> FetcherTx<T> for QuerySet<T>where
T: Model + MaybePgFromRow + MaybeMyFromRow + MaybeSqliteFromRow + LoadRelated + MaybeMyLoadRelated + MaybeSqliteLoadRelated + Send + Unpin,
Auto Trait Implementations§
impl<T> Freeze for QuerySet<T>
impl<T> RefUnwindSafe for QuerySet<T>
impl<T> Send for QuerySet<T>
impl<T> Sync for QuerySet<T>
impl<T> Unpin for QuerySet<T>
impl<T> UnsafeUnpin for QuerySet<T>
impl<T> UnwindSafe for QuerySet<T>
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<A, B, T> HttpServerConnExec<A, B> for Twhere
B: Body,
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