Skip to main content

QueryBuilder

Struct QueryBuilder 

Source
pub struct QueryBuilder<'a, T: Model> { /* private fields */ }
Available on crate features model-mysql or model-postgres or model-sqlite only.
Expand description

Fluent async query builder for SELECT, COUNT, DELETE, and UPDATE.

use rust_web_server::model::{DbPool, Order, QueryBuilder};

let pool = DbPool::memory().await?;
// pool.execute("CREATE TABLE users …", &[]).await?;

// let users: Vec<User> = QueryBuilder::<User>::new(&pool)
//     .where_eq("active", true)
//     .order_by("name", Order::Asc)
//     .limit(10)
//     .fetch_all()
//     .await?;

Implementations§

Source§

impl<'a, T: Model> QueryBuilder<'a, T>

Source

pub fn new(pool: &'a DbPool) -> Self

Source

pub fn where_eq(self, col: &str, val: impl ToColumn) -> Self

Add a col = ? equality filter.

Source

pub fn filter(self, expr: &str, params: Vec<Value>) -> Self

Add a raw SQL filter fragment with bind parameters.

ⓘ
.filter("age >= ?", vec![Value::Int(18)])
Source

pub fn order_by(self, col: &str, order: Order) -> Self

Set the ORDER BY clause.

Source

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

Set the LIMIT clause.

Source

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

Set the OFFSET clause.

Source

pub async fn fetch_all(self) -> Result<Vec<T>, DbError>

Execute SELECT * FROM table WHERE … ORDER BY … LIMIT … OFFSET ….

Source

pub async fn fetch_one(self) -> Result<Option<T>, DbError>

Execute SELECT * … LIMIT 1 and return the first result.

Source

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

Execute SELECT COUNT(*) FROM table WHERE ….

Source

pub async fn delete(self) -> Result<(), DbError>

Execute DELETE FROM table WHERE ….

Source

pub async fn update(self, col: &str, val: impl ToColumn) -> Result<(), DbError>

Execute UPDATE table SET col = ? WHERE ….

Source

pub async fn paginate( self, page: u64, per_page: u64, ) -> Result<Page<T>, DbError>

Offset-paginated fetch: runs a COUNT(*) (with the same filters, no limit/offset) and a SELECT … LIMIT … OFFSET …, and wraps both into a Page. page is 1-based; both page and per_page are clamped to a minimum of 1. Overrides any .limit()/.offset() set earlier in the chain — page/per_page are authoritative.

Two queries, not one — if you’re paginating a very large, frequently appended-to table and don’t need total_pages, Self::paginate_after (keyset pagination) needs only one.

Source

pub async fn paginate_after( self, cursor: Option<&str>, per_page: u64, ) -> Result<CursorPage<T>, DbError>

Cursor (keyset) paginated fetch: orders by the primary key ascending, fetches per_page + 1 rows to cheaply detect whether there’s a next page, and returns a CursorPage whose next_cursor is the last returned row’s primary key (as a string) — pass it back as cursor to get the next page. cursor: None fetches the first page.

A single query, unlike Self::paginate — no COUNT(*), and no OFFSET to skip over on every subsequent page, which is what makes keyset pagination scale on large tables where offset pagination gets slower page by page. The tradeoff: no total_items/total_pages, and only forward iteration (no jumping to an arbitrary page).

Overrides any .order_by() set earlier in the chain — keyset pagination requires ordering by the cursor column. Requires the primary key to be numeric (parsed as i64); returns Err if cursor isn’t a valid integer.

Trait Implementations§

Source§

impl<'a, T: Model> Clone for QueryBuilder<'a, T>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more

Auto Trait Implementations§

§

impl<'a, T> !RefUnwindSafe for QueryBuilder<'a, T>

§

impl<'a, T> !UnwindSafe for QueryBuilder<'a, T>

§

impl<'a, T> Freeze for QueryBuilder<'a, T>
where PhantomData<T>: Freeze,

§

impl<'a, T> Send for QueryBuilder<'a, T>
where PhantomData<T>: Send,

§

impl<'a, T> Sync for QueryBuilder<'a, T>
where PhantomData<T>: Sync,

§

impl<'a, T> Unpin for QueryBuilder<'a, T>
where PhantomData<T>: Unpin,

§

impl<'a, T> UnsafeUnpin for QueryBuilder<'a, T>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more