Skip to main content

QueryBuilder

Struct QueryBuilder 

Source
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>
where T: for<'r> FromRow<'r, AnyRow> + Send + Unpin,

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.

Source

pub fn new(table: &'static str) -> QueryBuilder<T>

Source

pub fn where_eq( self, column: &'static str, value: impl Into<BindValue>, ) -> QueryBuilder<T>

Source

pub fn where_op( self, column: &'static str, op: Op, value: impl Into<BindValue>, ) -> QueryBuilder<T>

WHERE column <op> value (Laravel’s 3-argument ->where(...)) - for comparisons where_eq can’t express (!=, >, >=, <, <=, LIKE).

Source

pub fn where_null(self, column: &'static str) -> QueryBuilder<T>

WHERE column IS NULL.

Source

pub fn where_not_null(self, column: &'static str) -> QueryBuilder<T>

WHERE column IS NOT NULL.

Source

pub fn where_in<V>( self, column: &'static str, values: Vec<V>, ) -> QueryBuilder<T>
where V: Into<BindValue>,

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

Source

pub fn or_where_eq( self, column: &'static str, value: impl Into<BindValue>, ) -> QueryBuilder<T>

OR column = value.

Source

pub fn or_where_op( self, column: &'static str, op: Op, value: impl Into<BindValue>, ) -> QueryBuilder<T>

OR column <op> value.

Source

pub fn or_where_in<V>( self, column: &'static str, values: Vec<V>, ) -> QueryBuilder<T>
where V: Into<BindValue>,

OR column IN (values...).

Source

pub fn or_where_null(self, column: &'static str) -> QueryBuilder<T>

OR column IS NULL.

Source

pub fn where_group( self, f: impl FnOnce(QueryBuilder<T>) -> QueryBuilder<T>, ) -> QueryBuilder<T>

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.

Source

pub fn or_where_group( self, f: impl FnOnce(QueryBuilder<T>) -> QueryBuilder<T>, ) -> QueryBuilder<T>

OR (...) - see where_group.

Source

pub fn scope( self, f: impl FnOnce(QueryBuilder<T>) -> QueryBuilder<T>, ) -> QueryBuilder<T>

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.

Source

pub fn where_in_query<U>( self, column: &'static str, sub_column: &'static str, sub: QueryBuilder<U>, ) -> QueryBuilder<T>

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.

Source

pub fn latest(self, column: &'static str) -> QueryBuilder<T>

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.

Source

pub fn oldest(self, column: &'static str) -> QueryBuilder<T>

Orders by column ascending (Laravel’s ->oldest($column)).

Source

pub fn order_by(self, column: &'static str, direction: Order) -> QueryBuilder<T>

->orderBy($column, $direction) - latest/oldest are sugar for this with a fixed direction.

Source

pub fn limit(self, n: i64) -> QueryBuilder<T>

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.

Source

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

Source

pub async fn get(self) -> Result<Vec<T>, AppError>

Source

pub async fn get_on(self, database: &Pool<Any>) -> 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.

Source

pub async fn first(self) -> Result<Option<T>, AppError>

Source

pub async fn first_on(self, database: &Pool<Any>) -> Result<Option<T>, AppError>

Source

pub async fn count(self) -> Result<i64, AppError>

Source

pub async fn count_on(self, database: &Pool<Any>) -> Result<i64, AppError>

Source

pub async fn exists(self) -> Result<bool, AppError>

Source§

impl<T> QueryBuilder<T>
where T: for<'r> FromRow<'r, AnyRow> + Send + Unpin + SoftDeletes,

Source

pub fn with_trashed(self) -> QueryBuilder<T>

Includes soft-deleted rows alongside normal ones (Eloquent’s withTrashed()).

Source

pub fn only_trashed(self) -> QueryBuilder<T>

Only soft-deleted rows (Eloquent’s onlyTrashed()).

Auto Trait Implementations§

§

impl<T> Forget for QueryBuilder<T>

§

impl<T> Freeze for QueryBuilder<T>
where PhantomData<fn() -> T>: Freeze,

§

impl<T> Move for QueryBuilder<T>

§

impl<T> RefUnwindSafe for QueryBuilder<T>
where PhantomData<fn() -> T>: RefUnwindSafe,

§

impl<T> Send for QueryBuilder<T>
where PhantomData<fn() -> T>: Send,

§

impl<T> Sync for QueryBuilder<T>
where PhantomData<fn() -> T>: Sync,

§

impl<T> Unpin for QueryBuilder<T>
where PhantomData<fn() -> T>: Unpin,

§

impl<T> UnsafeUnpin for QueryBuilder<T>
where PhantomData<fn() -> T>: UnsafeUnpin,

§

impl<T> UnwindSafe for QueryBuilder<T>
where PhantomData<fn() -> T>: 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> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

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

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. 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, 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