Search code examples
scalaslick

Await statement execution completion in Slick


In my tests, I've got some database actions that aren't exposed as Futures at the test level. Sometimes, my tests run fast enough that close() in my cleanup happens before those database actions complete, and then I get ugly errors. Is there a way to detect how many statements are in-flight or otherwise hold off close()?


Solution

  • When you execute a query you get Future[A] where A is the result of the query.

    You can compose all your queries using Future.sequence() to get a single future composedFuture which will be completed when all your queries have returned result.

    Now you can use composedFuture.map(_ => close()) to make sure that all queries have finished execution and then you close the resource.

    Best option is to expose the actions as future and then compose them. Otherwise you can put Thread.sleep(someSensibleTime) and hope your future completes within someSensibleTime, but this will make your tests slow and errorprone.