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>
impl<T: BaseModel> ModelQuery<T>
Sourcepub fn new(table_name: &str) -> Result<Self>
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.
Sourcepub fn alias(self, alias: &str) -> Self
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?;Sourcepub fn where_eq<V: Into<SqlValue>>(self, column: &str, value: V) -> Self
pub fn where_eq<V: Into<SqlValue>>(self, column: &str, value: V) -> Self
Add WHERE column = value condition
Sourcepub fn where_ne<V: Into<SqlValue>>(self, column: &str, value: V) -> Self
pub fn where_ne<V: Into<SqlValue>>(self, column: &str, value: V) -> Self
Add WHERE column != value condition
Sourcepub fn where_gt<V: Into<SqlValue>>(self, column: &str, value: V) -> Self
pub fn where_gt<V: Into<SqlValue>>(self, column: &str, value: V) -> Self
Add WHERE column > value condition
Sourcepub fn where_lt<V: Into<SqlValue>>(self, column: &str, value: V) -> Self
pub fn where_lt<V: Into<SqlValue>>(self, column: &str, value: V) -> Self
Add WHERE column < value condition
Sourcepub fn where_gte<V: Into<SqlValue>>(self, column: &str, value: V) -> Self
pub fn where_gte<V: Into<SqlValue>>(self, column: &str, value: V) -> Self
Add WHERE column >= value condition
Sourcepub fn where_lte<V: Into<SqlValue>>(self, column: &str, value: V) -> Self
pub fn where_lte<V: Into<SqlValue>>(self, column: &str, value: V) -> Self
Add WHERE column <= value condition
Sourcepub fn where_like<V: Into<SqlValue>>(self, column: &str, value: V) -> Self
pub fn where_like<V: Into<SqlValue>>(self, column: &str, value: V) -> Self
Add WHERE column LIKE value condition
Sourcepub fn where_not_like(self, column: &str, pattern: &str) -> Self
pub fn where_not_like(self, column: &str, pattern: &str) -> Self
Add WHERE column NOT LIKE value condition
Sourcepub fn where_in<V: Into<SqlValue>>(self, column: &str, values: Vec<V>) -> Self
pub fn where_in<V: Into<SqlValue>>(self, column: &str, values: Vec<V>) -> Self
Add WHERE column IN (values) condition
Sourcepub fn where_not_in<V: Into<SqlValue>>(
self,
column: &str,
values: Vec<V>,
) -> Self
pub fn where_not_in<V: Into<SqlValue>>( self, column: &str, values: Vec<V>, ) -> Self
Add WHERE column NOT IN (values) condition
Sourcepub fn where_between<V: Into<SqlValue>>(
self,
column: &str,
start: V,
end: V,
) -> Self
pub fn where_between<V: Into<SqlValue>>( self, column: &str, start: V, end: V, ) -> Self
Add WHERE column BETWEEN start AND end condition
Sourcepub fn where_null(self, column: &str) -> Self
pub fn where_null(self, column: &str) -> Self
Add WHERE column IS NULL condition
Sourcepub fn where_not_null(self, column: &str) -> Self
pub fn where_not_null(self, column: &str) -> Self
Add WHERE column IS NOT NULL condition
Sourcepub fn apply_filter(self, filter: &ModelFilter) -> Self
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?;Sourcepub fn or_where_eq<V: Into<SqlValue>>(self, column: &str, value: V) -> Self
pub fn or_where_eq<V: Into<SqlValue>>(self, column: &str, value: V) -> Self
Add OR WHERE column = value condition
Sourcepub fn or_where_ne<V: Into<SqlValue>>(self, column: &str, value: V) -> Self
pub fn or_where_ne<V: Into<SqlValue>>(self, column: &str, value: V) -> Self
Add OR WHERE column != value condition
Sourcepub fn or_where_gt<V: Into<SqlValue>>(self, column: &str, value: V) -> Self
pub fn or_where_gt<V: Into<SqlValue>>(self, column: &str, value: V) -> Self
Add OR WHERE column > value condition
Sourcepub fn or_where_lt<V: Into<SqlValue>>(self, column: &str, value: V) -> Self
pub fn or_where_lt<V: Into<SqlValue>>(self, column: &str, value: V) -> Self
Add OR WHERE column < value condition
Sourcepub fn or_where_like(self, column: &str, pattern: &str) -> Self
pub fn or_where_like(self, column: &str, pattern: &str) -> Self
Add OR WHERE column LIKE pattern condition
Sourcepub fn or_where_in<V: Into<SqlValue>>(
self,
column: &str,
values: Vec<V>,
) -> Self
pub fn or_where_in<V: Into<SqlValue>>( self, column: &str, values: Vec<V>, ) -> Self
Add OR WHERE column IN (values) condition
Sourcepub fn or_where_null(self, column: &str) -> Self
pub fn or_where_null(self, column: &str) -> Self
Add OR WHERE column IS NULL condition
Sourcepub fn select(self, columns: &[&str]) -> Self
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?;Sourcepub fn select_raw(self, expressions: &[&str]) -> Self
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?;Sourcepub fn order_by(self, column: &str, direction: OrderDirection) -> Self
pub fn order_by(self, column: &str, direction: OrderDirection) -> Self
Add ORDER BY column ASC/DESC
Sourcepub async fn get_first(self) -> Result<Option<T>>
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 foundOk(None)- If no records matchErr(Error)- If query execution fails
Sourcepub async fn get_one(self) -> Result<Option<T>>
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 foundOk(None)- If no records matchErr(Error)- If query execution fails
Sourcepub async fn get(self) -> Result<Vec<T>>
👎Deprecated since 0.2.0: Please use get_all() instead
pub async fn get(self) -> Result<Vec<T>>
Please use get_all() instead
Execute query and return all matching records
DEPRECATED: Use get_all() instead
Sourcepub async fn first(self) -> Result<Option<T>>
👎Deprecated since 0.2.0: Please use get_first() instead
pub async fn first(self) -> Result<Option<T>>
Please use get_first() instead
Execute query and return the first matching record
DEPRECATED: Use get_first() instead
Sourcepub async fn find(self, id: T::IdType) -> Result<Option<T>>
👎Deprecated since 0.2.0: Please use get_by_id() instead
pub async fn find(self, id: T::IdType) -> Result<Option<T>>
Please use get_by_id() instead
Find a record by its primary key ID
DEPRECATED: Use get_by_id() instead
Sourcepub async fn count(self) -> Result<i64>
pub async fn count(self) -> Result<i64>
Count the number of records matching the query
§Returns
Ok(i64)- Number of matching recordsErr(Error)- If query execution fails
Sourcepub async fn exists(self) -> Result<bool>
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 existsOk(false)- No records matchErr(Error)- If query execution fails
Sourcepub async fn get_raw(self) -> Result<Vec<Value>>
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);
}Sourcepub fn query_builder(&self) -> &QueryBuilder
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.
Sourcepub fn to_sql(&self) -> Result<(String, Vec<SqlValue>), QueryError>
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 parametersErr(QueryError)- If query building fails
Sourcepub async fn get_paginated(
self,
page: u32,
per_page: u32,
) -> Result<PagedResult<T>>
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:
- A COUNT query to get the total number of matching records (WITHOUT LIMIT/OFFSET/ORDER BY)
- 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 metadataErr(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>where
PhantomData<T>: UnsafeUnpin,
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<T> ErasedDestructor for Twhere
T: 'static,
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