Skip to main content

ModelQuery

Struct ModelQuery 

Source
pub struct ModelQuery<T> { /* private fields */ }
Expand description

Model-scoped query builder that provides type-safe, chainable query operations

This struct wraps the generic QueryBuilder and provides model-specific functionality with automatic table names and typed results.

Implementations§

Source§

impl<T: BaseModel> ModelQuery<T>

Source

pub fn new(table_name: &str) -> Result<Self>

Create a new ModelQuery for the specified table

This is typically called from the model’s query() method rather than directly.

Source

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

Set an alias for the main table

This is useful for:

  • Self-joins (joining the same table multiple times)
  • Simplifying long table names
  • Making queries more readable
§Example
ⓘ
// Simple aliasing
let users = Users::query()?
    .alias("u")
    .select(&["u.id", "u.name"])
    .where_eq("u.is_active", true)
    .get()
    .await?;

// Self-join for hierarchical data
let employees = Users::query()?
    .alias("emp")
    .select(&["emp.name as employee", "mgr.name as manager"])
    .left_join("users AS mgr", "mgr.id = emp.manager_id")
    .where_not_null("emp.manager_id")
    .get_raw()
    .await?;
Source

pub fn where_eq<V: Into<SqlValue>>(self, column: &str, value: V) -> Self

Add WHERE column = value condition

Source

pub fn where_ne<V: Into<SqlValue>>(self, column: &str, value: V) -> Self

Add WHERE column != value condition

Source

pub fn where_gt<V: Into<SqlValue>>(self, column: &str, value: V) -> Self

Add WHERE column > value condition

Source

pub fn where_lt<V: Into<SqlValue>>(self, column: &str, value: V) -> Self

Add WHERE column < value condition

Source

pub fn where_gte<V: Into<SqlValue>>(self, column: &str, value: V) -> Self

Add WHERE column >= value condition

Source

pub fn where_lte<V: Into<SqlValue>>(self, column: &str, value: V) -> Self

Add WHERE column <= value condition

Source

pub fn where_like<V: Into<SqlValue>>(self, column: &str, value: V) -> Self

Add WHERE column LIKE value condition

Source

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

Add WHERE column NOT LIKE value condition

Source

pub fn where_in<V: Into<SqlValue>>(self, column: &str, values: Vec<V>) -> Self

Add WHERE column IN (values) condition

Source

pub fn where_not_in<V: Into<SqlValue>>( self, column: &str, values: Vec<V>, ) -> Self

Add WHERE column NOT IN (values) condition

Source

pub fn where_between<V: Into<SqlValue>>( self, column: &str, start: V, end: V, ) -> Self

Add WHERE column BETWEEN start AND end condition

Source

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

Add WHERE column IS NULL condition

Source

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

Add WHERE column IS NOT NULL condition

Source

pub fn apply_filter(self, filter: &ModelFilter) -> Self

Apply a reusable filter to this query

This allows you to define common filters once and apply them to multiple queries.

§Example
ⓘ
let active_filter = ModelFilter::new()
    .where_eq("is_active", true)
    .where_not_null("verified_at");

let count = Users::query()?
    .apply_filter(&active_filter)
    .count()
    .await?;

let users = Users::query()?
    .apply_filter(&active_filter)
    .limit(10)
    .get()
    .await?;
Source

pub fn or_where_eq<V: Into<SqlValue>>(self, column: &str, value: V) -> Self

Add OR WHERE column = value condition

Source

pub fn or_where_ne<V: Into<SqlValue>>(self, column: &str, value: V) -> Self

Add OR WHERE column != value condition

Source

pub fn or_where_gt<V: Into<SqlValue>>(self, column: &str, value: V) -> Self

Add OR WHERE column > value condition

Source

pub fn or_where_lt<V: Into<SqlValue>>(self, column: &str, value: V) -> Self

Add OR WHERE column < value condition

Source

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

Add OR WHERE column LIKE pattern condition

Source

pub fn or_where_in<V: Into<SqlValue>>( self, column: &str, values: Vec<V>, ) -> Self

Add OR WHERE column IN (values) condition

Source

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

Add OR WHERE column IS NULL condition

Source

pub fn select(self, columns: &[&str]) -> Self

Select specific fields instead of SELECT *

§Example
ⓘ
// Select specific columns
let users = Users::query()?
    .select(&["id", "name", "email"])
    .where_eq("is_active", true)
    .get()
    .await?;

// Select with table prefixes (useful for JOINs)
let results = Users::query()?
    .select(&["users.id", "users.name", "posts.title"])
    .join("posts", "posts.user_id = users.id")
    .get()
    .await?;
Source

pub fn select_raw(self, expressions: &[&str]) -> Self

Select with raw SQL expressions

Use this for complex selections including SQL functions and aggregations.

§Example
ⓘ
let results = Users::query()?
    .select_raw(&[
        "users.name",
        "COUNT(posts.id) as post_count",
        "MAX(posts.created_at) as latest_post"
    ])
    .left_join("posts", "posts.user_id = users.id")
    .group_by(&["users.id", "users.name"])
    .get_raw()
    .await?;
Source

pub fn order_by(self, column: &str, direction: OrderDirection) -> Self

Add ORDER BY column ASC/DESC

Source

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

Set LIMIT

Source

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

Set OFFSET

Source

pub fn paginate(self, page: u32, per_page: u32) -> Self

Paginate results (page starts at 1)

Source

pub fn group_by(self, columns: &[&str]) -> Self

