Skip to content

Instantly share code, notes, and snippets.

@argan
Forked from bmc/Article.scala
Created February 20, 2013 06:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save argan/4993363 to your computer and use it in GitHub Desktop.
Save argan/4993363 to your computer and use it in GitHub Desktop.
case class Article(...);
object Article {
import DBUtil._
def delete(id: Long): Either[String, Boolean] = {
withTransaction { implicit connection =>
SQL("DELETE FROM comments WHERE article_id = {id}").on("id" -> id).executeUpdate()
SQL("DELETE FROM appusers WHERE id = {id}").on("id" -> id).executeUpdate( )
Right(true)
}
}
}
object DBUtil {
def withTransaction[T](code: java.sql.Connection => Either[String,T]): Either[String, T] = {
val connection = play.db.DB.getConnection
val autoCommit = connection.getAutoCommit
try {
connection.setAutoCommit(false)
result = code(connection)
result.fold(
{ error => throw new Exception(error) },
{ _ => connection.commit() }
)
result
}
catch {
case e: Throwable =>
connection.rollback()
val msg = "Error, rolling back transaction: " + e.getMessage
Logger.error(msg)
Left(msg)
}
finally {
connection.setAutoCommit(autoCommit)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment