Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Add database rollback documentation.
  • Loading branch information
xevix committed Feb 16, 2016
1 parent 921255c commit 6caaea3
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
29 changes: 29 additions & 0 deletions slick/src/sphinx/code/Connection.scala
@@ -1,6 +1,7 @@
package com.typesafe.slick.docs

import java.sql.Blob
import javax.sql.rowset.serial.SerialBlob

import org.reactivestreams.Publisher

Expand All @@ -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._

Expand Down Expand Up @@ -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
Expand Down
7 changes: 7 additions & 0 deletions slick/src/sphinx/dbio.rst
Expand Up @@ -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:

Expand Down

0 comments on commit 6caaea3

Please sign in to comment.