Last active
April 25, 2018 03:17
-
-
Save ruescasd/7911033 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 | |
} |
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
Modified version with support for Option-columns (i.e. nullable):