pub struct QueryBuilder<T> { /* private fields */ }Expand description
Laravel-shaped query builder (Post::query().where_eq(...).latest(...))
over sqlx. Column names passed in (Post::TITLE) are &'static str
constants generated by #[derive(Model)], never user input, so they’re
interpolated directly into the SQL string; bound values always go
through placeholders - never string-formatted into the query.
Implementations§
Source§impl<T> QueryBuilder<T>
Known gap: a bool-typed field on a #[derive(Model, sqlx::FromRow)]
struct doesn’t decode through AnyRow on SQLite. SQLite has no native
boolean column type (it stores 0/1 as an INTEGER); the concrete
sqlx::Sqlite driver knows to coerce that into bool, but sqlx’s
backend-agnostic Any driver tags the column as its own generic
BigInt kind instead and refuses the conversion (confirmed
empirically: decoding fails with “Rust type bool is not compatible
with SQL type BIGINT” - MySQL’s own Any adapter doesn’t have this
problem, since MySQL’s TINYINT(1)/BOOLEAN gets tagged correctly).
No current app model in this workspace has a bool field, so this
hasn’t needed a real fix yet - if one ever does, decode the column as
i64 and compare != 0 by hand instead (see
larust-permissions::has_role/has_permission_to for the exact
pattern, needed for their own SELECT EXISTS(...) queries).
impl<T> QueryBuilder<T>
Known gap: a bool-typed field on a #[derive(Model, sqlx::FromRow)]
struct doesn’t decode through AnyRow on SQLite. SQLite has no native
boolean column type (it stores 0/1 as an INTEGER); the concrete
sqlx::Sqlite driver knows to coerce that into bool, but sqlx’s
backend-agnostic Any driver tags the column as its own generic
BigInt kind instead and refuses the conversion (confirmed
empirically: decoding fails with “Rust type bool is not compatible
with SQL type BIGINT” - MySQL’s own Any adapter doesn’t have this
problem, since MySQL’s TINYINT(1)/BOOLEAN gets tagged correctly).
No current app model in this workspace has a bool field, so this
hasn’t needed a real fix yet - if one ever does, decode the column as
i64 and compare != 0 by hand instead (see
larust-permissions::has_role/has_permission_to for the exact
pattern, needed for their own SELECT EXISTS(...) queries).
A second, more consequential known gap in the same family: a
String-typed field backed by a MySQL TEXT (or TINYTEXT/
MEDIUMTEXT/LONGTEXT) column doesn’t decode through Any at all,
on any app model - not just framework-internal ones. Confirmed
empirically against a real MySQL server: sqlx-mysql’s own Any
adapter maps every one of those column types to its own generic
Blob kind unconditionally (it keys off the wire-protocol
ColumnType alone, which doesn’t distinguish TEXT from BLOB the way
the column’s actual charset does), and Decode<Any> for String only
ever accepts Text-kind values - decoding fails with “Rust type
String is not compatible with SQL type BLOB”. Only CHAR/
VARCHAR map to Any’s Text kind. A MySQL-targeted app’s own
migrations need VARCHAR(n) for any column a model reads back as
String, not TEXT - every framework-owned table with its own
bootstrap SQL (larust-http::session’s sessions.data,
larust-cache’s cache_items.value, larust-queue’s jobs.payload/
failed_jobs.error, larust-notifications’s notifications.data/
notification_type, larust-sanctum’s personal_access_tokens.name)
already had to make this exact switch, each landing on a generous but
bounded VARCHAR(4000) (kept well under MySQL’s ~65,535-byte
combined-row-size limit even at utf8mb4’s worst-case 4 bytes/char,
confirmed empirically against a real server - VARCHAR(16383) alone
already exceeds it once more than one such column shares a row).
There is no known workaround for genuinely unbounded content (a long
blog post body, say) beyond raising that cap and accepting the
row-size math, or waiting for an upstream sqlx fix - MySQL/Any
support in this framework is not a byte-for-byte drop-in replacement
for SQLite’s own effectively-unlimited TEXT in that one specific
respect.
Postgres has neither gap - confirmed empirically against a real
server, not just inferred from its type system. A native BOOLEAN
column decodes straight into bool through Any with no i64
workaround needed, and a TEXT column of several thousand characters
decodes straight into String with no VARCHAR(n) cap needed -
Postgres’s own Any adapter tags both correctly (Bool/Text kind),
unlike SQLite’s/MySQL’s own adapters. Every framework-owned table’s
Postgres arm (see larust-cache/larust-queue/larust-sanctum/
larust-notifications/larust-http::session) uses plain TEXT, not
a MySQL-style VARCHAR(4000) cap, on the strength of this.
pub fn new(table: &'static str) -> Self
pub fn where_eq(self, column: &'static str, value: impl Into<BindValue>) -> Self
Sourcepub fn where_op(
self,
column: &'static str,
op: Op,
value: impl Into<BindValue>,
) -> Self
pub fn where_op( self, column: &'static str, op: Op, value: impl Into<BindValue>, ) -> Self
WHERE column <op> value (Laravel’s 3-argument ->where(...)) -
for comparisons where_eq can’t express (!=, >, >=, <,
<=, LIKE).
Sourcepub fn where_null(self, column: &'static str) -> Self
pub fn where_null(self, column: &'static str) -> Self
WHERE column IS NULL.
Sourcepub fn where_not_null(self, column: &'static str) -> Self
pub fn where_not_null(self, column: &'static str) -> Self
WHERE column IS NOT NULL.
Sourcepub fn where_in<V: Into<BindValue>>(
self,
column: &'static str,
values: Vec<V>,
) -> Self
pub fn where_in<V: Into<BindValue>>( self, column: &'static str, values: Vec<V>, ) -> Self
WHERE column IN (values...) (Laravel’s ->whereIn(...)) - used by
relationship batch loaders (load_*, see larust-macros’
relations.rs) to fetch every related row for a whole batch of
already-loaded rows in one query instead of one query per row.
values empty is a real case (batch-loading relations for an empty
input slice), not just a hypothetical - rendering treats it as a
condition that matches nothing (1=0), since "col" IN () is
invalid SQL in SQLite (a syntax error, not an empty-result query).
Sourcepub fn or_where_eq(
self,
column: &'static str,
value: impl Into<BindValue>,
) -> Self
pub fn or_where_eq( self, column: &'static str, value: impl Into<BindValue>, ) -> Self
OR column = value.
Sourcepub fn or_where_op(
self,
column: &'static str,
op: Op,
value: impl Into<BindValue>,
) -> Self
pub fn or_where_op( self, column: &'static str, op: Op, value: impl Into<BindValue>, ) -> Self
OR column <op> value.
Sourcepub fn or_where_in<V: Into<BindValue>>(
self,
column: &'static str,
values: Vec<V>,
) -> Self
pub fn or_where_in<V: Into<BindValue>>( self, column: &'static str, values: Vec<V>, ) -> Self
OR column IN (values...).
Sourcepub fn or_where_null(self, column: &'static str) -> Self
pub fn or_where_null(self, column: &'static str) -> Self
OR column IS NULL.
Sourcepub fn where_group(self, f: impl FnOnce(Self) -> Self) -> Self
pub fn where_group(self, f: impl FnOnce(Self) -> Self) -> Self
A parenthesized AND (...) group - f receives an empty builder
over this same table and whatever conditions it adds (via its own
return value) become the group’s contents; nothing else about the
builder f receives (table/order/limit) is used. Exists so an
OR added inside the group doesn’t leak out and change the
precedence of conditions already on self - see scope’s own doc
comment for the same concern, solved automatically there.
Sourcepub fn or_where_group(self, f: impl FnOnce(Self) -> Self) -> Self
pub fn or_where_group(self, f: impl FnOnce(Self) -> Self) -> Self
OR (...) - see where_group.
Sourcepub fn scope(self, f: impl FnOnce(Self) -> Self) -> Self
pub fn scope(self, f: impl FnOnce(Self) -> Self) -> Self
A reusable, named WHERE preset (Eloquent’s local scopes), e.g.:
impl Post {
pub fn published(q: QueryBuilder<Self>) -> QueryBuilder<Self> {
q.where_not_null(Self::PUBLISHED_AT)
}
}
Post::query().scope(Post::published).latest(Post::ID).get().await?;Unlike where_group, a scope’s own conditions are only wrapped in
a parenthesized group when they actually contain an OR - an
all-AND scope body is flattened directly into self instead,
since plain ANDs are associative with whatever else is on
self and don’t need the parens. This is specifically what
prevents the classic Eloquent scope-precedence leak: a scope whose
own body uses OR (Post::recent_or_pinned, say) can be combined
with other conditions on self without that internal OR
silently changing what the rest of the query matches.
Sourcepub fn where_in_query<U>(
self,
column: &'static str,
sub_column: &'static str,
sub: QueryBuilder<U>,
) -> Self
pub fn where_in_query<U>( self, column: &'static str, sub_column: &'static str, sub: QueryBuilder<U>, ) -> Self
WHERE column IN (SELECT sub_column FROM ... [WHERE ...]) - a
subquery filter against a different model’s table, built from
sub’s own current state (table + whatever where_* it’s already
chained) - its own conditions, not self’s, become the
subquery’s WHERE clause. See Condition::InQuery’s own doc
comment for why this is a subquery, not a real JOIN.
Sourcepub fn latest(self, column: &'static str) -> Self
pub fn latest(self, column: &'static str) -> Self
Orders by column descending (Laravel’s ->latest($column)).
Each call adds a sort key rather than replacing the last one -
matching Eloquent’s own ->orderBy(...) chaining.
Sourcepub fn oldest(self, column: &'static str) -> Self
pub fn oldest(self, column: &'static str) -> Self
Orders by column ascending (Laravel’s ->oldest($column)).
Sourcepub fn order_by(self, column: &'static str, direction: Order) -> Self
pub fn order_by(self, column: &'static str, direction: Order) -> Self
->orderBy($column, $direction) - latest/oldest are sugar for
this with a fixed direction.
Sourcepub fn limit(self, n: i64) -> Self
pub fn limit(self, n: i64) -> Self
Caps the number of rows returned, independent of paginate (which
sets this internally). No public .offset() yet - SQLite/MySQL/
Postgres disagree on whether OFFSET needs a LIMIT alongside it
(MySQL requires one; Postgres doesn’t), and nothing in this
codebase needs offset-without-limit yet to justify picking one of
the backend-specific workarounds.
Sourcepub async fn paginate(self, per_page: i64) -> Result<Vec<T>, AppError>
pub async fn paginate(self, per_page: i64) -> Result<Vec<T>, AppError>
A stand-in for Laravel’s ->paginate($perPage) - limits to
per_page rows. Page-number/metadata support (current page, total
count, links) is a later addition; for now this is equivalent to
.limit(per_page).get().
pub async fn get(self) -> Result<Vec<T>, AppError>
Sourcepub async fn get_on(self, database: &AnyPool) -> Result<Vec<T>, AppError>
pub async fn get_on(self, database: &AnyPool) -> Result<Vec<T>, AppError>
Executes this query against an explicit pool. This is the preferred
building block for applications moving away from process-wide ORM
state, while get() remains compatible with existing models.
pub async fn first(self) -> Result<Option<T>, AppError>
pub async fn first_on(self, database: &AnyPool) -> Result<Option<T>, AppError>
pub async fn count(self) -> Result<i64, AppError>
pub async fn count_on(self, database: &AnyPool) -> Result<i64, AppError>
pub async fn exists(self) -> Result<bool, AppError>
Source§impl<T> QueryBuilder<T>
impl<T> QueryBuilder<T>
Sourcepub fn with_trashed(self) -> Self
pub fn with_trashed(self) -> Self
Includes soft-deleted rows alongside normal ones (Eloquent’s
withTrashed()).
Sourcepub fn only_trashed(self) -> Self
pub fn only_trashed(self) -> Self
Only soft-deleted rows (Eloquent’s onlyTrashed()).
Auto Trait Implementations§
impl<T> Forget for QueryBuilder<T>
impl<T> Freeze for QueryBuilder<T>
impl<T> Move for QueryBuilder<T>
impl<T> RefUnwindSafe for QueryBuilder<T>
impl<T> Send for QueryBuilder<T>
impl<T> Sync for QueryBuilder<T>
impl<T> Unpin for QueryBuilder<T>
impl<T> UnsafeUnpin for QueryBuilder<T>
impl<T> UnwindSafe for QueryBuilder<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
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