Slick: Default arguments in prepared query (for limit and range)

631 views Asked by At

I want to do something like this in Slick 2.0.x: select users with age <= maxAge or if maxAge is None, select all users (limited by a number). I tried this:

private def ageQuery(maxAge: Column[Option[Int]], limit: Column[Int]) = {
  Users.filter(user => maxAge.map(_ >= user.age).getOrElse(true)).take(limit)
}

val compiledAgeQuery = Compiled(ageQuery _)

I am running into following issues:

  • limit is a Column[_], but Users.take expects an Int. If I change it limit to Int then I can't use the Compiled macro anymore since that expects only Column[_]

  • This snippet itself does not compile: user => maxAge.map(_ >= user.age).getOrElse(true)

1

There are 1 answers

0
rtruszk On BEST ANSWER

I have found following solution to your problem:

private def ageQuery(maxAge: Column[Option[Int]] ,limit:  scala.slick.lifted.ConstColumn[Long]) = {
    Users.filter(_.age < maxAge.getOrElse(1000)).take(limit)
}

This is what I did:

  1. I changed type of limit parameter to scala.slick.lifted.ConstColumn[Long]. Now it satisfies both take method and Compiled macro
  2. I changed filtering condition. Now it returns all users younger then maxAge, and when maxAge is None then it returns all users younger than 1000 years. It is workaround but it works good (assuming that noone is older than 1000 years)