Tag Archives: scala

Advanced Squeryl/Play Integration

There’s a question on Stack Overflow about how best to integrate Squeryl and Play.

Since Play is an external framework, you might guess that you want to have quite tight integration, using SessionFactory.externalTransactionAdapter. However, the right answer turns out to be looser integration, using SessionFactory.concreteFactory, which means you have to use explicit inTransaction blocks.

So what’s the problem? Well, Play’s database support is deliberately minimal. It provides a connection pool, and handles evolutions for you, but otherwise it’s up to you how you use it. It won’t commit or rollback your transactions unless you ask it to, which means you’re probably best off using inTransaction blocks anyway.

Problem solved, right? Well, almost. There’s still a slight impedance mismatch between Play and Squeryl. Play uses an asynchronous event-driven model, whereas Squeryl is designed for a connection-per-thread model.

So, for example, if you have code like this:

def sendAsteroid = Action { req =>
  import org.squeryl.PrimitiveTypeMode._
  import DinosaurSchema._
  inTransaction {
    val cretaceousDinosaurs = from(dinosaurs)(d => where(d.era === "Cretaceous") select(d)).toList
    Async {
      Akka.future {
        for (dinosaur <- cretaceousDinosaurs.par) {
          dinosaur.extinct = true
          dinosaur.save
        }
        Ok("All cretaceous dinosaurs killed")
      }
    }
  }
}

Then your code won’t work the way you expect.

Continue reading

Advertisements