Transaction.php 15.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
<?php
/*
 *  $Id$
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the LGPL. For more information, see
 * <http://www.phpdoctrine.com>.
 */
21
Doctrine::autoload('Doctrine_Connection_Module');
22
/**
zYne's avatar
zYne committed
23 24
 * Doctrine_Transaction
 * Handles transaction savepoint and isolation abstraction
25 26
 *
 * @author      Konsta Vesterinen <kvesteri@cc.hut.fi>
zYne's avatar
zYne committed
27
 * @author      Lukas Smith <smith@pooteeweet.org> (PEAR MDB2 library)
28 29 30 31 32 33 34
 * @license     http://www.opensource.org/licenses/lgpl-license.php LGPL
 * @package     Doctrine
 * @category    Object Relational Mapping
 * @link        www.phpdoctrine.com
 * @since       1.0
 * @version     $Revision$
 */
lsmith's avatar
lsmith committed
35 36
class Doctrine_Transaction extends Doctrine_Connection_Module
{
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
    const STATE_ACTIVE      = 1;
45 46 47
    /**
     * Doctrine_Transaction is in busy state when it has multiple active transactions
     */
48
    const STATE_BUSY        = 2;
49
    /**
zYne's avatar
zYne committed
50
     * @var integer $transactionLevel      the nesting level of transactions, used by transaction methods
51 52
     */
    protected $transactionLevel  = 0;
53 54 55 56 57 58 59 60 61
    /**
     * @var array $invalid                  an array containing all invalid records within this transaction
     */
    protected $invalid          = array();
    /**
     * @var array $delete                   two dimensional pending delete list, the records in
     *                                      this list will be deleted when transaction is committed
     */
    protected $delete           = array();
zYne's avatar
zYne committed
62 63 64
    /**
     * @var array $savepoints               an array containing all savepoints
     */
zYne's avatar
zYne committed
65
    protected $savePoints       = array();
66 67 68 69
    /**
     * @var array $_collections             an array of Doctrine_Collection objects that were affected during the Transaction
     */
    protected $_collections     = array();
zYne's avatar
zYne committed
70
    /**
71
     * addCollection
zYne's avatar
zYne committed
72 73 74 75 76
     * adds a collection in the internal array of collections
     *
     * at the end of each commit this array is looped over and
     * of every collection Doctrine then takes a snapshot in order
     * to keep the collections up to date with the database
77
     *
zYne's avatar
zYne committed
78 79
     * @param Doctrine_Collection $coll     a collection to be added
     * @return void
80 81 82 83 84
     */
    public function addCollection(Doctrine_Collection $coll)
    {
        $this->_collections[] = $coll;
    }
85 86 87 88 89 90 91
    /**
     * getState
     * returns the state of this connection
     *
     * @see Doctrine_Connection_Transaction::STATE_* constants
     * @return integer          the connection state
     */
lsmith's avatar
lsmith committed
92 93
    public function getState()
    {
lsmith's avatar
lsmith committed
94
        switch ($this->transactionLevel) {
95 96 97 98 99 100 101 102
            case 0:
                return Doctrine_Transaction::STATE_SLEEP;
                break;
            case 1:
                return Doctrine_Transaction::STATE_ACTIVE;
                break;
            default:
                return Doctrine_Transaction::STATE_BUSY;
103 104
        }
    }
105
    /**
zYne's avatar
zYne committed
106
     * addDelete
107
     * adds record into pending delete list
zYne's avatar
zYne committed
108 109 110
     *
     * @param Doctrine_Record $record       a record to be added
     * @return void
111
     */
lsmith's avatar
lsmith committed
112 113
    public function addDelete(Doctrine_Record $record)
    {
114 115
        $name = $record->getTable()->getComponentName();
        $this->delete[$name][] = $record;
lsmith's avatar
lsmith committed
116
    }
117 118 119 120 121
    /**
     * addInvalid
     * adds record into invalid records list
     *
     * @param Doctrine_Record $record
lsmith's avatar
lsmith committed
122
     * @return boolean        false if record already existed in invalid records list,
123 124
     *                        otherwise true
     */
lsmith's avatar
lsmith committed
125 126
    public function addInvalid(Doctrine_Record $record)
    {
lsmith's avatar
lsmith committed
127
        if (in_array($record, $this->invalid)) {
128
            return false;
lsmith's avatar
lsmith committed
129
        }
130 131 132 133 134 135 136 137 138
        $this->invalid[] = $record;
        return true;
    }

