Skip to content

Instantly share code, notes, and snippets.

@ruescasd
Last active April 25, 2018 03:17
Show Gist options
  • Save ruescasd/7911033 to your computer and use it in GitHub Desktop.
Save ruescasd/7911033 to your computer and use it in GitHub Desktop.
// 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
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
Copy link

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