Skip to content

Instantly share code, notes, and snippets.

@fourbytes
Created February 4, 2021 06:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fourbytes/db2973e4041a1e121a7a1968fe7dcbe4 to your computer and use it in GitHub Desktop.
Save fourbytes/db2973e4041a1e121a7a1968fe7dcbe4 to your computer and use it in GitHub Desktop.
pub trait FilterWith: AsQuery + Sized {
fn filter_with(self, filters: FilterOpts) -> FilteredQuery<Self::Query> {
FilteredQuery {
query: self.as_query(),
filters,
}
}
}
#[derive(QueryId)]
pub struct FilteredQuery<T> {
query: T,
filters: FilterOpts,
}
impl<T: Query> Query for FilteredQuery<T> {
type SqlType = T::SqlType;
}
impl<T> RunQueryDsl<PgConnection> for FilteredQuery<T> {}
impl<T: AsQuery> FilterWith for T {}
impl<T> QueryFragment<Pg> for FilteredQuery<T>
where
T: QueryFragment<Pg>,
{
fn walk_ast(&self, mut out: AstPass<Pg>) -> QueryResult<()> {
self.query.walk_ast(out.reborrow())?;
out.push_sql(" WHERE ");
// TODO: dyanmically build this from self (looping self.filters and joining each with
// and/or).
out.push_sql(job::name.eq(self.query).into_sql());
Ok(())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment