I want to be able to surround a block of code with a transaction. The calling code should be as simple as this:
transactional {
save("something")
}
I thought to make the transactional
function like this:
def transactional(block: => Unit): Unit = {
implicit val conn: Connection = ???
conn.begin()
try {
block
conn.commit()
} catch {
case ex: Exception =>
conn.rollback()
throw ex
} finally {
conn.close()
}
}
Now the save
method will need to do something with the Connection, but I want to make the calling code agnostic of that (see above). I naively implemented it like this:
def save(operation: String)(implicit conn: Connection): Unit = {
println(s"saving $operation using $conn")
}
Of course I get a compilation error, that the Connection can not be found. What part am I missing to wire the Connection from the transactional
function to the save
function?