From f23d33e1b114e9032b4b966baebdeb14b4215313 Mon Sep 17 00:00:00 2001 From: Florent Bruneau Date: Thu, 7 Oct 2010 14:21:33 +0200 Subject: [PATCH] Add XDB::runTransaction($callback, $arg1, $arg2, $arg2...) to run a callback as a SQL transaction with automatic commit/rollback in case of success/failure. Signed-off-by: Florent Bruneau --- classes/xdb.php | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/classes/xdb.php b/classes/xdb.php index 28010c9..c353f54 100644 --- a/classes/xdb.php +++ b/classes/xdb.php @@ -212,6 +212,35 @@ class XDB self::rawExecute('SET AUTOCOMMIT = 1'); } + public static function runTransactionV($callback, array $args) + { + self::startTransaction(); + try { + if (call_user_func_array($callback, $args)) { + self::commit(); + return true; + } else { + self::rollback(); + return false; + } + } catch (Exception $e) { + self::rollback(); + throw $e; + } + } + + /** This function takes a callback followed by the arguments to be passed to the callback + * as arguments. It starts a transaction and execute the callback. If the callback fails + * (return false or raise an exception), the transaction is rollbacked, if the callback + * succeeds (return true), the transaction is committed. + */ + public static function runTransaction() + { + $args = func_get_args(); + $cb = array_shift($args); + self::runTransactionV($cb, $args); + } + public static function iterator() { return new XDBIterator(self::prepare(func_get_args())); -- 2.1.4