How to Enrich ScalaQuery with Nested Sessions and Transactions

Recently, we wrote an integration test in a Play Framework application using ScalaQuery which failed in a way that surprised us: we had misunderstood the library’s interface for database sessions and transactions.

It turns out that nested usage of #withSession / #withTransaction are not supported by ScalaQuery 0.10.0-M1 out of the box. Instead, a new session and transaction are created in each nested scope. This causes data write/read inconsistencies (due to separate sessions), and failures of transactional rollback (due to separate active transactions in the nested sessions).

Rather than maintain a fork of ScalaQuery, we used the Scala “enrich my library” pattern to add support for the nested usage in an external library. For examples and usage details, check out the scalaquery_nested github project.

For example:

database.withNestedSession {
  // add object to database here
  database.withNestedSession {
    // query same object back from database here
    // great! same connection used, so expected object is returned
  }
}