How to COUNT(*) in Slick 3.0?

Wilson de Carvalho picture Wilson de Carvalho · Sep 4, 2015 · Viewed 8.4k times · Source

I've been using Slick for quite a while and now I'm migrating from Slick 2.1 to 3.0. Unfortunatelly I got stuck with ordinary stuff like counting lines. My code worked perfectly in Slick 2.1 when I used to do this:

connection.withSession {
  implicit session => coffees.length.run
}

On the code above I would get my result as an Int, but I can't get it to work now after I moved to Slick 3.0.2 though the documentation tells me that the code should be the same.

I tried the following (I already removed the withSession deprecated call):

connection.createSession.withTransaction {
  coffees.length
}

But this code will return a slick.lifted.Rep[Int] which does not have any method to get the integer value. Am I missing some implicit import?

Answer

Shadowlands picture Shadowlands · Sep 5, 2015

As you have probably realised, the result of the run call is to produce a Future, which will resolve at some later point.

While this means that eventually somewhere in the code the future will need to be waited on in a manner like you show in your answer, this can, and should, be pushed back as late as possible. If you are working with, for example, the Play framework, use async Actions and let Play handle it for you.

In the meantime work with the Future as you would any other monadic construct (like Option) - calling map, flatMap, onSuccess and so on to chain your computations inside the propagated Future context.