3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 * @copyright David Strauss <david@fourkitchens.com> (c) 2007
18 * (Note: This has been considerably rewritten; the interface is preserved
19 * for backward compatibility.)
21 * Transaction management in Civi is divided among three classes:
22 * - CRM_Core_Transaction: API. This binds to __construct() + __destruct()
23 * and notifies the transaction manager when it's OK to begin/end a transaction.
24 * - Civi\Core\Transaction\Manager: Tracks pending transaction-frames
25 * - Civi\Core\Transaction\Frame: A nestable transaction (e.g. based on BEGIN/COMMIT/ROLLBACK
26 * or SAVEPOINT/ROLLBACK TO SAVEPOINT).
31 * // Some business logic using the helper functions
32 * function my_business_logic() {
33 * CRM_Core_Transaction::create()->run(function($tx) {
35 * if ($error) throw new Exception();
39 * // Some business logic which returns an error-value
40 * // and explicitly manages the transaction.
41 * function my_business_logic() {
42 * $tx = new CRM_Core_Transaction();
50 * // Some business logic which uses exceptions
51 * // and explicitly manages the transaction.
52 * function my_business_logic() {
53 * $tx = new CRM_Core_Transaction();
56 * } catch (Exception $ex) {
57 * $tx->rollback()->commit();
64 * Note: As of 4.6, the transaction manager supports both reference-counting and nested
65 * transactions (SAVEPOINTs). In the past, it only supported reference-counting. The two cases
66 * may exhibit different systemic effects with respect to unhandled exceptions.
68 class CRM_Core_Transaction
{
71 * These constants represent phases at which callbacks can be invoked.
73 const PHASE_PRE_COMMIT
= 1;
74 const PHASE_POST_COMMIT
= 2;
75 const PHASE_PRE_ROLLBACK
= 4;
76 const PHASE_POST_ROLLBACK
= 8;
79 * Whether commit() has been called on this instance
80 * of CRM_Core_Transaction
83 private $_pseudoCommitted = FALSE;
86 * Ensure that an SQL transaction is started.
88 * This is a thin wrapper around __construct() which allows more fluent coding.
91 * Determines what to do if there's currently an active transaction:.
92 * - If true, then make a new nested transaction ("SAVEPOINT")
93 * - If false, then attach to the existing transaction
94 * @return \CRM_Core_Transaction
96 public static function create($nest = FALSE) {
97 return new self($nest);
101 * Ensure that an SQL transaction is started.
104 * Determines what to do if there's currently an active transaction:.
105 * - If true, then make a new nested transaction ("SAVEPOINT")
106 * - If false, then attach to the existing transaction
108 public function __construct($nest = FALSE) {
109 \Civi\Core\Transaction\Manager
::singleton()->inc($nest);
112 public function __destruct() {
117 * Immediately commit or rollback.
119 * (Note: Prior to 4.6, return void)
121 * @return \CRM_Core_Exception this
123 public function commit() {
124 if (!$this->_pseudoCommitted
) {
125 $this->_pseudoCommitted
= TRUE;
126 \Civi\Core\Transaction\Manager
::singleton()->dec();
134 public static function rollbackIfFalse($flag) {
135 $frame = \Civi\Core\Transaction\Manager
::singleton()->getFrame();
136 if ($flag === FALSE && $frame !== NULL) {
137 $frame->setRollbackOnly();
142 * Mark the transaction for rollback.
144 * (Note: Prior to 4.6, return void)
145 * @return \CRM_Core_Transaction
147 public function rollback() {
148 $frame = \Civi\Core\Transaction\Manager
::singleton()->getFrame();
149 if ($frame !== NULL) {
150 $frame->setRollbackOnly();
156 * Execute a function ($callable) within the scope of a transaction. If
157 * $callable encounters an unhandled exception, then rollback the transaction.
159 * After calling run(), the CRM_Core_Transaction object is "used up"; do not
162 * @param callable $callable
163 * Should expect one parameter (CRM_Core_Transaction).
164 * @return CRM_Core_Transaction
167 public function run($callable) {
171 catch (Exception
$ex) {
172 $this->rollback()->commit();
180 * Force an immediate rollback, regardless of how many any
181 * CRM_Core_Transaction objects are waiting for
184 * Only rollback if the transaction API has been called.
186 * This is only appropriate when it is _certain_ that the
187 * callstack will not wind-down normally -- e.g. before
190 public static function forceRollbackIfEnabled() {
191 if (\Civi\Core\Transaction\Manager
::singleton()->getFrame() !== NULL) {
192 \Civi\Core\Transaction\Manager
::singleton()->forceRollback();
199 public static function willCommit() {
200 $frame = \Civi\Core\Transaction\Manager
::singleton()->getFrame();
201 return ($frame === NULL) ?
TRUE : !$frame->isRollbackOnly();
205 * Determine whether there is a pending transaction.
207 public static function isActive() {
208 $frame = \Civi\Core\Transaction\Manager
::singleton()->getFrame();
209 return ($frame !== NULL);
213 * Add a transaction callback.
215 * Note: It's conceivable to add callbacks to the main/overall transaction
216 * (aka $manager->getBaseFrame()) or to the innermost nested transaction
217 * (aka $manager->getFrame()). addCallback() has been used in the past to
218 * work-around deadlocks. This may or may not be necessary now -- but it
219 * seems more consistent (for b/c purposes) to attach callbacks to the
220 * main/overall transaction.
222 * Pre-condition: isActive()
225 * A constant; one of: self::PHASE_{PRE,POST}_{COMMIT,ROLLBACK}.
226 * @param string $callback
228 * @param mixed $params
229 * Optional values to pass to callback.
230 * See php manual call_user_func_array for details.
233 public static function addCallback($phase, $callback, $params = NULL, $id = NULL) {
234 $frame = \Civi\Core\Transaction\Manager
::singleton()->getBaseFrame();
235 $frame->addCallback($phase, $callback, $params, $id);
239 * Whenever hook_civicrm_post fires, schedule an equivalent
240 * call to hook_civicrm_postCommit.
242 * @param \Civi\Core\Event\PostEvent $e
243 * @see CRM_Utils_Hook::post
245 public static function addPostCommit($e) {
246 // Do we want to dedupe post-commit hooks for the same txn? Setting an ID
248 // $id = $e->entity . chr(0) . $e->action . chr(0) . $e->id;
249 $frame = \Civi\Core\Transaction\Manager
::singleton()->getBaseFrame();
251 $frame->addCallback(self
::PHASE_POST_COMMIT
, ['CRM_Utils_Hook', 'postCommit'], [$e->action
, $e->entity
, $e->id
, $e->object]);
254 \CRM_Utils_Hook
::postCommit($e->action
, $e->entity
, $e->id
, $e->object);