Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// optionally filter on a column with a supplied predicate
case class MaybeFilter[X, Y](val query: scala.slick.lifted.Query[X, Y]) {
def filter[T](data: Option[T])(f: T => X => scala.slick.lifted.Column[Boolean]) = {
data.map(v => MaybeFilter(query.filter(f(v)))).getOrElse(this)
}
}
// example use case
def find(id: Option[Int], createdMin: Option[Date], createdMax: Option[Date], modifiedMin: Option[Date], modifiedMax: Option[Date]) = {
val query = MaybeFilter(Query(this))
.filter(id)(v => d => d.id === v)
.filter(createdMin)(v => d => d.created >= v)
.filter(createdMax)(v => d => d.created <= v)
.filter(modifiedMin)(v => d => d.modified >= v)
.filter(modifiedMax)(v => d => d.modified <= v)
.query
query.list
}
@cvogt

This comment has been minimized.

Copy link

cvogt commented Feb 26, 2014

Modified version with support for Option-columns (i.e. nullable):

// optionally filter on a column with a supplied predicate
case class MaybeFilter[X, Y](val query: scala.slick.lifted.Query[X, Y]) {
  def filter[T,R:CanBeQueryCondition](data: Option[T])(f: T => X => R) = {
    data.map(v => MaybeFilter(query.filter(f(v)))).getOrElse(this)
  }
}
@alexlee85

This comment has been minimized.

Copy link

alexlee85 commented Nov 17, 2014

I think there is a better way.

implicit class QueryHelper[T, E](query: Query[T, E, Seq]) {
    def optionFilter[X, R: CanBeQueryCondition](name: Option[X])(f: (T, X) => R) =
      name.map(v => query.withFilter(f(_, v))).getOrElse(query)
  }
query.optionFilter(name)(_.name === _)
      .optionFilter(email)(_.email === _).list
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.