    /**
     * returns the pending delete list
     *
     * @return array
     */
lsmith's avatar
lsmith committed
139 140
    public function getDeletes()
    {
141 142 143 144 145 146 147 148
        return $this->delete;
    }
    /**
     * bulkDelete
     * deletes all records from the pending delete list
     *
     * @return void
     */
lsmith's avatar
lsmith committed
149 150
    public function bulkDelete()
    {
lsmith's avatar
lsmith committed
151
        foreach ($this->delete as $name => $deletes) {
152 153
            $record = false;
            $ids    = array();
zYne's avatar
zYne committed
154

zYne's avatar
zYne committed
155
    	    if (is_array($deletes[count($deletes)-1]->getTable()->getIdentifier())) {
zYne's avatar
zYne committed
156
                foreach ($deletes as $k => $record) {
zYne's avatar
zYne committed
157
                    $cond = array();
zYne's avatar
zYne committed
158
                    $ids = $record->obtainIdentifier();
zYne's avatar
zYne committed
159 160 161
                    $query = 'DELETE FROM ' 
                           . $this->conn->quoteIdentifier($record->getTable()->getTableName()) 
                           . ' WHERE ';
lsmith's avatar
lsmith committed
162

zYne's avatar
zYne committed
163 164
                    foreach (array_keys($ids) as $id){
                        $cond[] = $id . ' = ? ';
zYne's avatar
zYne committed
165
                    }
zYne's avatar
zYne committed
166 167

                    $query = $query . implode(' AND ', $cond);
zYne's avatar
zYne committed
168 169 170 171 172 173 174
                    $this->conn->execute($query, array_values($ids));
                }
    	    } else {
    		    foreach ($deletes as $k => $record) {
                    $ids[] = $record->getIncremented();
    		    }
    		    if ($record instanceof Doctrine_Record) {
zYne's avatar
zYne committed
175
        			$params = substr(str_repeat('?, ', count($ids)),0,-2);
zYne's avatar
zYne committed
176 177
    
        			$query = 'DELETE FROM '
zYne's avatar
zYne committed
178
        				   . $this->conn->quoteIdentifier($record->getTable()->getTableName())
zYne's avatar
zYne committed
179 180 181 182 183 184 185
        				   . ' WHERE '
        				   . $record->getTable()->getIdentifier()
        				   . ' IN(' . $params . ')';
        
        			$this->conn->execute($query, $ids);
    		    }
    	    }
186 187 188 189

        }
        $this->delete = array();
    }
190 191 192 193 194 195
    /**
     * getTransactionLevel
     * get the current transaction nesting level
     *
     * @return integer
     */
lsmith's avatar
lsmith committed
196 197
    public function getTransactionLevel()
    {
198 199 200 201 202 203
        return $this->transactionLevel;
    }
    /**
     * beginTransaction
     * Start a transaction or set a savepoint.
     *
lsmith's avatar
lsmith committed
204
     * if trying to set a savepoint and there is no active transaction
zYne's avatar
zYne committed
205 206
     * a new transaction is being started
     *
207 208
     * Listeners: onPreTransactionBegin, onTransactionBegin
     *
209
     * @param string $savepoint                 name of a savepoint to set
210
     * @throws Doctrine_Transaction_Exception   if the transaction fails at database level     
211 212
     * @return integer                          current transaction nesting level
     */
lsmith's avatar
lsmith committed
213 214
    public function beginTransaction($savepoint = null)
    {
215 216
        $this->conn->connect();

lsmith's avatar
lsmith committed
217
        if ( ! is_null($savepoint)) {
zYne's avatar
zYne committed
218
            $this->beginTransaction();
219

zYne's avatar
zYne committed
220
            $this->savePoints[] = $savepoint;
221 222 223

            $this->createSavePoint($savepoint);
        } else {
lsmith's avatar
lsmith committed
224
            if ($this->transactionLevel == 0) {
225 226
                $this->conn->getAttribute(Doctrine::ATTR_LISTENER)->onPreTransactionBegin($this->conn);

227 228 229 230 231
                try {
                    $this->conn->getDbh()->beginTransaction();
                } catch(Exception $e) {
                    throw new Doctrine_Transaction_Exception($e->getMessage());
                }
232 233 234

                $this->conn->getAttribute(Doctrine::ATTR_LISTENER)->onTransactionBegin($this->conn);
            }
235 236 237 238 239 240 241
        }

        $level = ++$this->transactionLevel;

        return $level;
    }
    /**
zYne's avatar
zYne committed
242
     * commit
243 244
     * Commit the database changes done during a transaction that is in
     * progress or release a savepoint. This function may only be called when
lsmith's avatar
lsmith committed
245
     * auto-committing is disabled, otherwise it will fail.
246 247
     *
     * Listeners: onPreTransactionCommit, onTransactionCommit
248 249
     *
     * @param string $savepoint                 name of a savepoint to release
250
     * @throws Doctrine_Transaction_Exception   if the transaction fails at database level
251
     * @throws Doctrine_Validator_Exception     if the transaction fails due to record validations
zYne's avatar
zYne committed
252
     * @return boolean                          false if commit couldn't be performed, true otherwise
253
     */
lsmith's avatar
lsmith committed
254 255
    public function commit($savepoint = null)
    {
256 257 258
    	$this->conn->connect();

        if ($this->transactionLevel == 0) {
zYne's avatar
zYne committed
259
            return false;
260
        }
zYne's avatar
zYne committed
261

262
        if ( ! is_null($savepoint)) {
zYne's avatar
zYne committed
263 264
            $this->transactionLevel = $this->removeSavePoints($savepoint);

zYne's avatar
zYne committed
265
            $this->releaseSavePoint($savepoint);
lsmith's avatar
lsmith committed
266 267
        } else {
            if ($this->transactionLevel == 1) {
zYne's avatar
zYne committed
268
                $this->conn->getAttribute(Doctrine::ATTR_LISTENER)->onPreTransactionCommit($this->conn);
269

zYne's avatar
zYne committed
270 271
                try {
                    $this->bulkDelete();
272

zYne's avatar
zYne committed
273 274
                } catch(Exception $e) {
                    $this->rollback();
275

276
                    throw new Doctrine_Transaction_Exception($e->getMessage());
zYne's avatar
zYne committed
277
                }
lsmith's avatar
lsmith committed
278
                if ( ! empty($this->invalid)) {
zYne's avatar
zYne committed
279
                    $this->rollback();
lsmith's avatar
lsmith committed
280

281 282
                    $tmp = $this->invalid;
                    $this->invalid = array();
283

zYne's avatar
zYne committed
284 285
                    throw new Doctrine_Validator_Exception($tmp);
                }
286

287 288 289 290 291 292
                // take snapshots of all collections used within this transaction
                foreach (array_unique($this->_collections) as $coll) {
                    $coll->takeSnapshot();
                }
                $this->_collections = array();

zYne's avatar
zYne committed
293
                $this->conn->getDbh()->commit();
lsmith's avatar
lsmith committed
294

295
                //$this->conn->unitOfWork->reset();
lsmith's avatar
lsmith committed
296

zYne's avatar
zYne committed
297
                $this->conn->getAttribute(Doctrine::ATTR_LISTENER)->onTransactionCommit($this->conn);
298 299
            }
        }
lsmith's avatar
lsmith committed
300

301 302
        $this->transactionLevel--;

zYne's avatar
zYne committed
303
        return true;
304 305 306 307 308 309 310 311
    }
    /**
     * rollback
     * Cancel any database changes done during a transaction or since a specific
     * savepoint that is in progress. This function may only be called when
     * auto-committing is disabled, otherwise it will fail. Therefore, a new
     * transaction is implicitly started after canceling the pending changes.
     *
312
     * this method can be listened with onPreTransactionRollback and onTransactionRollback
313 314
     * eventlistener methods
     *
315 316
     * @param string $savepoint                 name of a savepoint to rollback to   
     * @throws Doctrine_Transaction_Exception   if the rollback operation fails at database level
zYne's avatar
zYne committed
317
     * @return boolean                          false if rollback couldn't be performed, true otherwise
318
     */
lsmith's avatar
lsmith committed
319 320
    public function rollback($savepoint = null)
    {
321 322 323
        $this->conn->connect();

        if ($this->transactionLevel == 0) {
zYne's avatar
zYne committed
324
            return false;
325
        }
326 327 328

        $this->conn->getAttribute(Doctrine::ATTR_LISTENER)->onPreTransactionRollback($this->conn);

lsmith's avatar
lsmith committed
329
        if ( ! is_null($savepoint)) {
zYne's avatar
zYne committed
330 331
            $this->transactionLevel = $this->removeSavePoints($savepoint);

332 333
            $this->rollbackSavePoint($savepoint);
        } else {
334 335
            //$this->conn->unitOfWork->reset();
            $this->deteles = array();
336 337

            $this->transactionLevel = 0;
338 339 340 341 342
            try {
                $this->conn->getDbh()->rollback();
            } catch (Exception $e) {
                throw new Doctrine_Transaction_Exception($e->getMessage());
            }
343 344
        }
        $this->conn->getAttribute(Doctrine::ATTR_LISTENER)->onTransactionRollback($this->conn);
lsmith's avatar
lsmith committed
345

zYne's avatar
zYne committed
346
        return true;
347 348 349 350 351 352 353 354
    }
    /**
     * releaseSavePoint
     * creates a new savepoint
     *
     * @param string $savepoint     name of a savepoint to create
     * @return void
     */
lsmith's avatar
lsmith committed
355 356
    protected function createSavePoint($savepoint)
    {
357 358 359 360 361 362 363 364 365
        throw new Doctrine_Transaction_Exception('Savepoints not supported by this driver.');
    }
    /**
     * releaseSavePoint
     * releases given savepoint
     *
     * @param string $savepoint     name of a savepoint to release
     * @return void
     */
lsmith's avatar
lsmith committed
366 367
    protected function releaseSavePoint($savepoint)
    {
368 369 370 371 372 373 374 375 376
        throw new Doctrine_Transaction_Exception('Savepoints not supported by this driver.');
    }
    /**
     * rollbackSavePoint
     * releases given savepoint
     *
     * @param string $savepoint     name of a savepoint to rollback to
     * @return void
     */
lsmith's avatar
lsmith committed
377 378
    protected function rollbackSavePoint($savepoint)
    {
379 380
        throw new Doctrine_Transaction_Exception('Savepoints not supported by this driver.');
    }
zYne's avatar
zYne committed
381 382 383 384 385 386 387 388
    /**
     * removeSavePoints
     * removes a savepoint from the internal savePoints array of this transaction object
     * and all its children savepoints
     *
     * @param sring $savepoint      name of the savepoint to remove
     * @return integer              the current transaction level
     */
lsmith's avatar
lsmith committed
389 390
    private function removeSavePoints($savepoint)
    {
zYne's avatar
zYne committed
391 392 393 394
        $i = array_search($savepoint, $this->savePoints);

        $c = count($this->savePoints);

lsmith's avatar
lsmith committed
395
        for ($x = $i; $x < count($this->savePoints); $x++) {
zYne's avatar
zYne committed
396 397 398 399
            unset($this->savePoints[$x]);
        }
        return ($c - $i);
    }
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417
    /**
     * setIsolation
     *
     * Set the transacton isolation level.
     * (implemented by the connection drivers)
     *
     * example:
     *
     * <code>
     * $tx->setIsolation('READ UNCOMMITTED');
     * </code>
     *
     * @param   string  standard isolation level
     *                  READ UNCOMMITTED (allows dirty reads)
     *                  READ COMMITTED (prevents dirty reads)
     *                  REPEATABLE READ (prevents nonrepeatable reads)
     *                  SERIALIZABLE (prevents phantom reads)
     *
418
     * @throws Doctrine_Transaction_Exception           if the feature is not supported by the driver
419 420 421
     * @throws PDOException                             if something fails at the PDO level
     * @return void
     */
lsmith's avatar
lsmith committed
422 423
    public function setIsolation($isolation)
    {
424
        throw new Doctrine_Transaction_Exception('Transaction isolation levels not supported by this driver.');
425 426 427 428 429 430 431
    }

    /**
     * getTransactionIsolation
     *
     * fetches the current session transaction isolation level
     *
lsmith's avatar
lsmith committed
432
     * note: some drivers may support setting the transaction isolation level
433
     * but not fetching it
434 435
     *
     * @throws Doctrine_Transaction_Exception           if the feature is not supported by the driver
436 437 438
     * @throws PDOException                             if something fails at the PDO level
     * @return string                                   returns the current session transaction isolation level
     */
lsmith's avatar
lsmith committed
439 440
    public function getIsolation()
    {
441
        throw new Doctrine_Transaction_Exception('Fetching transaction isolation level not supported by this driver.');
442
    }
443
}