pub trait SqlFilter<'args, DB: DatabaseTrait = Database> {
// Required methods
fn apply_filter(self, builder: &mut QueryBuilder<'args, DB>);
fn should_apply_filter(&self) -> bool;
}
Expand description
Trait for creating SQL filter conditions that can be applied to database queries.
The SqlFilter
trait provides a standardized way to define reusable, type-safe
SQL filter conditions. Filters can be composed and combined using logical operators
to create complex query criteria.
§Type Parameters
'args
: The lifetime for query argumentsDB
: The database backend type (defaults to the configured default database)
§Examples
Basic implementation using the macro:
sql_filter! {
pub struct UserFilter {
SELECT * FROM users WHERE
id = i32 AND
?name LIKE String AND
?email LIKE String
}
}
// Usage
let filter = UserFilter::new(42)
.name("Alice%")
.email("alice@example.com");
let mut builder = QueryBuilder::<Database>::new("SELECT * FROM users WHERE ");
filter.apply_filter(&mut builder);
Custom implementation:
struct AgeRangeFilter {
min_age: Option<i32>,
max_age: Option<i32>,
}
impl<'args> SqlFilter<'args, Database> for AgeRangeFilter {
fn apply_filter(self, builder: &mut QueryBuilder<'args, Database>) {
if self.min_age.is_some() || self.max_age.is_some() {
let mut first = true;
if let Some(min) = self.min_age {
if !first { builder.push(" AND "); }
builder.push("age >= ");
builder.push_bind(min);
first = false;
}
if let Some(max) = self.max_age {
if !first { builder.push(" AND "); }
builder.push("age <= ");
builder.push_bind(max);
}
}
}
fn should_apply_filter(&self) -> bool {
self.min_age.is_some() || self.max_age.is_some()
}
}
§Implementation Notes
When implementing this trait:
- The
apply_filter
method should add SQL conditions to the builder - The
should_apply_filter
method should returntrue
if this filter has criteria to apply - Consider using the
sql_filter!
macro for common filter patterns - Ensure proper parameterization to prevent SQL injection
Required Methods§
Sourcefn apply_filter(self, builder: &mut QueryBuilder<'args, DB>)
fn apply_filter(self, builder: &mut QueryBuilder<'args, DB>)
Applies this filter’s conditions to a SQL query builder.
This method should add the necessary SQL conditions represented by this filter to the provided query builder. It should handle binding parameters securely.
§Parameters
self
- The filter instance, consumed during applicationbuilder
- The query builder to which the filter will be applied
Sourcefn should_apply_filter(&self) -> bool
fn should_apply_filter(&self) -> bool
Determines whether this filter has meaningful conditions to apply.
This method should return true
if the filter has non-default conditions
that should be included in a query, or false
if the filter is empty or
represents default criteria that don’t need to be applied.
§Returns
true
- If the filter has conditions to applyfalse
- If the filter has no conditions to apply