-
-
Save cvogt/9193220 to your computer and use it in GitHub Desktop.
Slick: Dynamic query conditions using the **MaybeFilter** (Updated to support nullable columns)
This file contains hidden or 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
import scala.slick.lifted.CanBeQueryCondition | |
// 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) | |
} | |
} | |
// example use case | |
import java.sql.Date | |
class SomeTable(tag: Tag) extends Table[(Int, Date, Date)](tag, "some_table") { | |
def id = column[Int]("id", O.PrimaryKey, O.AutoInc) | |
def created = column[Date]("created") | |
def modified = column[Date]("modified") | |
def * = (id, created, modified) | |
} | |
lazy val someTable = TableQuery[SomeTable] | |
someTable.ddl.create | |
def find(id: Option[Int], createdMin: Option[Date], createdMax: Option[Date], modifiedMin: Option[Date], modifiedMax: Option[Date]) = { | |
MaybeFilter(someTable) | |
.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 | |
} | |
find(Some(1),None,None,None,None).list // <- example: find by id only |
@simao, this fails on:
table.maybeFilter(_.someColumn.asColumnOf[String] like arg.map(a => s"%$a%)).take(10).result
at least on mariadb it looks like it generates invalid query in the end:
Query is: select `id`, `some_column`, `status` from `test_table` where ifnull((convert(`some_column`,VARCHAR)) like '%test%',true) limit 10
Do you know what is this ifnull
? - update: ifnull is db function to filter expressions
without maybeFilter
it does not work either, but that is another story :)
update: problem is related to slick, as it can't do like query on field with custom mapping. once column type is plain String, it all works
how to make it happen on Slick 1.0.0?
Very useful, thank you!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
We use an implicit class to make a nice api around a
maybeFilter
:This is how you'd use it:
More info:
https://github.com/advancedtelematic/libats/blob/master/libats-slick/src/main/scala/com/advancedtelematic/libats/slick/db/SlickExtensions.scala
https://0io.eu/blog/2017/09/15/useful-slick-implicits