Skip to content

Instantly share code, notes, and snippets.

@danslapman
Created December 17, 2018 12:35
Show Gist options
  • Save danslapman/fe008d35fc69997aa2adae3be9ede5ec to your computer and use it in GitHub Desktop.
Save danslapman/fe008d35fc69997aa2adae3be9ede5ec to your computer and use it in GitHub Desktop.
Dynamic querying in Quill
import $ivy.`io.getquill::quill:2.6.0`
import io.getquill._
val ctx = new SqlMirrorContext(MirrorSqlDialect, Literal)
import ctx._
case class Entity(field1: String, field2: Int)
def getEntity(field1: Option[String], field2: Option[Int]) = {
type QEC = Quoted[EntityQuery[Entity]]
val initialQ: QEC = quote {
query[Entity]
}
val field1Filter = field1.map(f1 => (q: QEC) => quote(q.filter(_.field1 == lift(f1))))
val field2Filter = field2.map(f2 => (q: QEC) => quote(q.filter(_.field2 == lift(f2))))
val activeFilters = Seq(
field1Filter, field2Filter
).flatten
val conQ = activeFilters.foldLeft(initialQ)((q, filter) => filter(q))
ctx.run(conQ).string
}
println(getEntity(Some("foo"), None))
println(getEntity(None, Some(42)))
println(getEntity(Some("foo"), Some(42)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment