scalaslickslick-2.0

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


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:


Solution

  • 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)