Transaction.php 15.5 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 227
                $event = new Doctrine_Event($this, Doctrine_Event::BEGIN);

                $this->conn->getAttribute(Doctrine::ATTR_LISTENER)->onPreTransactionBegin($event);
228

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

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

        $level = ++$this->transactionLevel;

        return $level;
    }
    /**
zYne's avatar
zYne committed
244
     * commit
245 246
     * 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
247
     * auto-committing is disabled, otherwise it will fail.
248 249
     *
     * Listeners: onPreTransactionCommit, onTransactionCommit
250 251
     *
     * @param string $savepoint                 name of a savepoint to release
252
     * @throws Doctrine_Transaction_Exception   if the transaction fails at database level
253
     * @throws Doctrine_Validator_Exception     if the transaction fails due to record validations
zYne's avatar
zYne committed
254
     * @return boolean                          false if commit couldn't be performed, true otherwise
255
     */
lsmith's avatar
lsmith committed
256 257
    public function commit($savepoint = null)
    {
258 259 260
    	$this->conn->connect();

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

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

zYne's avatar
zYne committed
267
            $this->releaseSavePoint($savepoint);
lsmith's avatar
lsmith committed
268 269
        } else {
            if ($this->transactionLevel == 1) {
270 271
                $event = new Doctrine_Event($this, Doctrine_Event::COMMIT);
                $this->conn->getAttribute(Doctrine::ATTR_LISTENER)->onPreTransactionCommit($event);
272

zYne's avatar
zYne committed
273 274
                try {
                    $this->bulkDelete();
275

zYne's avatar
zYne committed
276 277
                } catch(Exception $e) {
                    $this->rollback();
278

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

284 285
                    $tmp = $this->invalid;
                    $this->invalid = array();
286

zYne's avatar
zYne committed
287 288
                    throw new Doctrine_Validator_Exception($tmp);
                }
289

290 291 292 293 294 295
                // 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
296
                $this->conn->getDbh()->commit();
lsmith's avatar
lsmith committed
297

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

300
                $this->conn->getAttribute(Doctrine::ATTR_LISTENER)->onTransactionCommit($event);
301 302
            }
        }
lsmith's avatar
lsmith committed
303

304 305
        $this->transactionLevel--;

zYne's avatar
zYne committed
306
        return true;
307 308 309 310 311 312 313 314
    }
    /**
     * 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.
     *
315
     * this method can be listened with onPreTransactionRollback and onTransactionRollback
316 317
     * eventlistener methods
     *
318 319
     * @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
320
     * @return boolean                          false if rollback couldn't be performed, true otherwise
321
     */
lsmith's avatar
lsmith committed
322 323
    public function rollback($savepoint = null)
    {
324 325 326
        $this->conn->connect();

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

330 331 332
        $event = new Doctrine_Event($this, Doctrine_Event::ROLLBACK);

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

lsmith's avatar
lsmith committed
334
        if ( ! is_null($savepoint)) {
zYne's avatar
zYne committed
335 336
            $this->transactionLevel = $this->removeSavePoints($savepoint);

337 338
            $this->rollbackSavePoint($savepoint);
        } else {
339 340
            //$this->conn->unitOfWork->reset();
            $this->deteles = array();
341 342

            $this->transactionLevel = 0;
343 344 345 346 347
            try {
                $this->conn->getDbh()->rollback();
            } catch (Exception $e) {
                throw new Doctrine_Transaction_Exception($e->getMessage());
            }
348
        }
349
        $this->conn->getAttribute(Doctrine::ATTR_LISTENER)->onTransactionRollback($event);
lsmith's avatar
lsmith committed
350

zYne's avatar
zYne committed
351
        return true;
352 353 354 355 356 357 358 359
    }
    /**
     * releaseSavePoint
     * creates a new savepoint
     *
     * @param string $savepoint     name of a savepoint to create
     * @return void
     */
lsmith's avatar
lsmith committed
360 361
    protected function createSavePoint($savepoint)
    {
362 363 364 365 366 367 368 369 370
        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
371 372
    protected function releaseSavePoint($savepoint)
    {
373 374 375 376 377 378 379 380 381
        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
382 383
    protected function rollbackSavePoint($savepoint)
    {
384 385
        throw new Doctrine_Transaction_Exception('Savepoints not supported by this driver.');
    }
zYne's avatar
zYne committed
386 387 388 389 390 391 392 393
    /**
     * 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
394 395
    private function removeSavePoints($savepoint)
    {
zYne's avatar
zYne committed
396 397 398 399
        $i = array_search($savepoint, $this->savePoints);

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

lsmith's avatar
lsmith committed
400
        for ($x = $i; $x < count($this->savePoints); $x++) {
zYne's avatar
zYne committed
401 402 403 404
            unset($this->savePoints[$x]);
        }
        return ($c - $i);
    }
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
    /**
     * 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)
     *
423
     * @throws Doctrine_Transaction_Exception           if the feature is not supported by the driver
424 425 426
     * @throws PDOException                             if something fails at the PDO level
     * @return void
     */
lsmith's avatar
lsmith committed
427 428
    public function setIsolation($isolation)
    {
429
        throw new Doctrine_Transaction_Exception('Transaction isolation levels not supported by this driver.');
430 431 432 433 434 435 436
    }

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