Skip to content

Instantly share code, notes, and snippets.

@ib84
Created November 11, 2012 16:57
Show Gist options
  • Save ib84/4055504 to your computer and use it in GitHub Desktop.
Save ib84/4055504 to your computer and use it in GitHub Desktop.
Scala HyperGraphDB-Transaction Utility methods + tests
object TestTransa {
import org.hypergraphdb.transaction.HGUserAbortException
import scala.runtime.NonLocalReturnControl
import org.hypergraphdb._
import HGQuery.hg
import java.lang.Throwable
import scala.annotation.tailrec
val graph:HyperGraph = new HyperGraph("/home/ingvar/bin/sbt-scala-hypergraphdb/bje")
def main(args:Array[String]) =
{
val b :Either[Throwable,String]= transact[String](Unit => { graph.get(graph.add("Hello World")).asInstanceOf[String] })
val d: String= transact2T[String](Unit => { graph.get(graph.add("Hello World")).asInstanceOf[String] })
println("funtional transact result: " + b)
println("transact result returning T: " + d)
graph.close
}
// transaction method returning Either[Throwable,T]
def transact[T](code: Unit => T):Either[Throwable,T] =
{
//shorthands
def retryThrow(t:Throwable):Boolean = graph.getStore().getTransactionFactory().canRetryAfter(t);
def commit(b:Boolean) = try{ graph.getTransactionManager().endTransaction(b); } catch { case e => if (retryThrow(e)) throw(e) }
@tailrec def transactInt[T](code: Unit => T):Either[Throwable,T] =
{
( try {
graph.getTransactionManager().beginTransaction()
Right(code())
} catch { case e:Throwable => Left(e) }
) match {
case e: Right[Throwable,T] => commit(true) ; e
case l1: Left[NonLocalReturnControl[T],Int] => commit(true) ; Right(l1.left.get.value)
case l2: Left[HGUserAbortException,T] => commit(false); l2
case t: Left[Throwable,T] => commit(false); if (retryThrow(t.left.get)) throw(t.left.get) else transactInt(code)
}
}
transactInt(code)
}
// transaction method returning T
def transact2T[T](code: Unit => T):T = {
//shorthands
def retryThrow(t:Throwable):Boolean = graph.getStore().getTransactionFactory().canRetryAfter(t);
def commit(b:Boolean) = try{ graph.getTransactionManager().endTransaction(b); } catch { case e => if (retryThrow(e)) throw(e) }
@tailrec def transact2TInt[T](code: Unit => T):T = {
( try {
graph.getTransactionManager().beginTransaction()
Right(code())
} catch { case e:Throwable => Left(e) }
) match {
case Right(r) => commit(true) ; r
case l1: Left[NonLocalReturnControl[T],Int] => commit(true) ; l1.left.get.value
case l2: Left[HGUserAbortException,T] => commit(false); null.asInstanceOf[T]
case t: Left[Throwable,T] => commit(false); if (retryThrow(t.left.get)) throw(t.left.get) else transact2TInt(code)
}
}
transact2TInt(code)
}
}
@ib84
Copy link
Author

ib84 commented Dec 4, 2012

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment