Add XDB::runTransaction($callback, $arg1, $arg2, $arg2...) to run a
authorFlorent Bruneau <florent.bruneau@polytechnique.org>
Thu, 7 Oct 2010 12:21:33 +0000 (14:21 +0200)
committerFlorent Bruneau <florent.bruneau@polytechnique.org>
Thu, 7 Oct 2010 12:21:33 +0000 (14:21 +0200)
callback as a SQL transaction with automatic commit/rollback in case of
success/failure.

Signed-off-by: Florent Bruneau <florent.bruneau@polytechnique.org>
classes/xdb.php

index 28010c9..c353f54 100644 (file)
@@ -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()));