Transaction.php 14.7 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 210 211
     * @param string $savepoint                 name of a savepoint to set
     * @return integer                          current transaction nesting level
     */
lsmith's avatar
lsmith committed
212 213
    public function beginTransaction($savepoint = null)
    {
lsmith's avatar
lsmith committed
214
        if ( ! is_null($savepoint)) {
zYne's avatar
zYne committed
215
            $this->beginTransaction();
216

zYne's avatar
zYne committed
217
            $this->savePoints[] = $savepoint;
218 219 220

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

zYne's avatar
zYne committed
224
                $this->conn->getDbh()->beginTransaction();
225 226 227

                $this->conn->getAttribute(Doctrine::ATTR_LISTENER)->onTransactionBegin($this->conn);
            }
228 229 230 231 232 233 234
        }

        $level = ++$this->transactionLevel;

        return $level;
    }
    /**
zYne's avatar
zYne committed
235
     * commit
236 237
     * 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
238
     * auto-committing is disabled, otherwise it will fail.
239 240
     *
     * Listeners: onPreTransactionCommit, onTransactionCommit
241 242 243 244
     *
     * @param string $savepoint                 name of a savepoint to release
     * @throws Doctrine_Transaction_Exception   if the transaction fails at PDO level
     * @throws Doctrine_Validator_Exception     if the transaction fails due to record validations
zYne's avatar
zYne committed
245
     * @return boolean                          false if commit couldn't be performed, true otherwise
246
     */
lsmith's avatar
lsmith committed
247 248
    public function commit($savepoint = null)
    {
lsmith's avatar
lsmith committed
249
        if ($this->transactionLevel == 0)
zYne's avatar
zYne committed
250 251
            return false;

252
        if ( ! is_null($savepoint)) {
zYne's avatar
zYne committed
253 254
            $this->transactionLevel = $this->removeSavePoints($savepoint);

zYne's avatar
zYne committed
255
            $this->releaseSavePoint($savepoint);
lsmith's avatar
lsmith committed
256 257
        } else {
            if ($this->transactionLevel == 1) {
zYne's avatar
zYne committed
258
                $this->conn->getAttribute(Doctrine::ATTR_LISTENER)->onPreTransactionCommit($this->conn);
259

zYne's avatar
zYne committed
260 261
                try {
                    $this->bulkDelete();
262

zYne's avatar
zYne committed
263 264
                } catch(Exception $e) {
                    $this->rollback();
265

zYne's avatar
zYne committed
266
                    throw new Doctrine_Transaction_Exception($e->__toString());
zYne's avatar
zYne committed
267
                }
lsmith's avatar
lsmith committed
268
                if ( ! empty($this->invalid)) {
zYne's avatar
zYne committed
269
                    $this->rollback();
lsmith's avatar
lsmith committed
270

271 272
                    $tmp = $this->invalid;
                    $this->invalid = array();
273

zYne's avatar
zYne committed
274 275
                    throw new Doctrine_Validator_Exception($tmp);
                }
276

277 278 279 280 281 282
                // 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
283
                $this->conn->getDbh()->commit();
lsmith's avatar
lsmith committed
284

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

zYne's avatar
zYne committed
287
                $this->conn->getAttribute(Doctrine::ATTR_LISTENER)->onTransactionCommit($this->conn);
288 289
            }
        }
lsmith's avatar
lsmith committed
290

291 292
        $this->transactionLevel--;

zYne's avatar
zYne committed
293
        return true;
294 295 296 297 298 299 300 301 302 303 304 305
    }
    /**
     * 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.
     *
     * this method listens to onPreTransactionRollback and onTransactionRollback
     * eventlistener methods
     *
     * @param string $savepoint                 name of a savepoint to rollback to
zYne's avatar
zYne committed
306
     * @return boolean                          false if rollback couldn't be performed, true otherwise
307
     */
lsmith's avatar
lsmith committed
308 309
    public function rollback($savepoint = null)
    {
lsmith's avatar
lsmith committed
310
        if ($this->transactionLevel == 0)
zYne's avatar
zYne committed
311
            return false;
312 313 314

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

lsmith's avatar
lsmith committed
315
        if ( ! is_null($savepoint)) {
zYne's avatar
zYne committed
316 317
            $this->transactionLevel = $this->removeSavePoints($savepoint);

318 319
            $this->rollbackSavePoint($savepoint);
        } else {
320 321
            //$this->conn->unitOfWork->reset();
            $this->deteles = array();
322 323 324 325 326 327

            $this->transactionLevel = 0;

            $this->conn->getDbh()->rollback();
        }
        $this->conn->getAttribute(Doctrine::ATTR_LISTENER)->onTransactionRollback($this->conn);
lsmith's avatar
lsmith committed
328

zYne's avatar
zYne committed
329
        return true;
330 331 332 333 334 335 336 337
    }
    /**
     * releaseSavePoint
     * creates a new savepoint
     *
     * @param string $savepoint     name of a savepoint to create
     * @return void
     */
lsmith's avatar
lsmith committed
338 339
    protected function createSavePoint($savepoint)
    {
340 341 342 343 344 345 346 347 348
        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
349 350
    protected function releaseSavePoint($savepoint)
    {
351 352 353 354 355 356 357 358 359
        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
360 361
    protected function rollbackSavePoint($savepoint)
    {
362 363
        throw new Doctrine_Transaction_Exception('Savepoints not supported by this driver.');
    }
zYne's avatar
zYne committed
364 365 366 367 368 369 370 371
    /**
     * 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
372 373
    private function removeSavePoints($savepoint)
    {
zYne's avatar
zYne committed
374 375 376 377
        $i = array_search($savepoint, $this->savePoints);

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

lsmith's avatar
lsmith committed
378
        for ($x = $i; $x < count($this->savePoints); $x++) {
zYne's avatar
zYne committed
379 380 381 382
            unset($this->savePoints[$x]);
        }
        return ($c - $i);
    }
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
    /**
     * 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)
     *
401
     * @throws Doctrine_Transaction_Exception           if the feature is not supported by the driver
402 403 404
     * @throws PDOException                             if something fails at the PDO level
     * @return void
     */
lsmith's avatar
lsmith committed
405 406
    public function setIsolation($isolation)
    {
407
        throw new Doctrine_Transaction_Exception('Transaction isolation levels not supported by this driver.');
408 409 410 411 412 413 414
    }

    /**
     * getTransactionIsolation
     *
     * fetches the current session transaction isolation level
     *
lsmith's avatar
lsmith committed
415
     * note: some drivers may support setting the transaction isolation level
416
     * but not fetching it
417 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 string                                   returns the current session transaction isolation level
     */
lsmith's avatar
lsmith committed
422 423
    public function getIsolation()
    {
424
        throw new Doctrine_Transaction_Exception('Fetching transaction isolation level not supported by this driver.');
425
    }
426
}