Add GROUP BY clause

§Example
ⓘ
let results = Users::query()?
    .select_raw(&["department", "COUNT(*) as count"])
    .group_by(&["department"])
    .get_raw()
    .await?;
Source

pub fn join(self, table: &str, on: &str) -> Self

Add INNER JOIN

Source

pub fn left_join(self, table: &str, on: &str) -> Self

Add LEFT JOIN

Source

pub async fn get_all(self) -> Result<Vec<T>>

Execute query and return all matching records

§Returns
  • Ok(Vec<T>) - All records matching the query
  • Err(Error) - If query execution fails
§Examples
ⓘ
let users = Users::query()
    .where_eq("is_active", 1)
    .order_by("created_at", OrderDirection::Desc)
    .get_all()
    .await?;
Source

pub async fn get_first(self) -> Result<Option<T>>

Execute query and return the first matching record

Automatically adds LIMIT 1 to the query for efficiency.

§Returns
  • Ok(Some(T)) - First record if found
  • Ok(None) - If no records match
  • Err(Error) - If query execution fails
Source

pub async fn get_by_id(self, id: T::IdType) -> Result<Option<T>>

Find a record by its primary key ID

This is a convenience method that adds WHERE id = ? to the query.

§Arguments
  • id - The primary key value to search for
§Returns
  • Ok(Some(T)) - Record if found
  • Ok(None) - If no record with that ID exists
  • Err(Error) - If query execution fails
Source

pub async fn get_one(self) -> Result<Option<T>>

Get one record (alias for get_first)

This is an alias that AI agents and developers often expect.

§Returns
  • Ok(Some(T)) - First record if found
  • Ok(None) - If no records match
  • Err(Error) - If query execution fails
Source

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

👎Deprecated since 0.2.0:

Please use get_all() instead

Execute query and return all matching records

DEPRECATED: Use get_all() instead

Source

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

👎Deprecated since 0.2.0:

Please use get_first() instead

Execute query and return the first matching record

DEPRECATED: Use get_first() instead

Source

pub async fn find(self, id: T::IdType) -> Result<Option<T>>

👎Deprecated since 0.2.0:

Please use get_by_id() instead

Find a record by its primary key ID

DEPRECATED: Use get_by_id() instead

Source

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

Count the number of records matching the query

§Returns
  • Ok(i64) - Number of matching records
  • Err(Error) - If query execution fails
Source

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

Check if any records exist matching the query

This is more efficient than counting when you only need to know if records exist.

§Returns
  • Ok(true) - At least one record exists
  • Ok(false) - No records match
  • Err(Error) - If query execution fails
Source

pub async fn get_raw(self) -> Result<Vec<Value>>

Execute raw query and return results as JSON

This is useful for queries with custom SELECT expressions, aggregations, or complex JOINs that don’t map directly to the model structure.

§Returns

A vector of JSON objects representing the query results.

§Example
ⓘ
let results = Users::query()?
    .select_raw(&[
        "department",
        "COUNT(*) as user_count",
        "AVG(salary) as avg_salary"
    ])
    .group_by(&["department"])
    .get_raw()
    .await?;

for row in results {
    let dept = row["department"].as_str().unwrap();
    let count = row["user_count"].as_i64().unwrap();
    let avg_salary = row["avg_salary"].as_f64().unwrap();
    println!("{}: {} users, avg salary: {}", dept, count, avg_salary);
}
Source

pub fn query_builder(&self) -> &QueryBuilder

Get the underlying QueryBuilder for advanced operations

This provides access to the raw QueryBuilder if you need functionality not exposed by ModelQuery.

Source

pub fn to_sql(&self) -> Result<(String, Vec<SqlValue>), QueryError>

Get the raw SQL and parameters (for debugging)

§Returns
  • Ok((String, Vec<SqlValue>)) - SQL string and parameters
  • Err(QueryError) - If query building fails
Source

pub async fn get_paginated( self, page: u32, per_page: u32, ) -> Result<PagedResult<T>>

Execute paginated query and return results with pagination metadata

This method executes two queries:

  1. A COUNT query to get the total number of matching records (WITHOUT LIMIT/OFFSET/ORDER BY)
  2. A SELECT query to get the actual data for the current page (WITH all conditions + pagination)
§Arguments
  • page - Page number (1-based)
  • per_page - Number of items per page
§Returns
  • Ok(PagedResult<T>) - Paginated results with metadata
  • Err(Error) - If query execution fails
§Example
ⓘ
let result = Users::query()?
    .where_eq("is_active", true)
    .order_by("created_at", OrderDirection::Desc)
    .get_paginated(2, 20)
    .await?;

// Access the data
for user in &result.rows {
    println!("User: {}", user.name);
}

// Access pagination metadata
println!("Page {} of {}", result.page, result.total_pages);
println!("Total rows: {}", result.total_rows);

Auto Trait Implementations§

§

impl<T> !RefUnwindSafe for ModelQuery<T>

§

impl<T> !UnwindSafe for ModelQuery<T>

§

impl<T> Freeze for ModelQuery<T>
where PhantomData<T>: Freeze,

§

impl<T> Send for ModelQuery<T>
where PhantomData<T>: Send,

§

impl<T> Sync for ModelQuery<T>
where PhantomData<T>: Sync,

§

impl<T> Unpin for ModelQuery<T>
where PhantomData<T>: Unpin,

§

impl<T> UnsafeUnpin for ModelQuery<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<T> ErasedDestructor for T
where T: 'static,

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