Subversion-Projekte lars-tiefland.php_share

Revision

Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
1 lars 1
<?php
2
/*
3
 *  $Id: Transaction.php 7651 2010-06-08 15:47:06Z jwage $
4
 *
5
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
6
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
7
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
8
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
10
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
11
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
12
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
13
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
14
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
15
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
16
 *
17
 * This software consists of voluntary contributions made by many individuals
18
 * and is licensed under the LGPL. For more information, see
19
 * <http://www.doctrine-project.org>.
20
 */
21
 
22
/**
23
 * Doctrine_Transaction
24
 * Handles transaction savepoint and isolation abstraction
25
 *
26
 * @author      Konsta Vesterinen <kvesteri@cc.hut.fi>
27
 * @author      Lukas Smith <smith@pooteeweet.org> (PEAR MDB2 library)
28
 * @license     http://www.opensource.org/licenses/lgpl-license.php LGPL
29
 * @package     Doctrine
30
 * @subpackage  Transaction
31
 * @link        www.doctrine-project.org
32
 * @since       1.0
33
 * @version     $Revision: 7651 $
34
 */
35
class Doctrine_Transaction extends Doctrine_Connection_Module
36
{
37
    /**
38
     * Doctrine_Transaction is in sleep state when it has no active transactions
39
     */
40
    const STATE_SLEEP       = 0;
41
 
42
    /**
43
     * Doctrine_Transaction is in active state when it has one active transaction
44
     */
45
    const STATE_ACTIVE      = 1;
46
 
47
    /**
48
     * Doctrine_Transaction is in busy state when it has multiple active transactions
49
     */
50
    const STATE_BUSY        = 2;
51
 
52
    /**
53
     * @var integer $_nestingLevel      The current nesting level of this transaction.
54
     *                                  A nesting level of 0 means there is currently no active
55
     *                                  transaction.
56
     */
57
    protected $_nestingLevel = 0;
58
 
59
    /**
60
     * @var integer $_internalNestingLevel  The current internal nesting level of this transaction.
61
     *                                      "Internal" means transactions started by Doctrine itself.
62
     *                                      Therefore the internal nesting level is always
63
     *                                      lower or equal to the overall nesting level.
64
     *                                      A level of 0 means there is currently no active
65
     *                                      transaction that was initiated by Doctrine itself.
66
     */
67
    protected $_internalNestingLevel = 0;
68
 
69
    /**
70
     * @var array $invalid                  an array containing all invalid records within this transaction
71
     * @todo What about a more verbose name? $invalidRecords?
72
     */
73
    protected $invalid          = array();
74
 
75
    /**
76
     * @var array $savepoints               an array containing all savepoints
77
     */
78
    protected $savePoints       = array();
79
 
80
    /**
81
     * @var array $_collections             an array of Doctrine_Collection objects that were affected during the Transaction
82
     */
83
    protected $_collections     = array();
84
 
85
    /**
86
     * addCollection
87
     * adds a collection in the internal array of collections
88
     *
89
     * at the end of each commit this array is looped over and
90
     * of every collection Doctrine then takes a snapshot in order
91
     * to keep the collections up to date with the database
92
     *
93
     * @param Doctrine_Collection $coll     a collection to be added
94
     * @return Doctrine_Transaction         this object
95
     */
96
    public function addCollection(Doctrine_Collection $coll)
97
    {
98
        $this->_collections[] = $coll;
99
 
100
        return $this;
101
    }
102
 
103
    /**
104
     * getState
105
     * returns the state of this transaction module.
106
     *
107
     * @see Doctrine_Connection_Transaction::STATE_* constants
108
     * @return integer          the connection state
109
     */
110
    public function getState()
111
    {
112
        switch ($this->_nestingLevel) {
113
            case 0:
114
                return Doctrine_Transaction::STATE_SLEEP;
115
                break;
116
            case 1:
117
                return Doctrine_Transaction::STATE_ACTIVE;
118
                break;
119
            default:
120
                return Doctrine_Transaction::STATE_BUSY;
121
        }
122
    }
123
 
124
    /**
125
     * addInvalid
126
     * adds record into invalid records list
127
     *
128
     * @param Doctrine_Record $record
129
     * @return boolean        false if record already existed in invalid records list,
130
     *                        otherwise true
131
     */
132
    public function addInvalid(Doctrine_Record $record)
133
    {
134
        if (in_array($record, $this->invalid, true)) {
135
            return false;
136
        }
137
        $this->invalid[] = $record;
138
        return true;
139
    }
140
 
141
 
142
   /**
143
    * Return the invalid records
144
    *
145
    * @return array An array of invalid records
146
    */
147
    public function getInvalid()
148
    {
149
        return $this->invalid;
150
    }
151
 
152
    /**
153
     * getTransactionLevel
154
     * get the current transaction nesting level
155
     *
156
     * @return integer
157
     */
158
    public function getTransactionLevel()
159
    {
160
        return $this->_nestingLevel;
161
    }
162
 
163
    public function getInternalTransactionLevel()
164
    {
165
        return $this->_internalNestingLevel;
166
    }
167
 
168
    /**
169
     * beginTransaction
170
     * Start a transaction or set a savepoint.
171
     *
172
     * if trying to set a savepoint and there is no active transaction
173
     * a new transaction is being started
174
     *
175
     * This method should only be used by userland-code to initiate transactions.
176
     * To initiate a transaction from inside Doctrine use {@link beginInternalTransaction()}.
177
     *
178
     * Listeners: onPreTransactionBegin, onTransactionBegin
179
     *
180
     * @param string $savepoint                 name of a savepoint to set
181
     * @throws Doctrine_Transaction_Exception   if the transaction fails at database level
182
     * @return integer                          current transaction nesting level
183
     */
184
    public function beginTransaction($savepoint = null)
185
    {
186
        $this->conn->connect();
187
 
188
        $listener = $this->conn->getAttribute(Doctrine_Core::ATTR_LISTENER);
189
 
190
        if ( ! is_null($savepoint)) {
191
            $this->savePoints[] = $savepoint;
192
 
193
            $event = new Doctrine_Event($this, Doctrine_Event::SAVEPOINT_CREATE);
194
 
195
            $listener->preSavepointCreate($event);
196
 
197
            if ( ! $event->skipOperation) {
198
                $this->createSavePoint($savepoint);
199
            }
200
 
201
            $listener->postSavepointCreate($event);
202
        } else {
203
            if ($this->_nestingLevel == 0) {
204
                $event = new Doctrine_Event($this, Doctrine_Event::TX_BEGIN);
205
 
206
                $listener->preTransactionBegin($event);
207
 
208
                if ( ! $event->skipOperation) {
209
                    try {
210
                        $this->_doBeginTransaction();
211
                    } catch (Exception $e) {
212
                        throw new Doctrine_Transaction_Exception($e->getMessage());
213
                    }
214
                }
215
                $listener->postTransactionBegin($event);
216
            }
217
        }
218
 
219
        $level = ++$this->_nestingLevel;
220
 
221
        return $level;
222
    }
223
 
224
    /**
225
     * Commit the database changes done during a transaction that is in
226
     * progress or release a savepoint. This function may only be called when
227
     * auto-committing is disabled, otherwise it will fail.
228
     *
229
     * Listeners: preTransactionCommit, postTransactionCommit
230
     *
231
     * @param string $savepoint                 name of a savepoint to release
232
     * @throws Doctrine_Transaction_Exception   if the transaction fails at database level
233
     * @throws Doctrine_Validator_Exception     if the transaction fails due to record validations
234
     * @return boolean                          false if commit couldn't be performed, true otherwise
235
     */
236
    public function commit($savepoint = null)
237
    {
238
        if ($this->_nestingLevel == 0) {
239
            throw new Doctrine_Transaction_Exception("Commit failed. There is no active transaction.");
240
        }
241
 
242
        $this->conn->connect();
243
 
244
        $listener = $this->conn->getAttribute(Doctrine_Core::ATTR_LISTENER);
245
 
246
        if ( ! is_null($savepoint)) {
247
            $this->_nestingLevel -= $this->removeSavePoints($savepoint);
248
 
249
            $event = new Doctrine_Event($this, Doctrine_Event::SAVEPOINT_COMMIT);
250
 
251
            $listener->preSavepointCommit($event);
252
 
253
            if ( ! $event->skipOperation) {
254
                $this->releaseSavePoint($savepoint);
255
            }
256
 
257
            $listener->postSavepointCommit($event);
258
        } else {
259
 
260
            if ($this->_nestingLevel == 1 || $this->_internalNestingLevel == 1) {
261
                if ( ! empty($this->invalid)) {
262
                    if ($this->_internalNestingLevel == 1) {
263
                        $tmp = $this->invalid;
264
                        $this->invalid = array();
265
                        throw new Doctrine_Validator_Exception($tmp);
266
                    }
267
                }
268
                if ($this->_nestingLevel == 1) {
269
                    // take snapshots of all collections used within this transaction
270
                    foreach ($this->_collections as $coll) {
271
                        $coll->takeSnapshot();
272
                    }
273
                    $this->_collections = array();
274
 
275
                    $event = new Doctrine_Event($this, Doctrine_Event::TX_COMMIT);
276
 
277
                    $listener->preTransactionCommit($event);
278
                    if ( ! $event->skipOperation) {
279
                        $this->_doCommit();
280
                    }
281
                    $listener->postTransactionCommit($event);
282
                }
283
            }
284
 
285
            if ($this->_nestingLevel > 0) {
286
                $this->_nestingLevel--;
287
            }
288
            if ($this->_internalNestingLevel > 0) {
289
                $this->_internalNestingLevel--;
290
            }
291
        }
292
 
293
        return true;
294
    }
295
 
296
    /**
297
     * rollback
298
     * Cancel any database changes done during a transaction or since a specific
299
     * savepoint that is in progress. This function may only be called when
300
     * auto-committing is disabled, otherwise it will fail. Therefore, a new
301
     * transaction is implicitly started after canceling the pending changes.
302
     *
303
     * this method can be listened with onPreTransactionRollback and onTransactionRollback
304
     * eventlistener methods
305
     *
306
     * @param string $savepoint                 name of a savepoint to rollback to
307
     * @throws Doctrine_Transaction_Exception   if the rollback operation fails at database level
308
     * @return boolean                          false if rollback couldn't be performed, true otherwise
309
     * @todo Shouldnt this method only commit a rollback if the transactionLevel is 1
310
     *       (STATE_ACTIVE)? Explanation: Otherwise a rollback that is triggered from inside doctrine
311
     *       in an (emulated) nested transaction would lead to a complete database level
312
     *       rollback even though the client code did not yet want to do that.
313
     *       In other words: if the user starts a transaction doctrine shouldnt roll it back.
314
     *       Doctrine should only roll back transactions started by doctrine. Thoughts?
315
     */
316
    public function rollback($savepoint = null)
317
    {
318
        if ($this->_nestingLevel == 0) {
319
            throw new Doctrine_Transaction_Exception("Rollback failed. There is no active transaction.");
320
        }
321
 
322
        $this->conn->connect();
323
 
324
        if ($this->_internalNestingLevel >= 1 && $this->_nestingLevel > 1) {
325
            $this->_internalNestingLevel--;
326
            $this->_nestingLevel--;
327
            return false;
328
        } else if ($this->_nestingLevel > 1) {
329
            $this->_nestingLevel--;
330
            return false;
331
        }
332
 
333
        $listener = $this->conn->getAttribute(Doctrine_Core::ATTR_LISTENER);
334
 
335
        if ( ! is_null($savepoint)) {
336
            $this->_nestingLevel -= $this->removeSavePoints($savepoint);
337
 
338
            $event = new Doctrine_Event($this, Doctrine_Event::SAVEPOINT_ROLLBACK);
339
 
340
            $listener->preSavepointRollback($event);
341
 
342
            if ( ! $event->skipOperation) {
343
                $this->rollbackSavePoint($savepoint);
344
            }
345
 
346
            $listener->postSavepointRollback($event);
347
        } else {
348
            $event = new Doctrine_Event($this, Doctrine_Event::TX_ROLLBACK);
349
 
350
            $listener->preTransactionRollback($event);
351
 
352
            if ( ! $event->skipOperation) {
353
                $this->_nestingLevel = 0;
354
                $this->_internalNestingLevel = 0;
355
                try {
356
                    $this->_doRollback();
357
                } catch (Exception $e) {
358
                    throw new Doctrine_Transaction_Exception($e->getMessage());
359
                }
360
            }
361
 
362
            $listener->postTransactionRollback($event);
363
        }
364
 
365
        return true;
366
    }
367
 
368
    /**
369
     * releaseSavePoint
370
     * creates a new savepoint
371
     *
372
     * @param string $savepoint     name of a savepoint to create
373
     * @return void
374
     */
375
    protected function createSavePoint($savepoint)
376
    {
377
        throw new Doctrine_Transaction_Exception('Savepoints not supported by this driver.');
378
    }
379
 
380
    /**
381
     * releaseSavePoint
382
     * releases given savepoint
383
     *
384
     * @param string $savepoint     name of a savepoint to release
385
     * @return void
386
     */
387
    protected function releaseSavePoint($savepoint)
388
    {
389
        throw new Doctrine_Transaction_Exception('Savepoints not supported by this driver.');
390
    }
391
 
392
    /**
393
     * rollbackSavePoint
394
     * releases given savepoint
395
     *
396
     * @param string $savepoint     name of a savepoint to rollback to
397
     * @return void
398
     */
399
    protected function rollbackSavePoint($savepoint)
400
    {
401
        throw new Doctrine_Transaction_Exception('Savepoints not supported by this driver.');
402
    }
403
 
404
    /**
405
     * Performs the rollback.
406
     */
407
    protected function _doRollback()
408
    {
409
        $this->conn->getDbh()->rollback();
410
    }
411
 
412
    /**
413
     * Performs the commit.
414
     */
415
    protected function _doCommit()
416
    {
417
        $this->conn->getDbh()->commit();
418
    }
419
 
420
    /**
421
     * Begins a database transaction.
422
     */
423
    protected function _doBeginTransaction()
424
    {
425
        $this->conn->getDbh()->beginTransaction();
426
    }
427
 
428
    /**
429
     * removeSavePoints
430
     * removes a savepoint from the internal savePoints array of this transaction object
431
     * and all its children savepoints
432
     *
433
     * @param sring $savepoint      name of the savepoint to remove
434
     * @return integer              removed savepoints
435
     */
436
    private function removeSavePoints($savepoint)
437
    {
438
        $this->savePoints = array_values($this->savePoints);
439
 
440
        $found = false;
441
        $i = 0;
442
 
443
        foreach ($this->savePoints as $key => $sp) {
444
            if ( ! $found) {
445
                if ($sp === $savepoint) {
446
                    $found = true;
447
                }
448
            }
449
            if ($found) {
450
                $i++;
451
                unset($this->savePoints[$key]);
452
            }
453
        }
454
 
455
        return $i;
456
    }
457
 
458
    /**
459
     * setIsolation
460
     *
461
     * Set the transacton isolation level.
462
     * (implemented by the connection drivers)
463
     *
464
     * example:
465
     *
466
     * <code>
467
     * $tx->setIsolation('READ UNCOMMITTED');
468
     * </code>
469
     *
470
     * @param   string  standard isolation level
471
     *                  READ UNCOMMITTED (allows dirty reads)
472
     *                  READ COMMITTED (prevents dirty reads)
473
     *                  REPEATABLE READ (prevents nonrepeatable reads)
474
     *                  SERIALIZABLE (prevents phantom reads)
475
     *
476
     * @throws Doctrine_Transaction_Exception           if the feature is not supported by the driver
477
     * @throws PDOException                             if something fails at the PDO level
478
     * @return void
479
     */
480
    public function setIsolation($isolation)
481
    {
482
        throw new Doctrine_Transaction_Exception('Transaction isolation levels not supported by this driver.');
483
    }
484
 
485
    /**
486
     * getTransactionIsolation
487
     *
488
     * fetches the current session transaction isolation level
489
     *
490
     * note: some drivers may support setting the transaction isolation level
491
     * but not fetching it
492
     *
493
     * @throws Doctrine_Transaction_Exception           if the feature is not supported by the driver
494
     * @throws PDOException                             if something fails at the PDO level
495
     * @return string                                   returns the current session transaction isolation level
496
     */
497
    public function getIsolation()
498
    {
499
        throw new Doctrine_Transaction_Exception('Fetching transaction isolation level not supported by this driver.');
500
    }
501
 
502
    /**
503
     * Initiates a transaction.
504
     *
505
     * This method must only be used by Doctrine itself to initiate transactions.
506
     * Userland-code must use {@link beginTransaction()}.
507
     */
508
    public function beginInternalTransaction($savepoint = null)
509
    {
510
        $this->_internalNestingLevel++;
511
        return $this->beginTransaction($savepoint);
512
    }
513
 
514
}