Permalink
Browse files

Add database rollback documentation.

  • Loading branch information...
1 parent 921255c commit 6caaea3a8a888d54dc51463bc0e1725191b9721a @xevix xevix committed Dec 2, 2015
Showing with 36 additions and 0 deletions.
  1. +29 −0 slick/src/sphinx/code/Connection.scala
  2. +7 −0 slick/src/sphinx/dbio.rst
@@ -1,6 +1,7 @@
package com.typesafe.slick.docs
import java.sql.Blob
+import javax.sql.rowset.serial.SerialBlob
import org.reactivestreams.Publisher
@@ -9,6 +10,7 @@ import scala.concurrent.{Future, Await}
import scala.concurrent.duration.Duration
import scala.concurrent.ExecutionContext.Implicits.global
import scala.language.higherKinds
+import scala.util.{Failure, Success}
import slick.basic.DatabasePublisher
import slick.jdbc.H2Profile.api._
@@ -103,6 +105,33 @@ object Connection extends App {
val f: Future[Unit] = db.run(a)
//#transaction
Await.result(f, Duration.Inf)
+ };{
+ //#rollback
+ val countAction = coffees.length.result
+
+ val rollbackAction = (coffees ++= Seq(
+ ("Cold_Drip", new SerialBlob(Array[Byte](101))),
+ ("Dutch_Coffee", new SerialBlob(Array[Byte](49)))
+ )).flatMap { _ =>
+ DBIO.failed(new Exception("Roll it back"))
+ }.transactionally
+
+ val errorHandleAction = rollbackAction.asTry.flatMap {
+ case Failure(e: Throwable) => DBIO.successful(e.getMessage)
+ case Success(_) => DBIO.successful("never reached")
+ }
+
+ // Here we show that that coffee count is the same before and after the attempted insert.
+ // We also show that the result of the action is filled in with the exception's message.
+ val f = db.run(countAction zip errorHandleAction zip countAction).map {
+ case ((initialCount, result), finalCount) =>
+ // init: 5, final: 5, result: Roll it back
+ println(s"init: ${initialCount}, final: ${finalCount}, result: ${result}")
+ result
+ }
+
+ //#rollback
+ assert(Await.result(f, Duration.Inf) == "Roll it back")
}
lines.foreach(Predef.println _)
} finally db.close
@@ -196,6 +196,13 @@ always implies a pinned session.
transaction is only created and committed or rolled back for the outermost ``transactionally`` action. Nested
``transactionally`` actions simply execute inside the existing transaction without additional savepoints.
+Rollbacks
+_________
+
+In case you want to force a rollback, you can return ``DBIO.failed`` within a ``DBIOAction``.
+
+.. includecode:: code/Connection.scala#rollback
+
.. index:: JDBC
.. _jdbc-interop:

0 comments on commit 6caaea3

Please sign in to comment.