Skip to content

Instantly share code, notes, and snippets.

@potato2003
Created September 25, 2013 09:20
Show Gist options
  • Save potato2003/6697131 to your computer and use it in GitHub Desktop.
Save potato2003/6697131 to your computer and use it in GitHub Desktop.
StackableController + Slick + PlayFramework で暗黙的にDBSession使いまわすのやつメモ
trait SlickDBSessionElement extends StackableController {
self: Controller =>
import play.api.db.slick
type Session = slick.Session
case object DBSessionKey extends RequestAttributeKey[Session]
override def proceed[A](req: RequestWithAttributes[A])(f: RequestWithAttributes[A] => Result): Result = {
val session:Session = play.api.db.slick.DB.createSession()
super.proceed(req.set(DBSessionKey, session))(f)
}
override def cleanupOnSucceeded[A](req: RequestWithAttributes[A]): Unit = {
try {
req.get(DBSessionKey).map(_.close())
} finally {
super.cleanupOnSucceeded(req)
}
}
override def cleanupOnFailed[A](req: RequestWithAttributes[A], e: Exception): Unit = {
try {
req.get(DBSessionKey).map(_.close())
} finally {
super.cleanupOnFailed(req, e)
}
}
implicit def dbSession(implicit req: RequestWithAttributes[_]): Session = req.get(DBSessionKey).get
def withTransaction[T](f: => T)(implicit req: RequestWithAttributes[_]): T = {
slick.DB("master").withTransaction(f)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment