Transaction.php 13.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 70 71 72
    /**
     * getState
     * returns the state of this connection
     *
     * @see Doctrine_Connection_Transaction::STATE_* constants
     * @return integer          the connection state
     */
lsmith's avatar
lsmith committed
73 74
    public function getState()
    {
lsmith's avatar
lsmith committed
75
        switch ($this->transactionLevel) {
76 77 78 79 80 81 82 83
            case 0:
                return Doctrine_Transaction::STATE_SLEEP;
                break;
            case 1:
                return Doctrine_Transaction::STATE_ACTIVE;
                break;
            default:
                return Doctrine_Transaction::STATE_BUSY;
84 85
        }
    }
86 87 88 89
    /**
     * adds record into pending delete list
     * @param Doctrine_Record $record
     */
lsmith's avatar
lsmith committed
90 91
    public function addDelete(Doctrine_Record $record)
    {
92 93
        $name = $record->getTable()->getComponentName();
        $this->delete[$name][] = $record;
lsmith's avatar
lsmith committed
94
    }
95 96 97 98 99
    /**
     * addInvalid
     * adds record into invalid records list
     *
     * @param Doctrine_Record $record
lsmith's avatar
lsmith committed
100
     * @return boolean        false if record already existed in invalid records list,
101 102
     *                        otherwise true
     */
lsmith's avatar
lsmith committed
103 104
    public function addInvalid(Doctrine_Record $record)
    {
lsmith's avatar
lsmith committed
105
        if (in_array($record, $this->invalid)) {
106
            return false;
lsmith's avatar
lsmith committed
107
        }
108 109 110 111 112 113 114 115 116
        $this->invalid[] = $record;
        return true;
    }

    /**
     * returns the pending delete list
     *
     * @return array
     */
lsmith's avatar
lsmith committed
117 118
    public function getDeletes()
    {
119 120 121 122 123 124 125 126
        return $this->delete;
    }
    /**
     * bulkDelete
     * deletes all records from the pending delete list
     *
     * @return void
     */
lsmith's avatar
lsmith committed
127 128
    public function bulkDelete()
    {
lsmith's avatar
lsmith committed
129
        foreach ($this->delete as $name => $deletes) {
130 131
            $record = false;
            $ids    = array();
zYne's avatar
zYne committed
132

zYne's avatar
zYne committed
133
    	    if (is_array($deletes[count($deletes)-1]->getTable()->getIdentifier())) {
zYne's avatar
zYne committed
134
                foreach ($deletes as $k => $record) {
zYne's avatar
zYne committed
135
                    $cond = array();
zYne's avatar
zYne committed
136
                    $ids = $record->obtainIdentifier();
zYne's avatar
zYne committed
137 138 139
                    $query = 'DELETE FROM ' 
                           . $this->conn->quoteIdentifier($record->getTable()->getTableName()) 
                           . ' WHERE ';
lsmith's avatar
lsmith committed
140

zYne's avatar
zYne committed
141 142
                    foreach (array_keys($ids) as $id){
                        $cond[] = $id . ' = ? ';
zYne's avatar
zYne committed
143
                    }
zYne's avatar
zYne committed
144 145

                    $query = $query . implode(' AND ', $cond);
zYne's avatar
zYne committed
146 147 148 149 150 151 152 153
                    $this->conn->execute($query, array_values($ids));
                }
    	    } else {
    		    foreach ($deletes as $k => $record) {
                    $ids[] = $record->getIncremented();
                    $record->assignIdentifier(false);
    		    }
    		    if ($record instanceof Doctrine_Record) {
zYne's avatar
zYne committed
154
        			$params = substr(str_repeat('?, ', count($ids)),0,-2);
zYne's avatar
zYne committed
155 156
    
        			$query = 'DELETE FROM '
zYne's avatar
zYne committed
157
        				   . $this->conn->quoteIdentifier($record->getTable()->getTableName())
zYne's avatar
zYne committed
158 159 160 161 162 163 164
        				   . ' WHERE '
        				   . $record->getTable()->getIdentifier()
        				   . ' IN(' . $params . ')';
        
        			$this->conn->execute($query, $ids);
    		    }
    	    }
165 166 167 168

        }
        $this->delete = array();
    }
169 170 171 172 173 174
    /**
     * getTransactionLevel
     * get the current transaction nesting level
     *
     * @return integer
     */
lsmith's avatar
lsmith committed
175 176
    public function getTransactionLevel()
    {
177 178 179 180 181 182
        return $this->transactionLevel;
    }
    /**
     * beginTransaction
     * Start a transaction or set a savepoint.
     *
lsmith's avatar
lsmith committed
183
     * if trying to set a savepoint and there is no active transaction
zYne's avatar
zYne committed
184 185
     * a new transaction is being started
     *
186 187
     * Listeners: onPreTransactionBegin, onTransactionBegin
     *
188 189 190
     * @param string $savepoint                 name of a savepoint to set
     * @return integer                          current transaction nesting level
     */
lsmith's avatar
lsmith committed
191 192
    public function beginTransaction($savepoint = null)
    {
lsmith's avatar
lsmith committed
193
        if ( ! is_null($savepoint)) {
zYne's avatar
zYne committed
194
            $this->beginTransaction();
195

zYne's avatar
zYne committed
196
            $this->savePoints[] = $savepoint;
197 198 199

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

zYne's avatar
zYne committed
203
                $this->conn->getDbh()->beginTransaction();
204 205 206

                $this->conn->getAttribute(Doctrine::ATTR_LISTENER)->onTransactionBegin($this->conn);
            }
207 208 209 210 211 212 213
        }

        $level = ++$this->transactionLevel;

        return $level;
    }
    /**
zYne's avatar
zYne committed
214
     * commit
215 216
     * 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
217
     * auto-committing is disabled, otherwise it will fail.
218 219
     *
     * Listeners: onPreTransactionCommit, onTransactionCommit
220 221 222 223
     *
     * @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
224
     * @return boolean                          false if commit couldn't be performed, true otherwise
225
     */
lsmith's avatar
lsmith committed
226 227
    public function commit($savepoint = null)
    {
lsmith's avatar
lsmith committed
228
        if ($this->transactionLevel == 0)
zYne's avatar
zYne committed
229 230
            return false;

231
        if ( ! is_null($savepoint)) {
zYne's avatar
zYne committed
232 233
            $this->transactionLevel = $this->removeSavePoints($savepoint);

zYne's avatar
zYne committed
234
            $this->releaseSavePoint($savepoint);
lsmith's avatar
lsmith committed
235 236
        } else {
            if ($this->transactionLevel == 1) {
zYne's avatar
zYne committed
237
                $this->conn->getAttribute(Doctrine::ATTR_LISTENER)->onPreTransactionCommit($this->conn);
238

zYne's avatar
zYne committed
239 240
                try {
                    $this->bulkDelete();
241

zYne's avatar
zYne committed
242 243
                } catch(Exception $e) {
                    $this->rollback();
244

zYne's avatar
zYne committed
245
                    throw new Doctrine_Transaction_Exception($e->__toString());
zYne's avatar
zYne committed
246
                }
lsmith's avatar
lsmith committed
247
                if ( ! empty($this->invalid)) {
zYne's avatar
zYne committed
248
                    $this->rollback();
lsmith's avatar
lsmith committed
249

250 251
                    $tmp = $this->invalid;
                    $this->invalid = array();
252

zYne's avatar
zYne committed
253 254
                    throw new Doctrine_Validator_Exception($tmp);
                }
255

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

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

zYne's avatar
zYne committed
260
                $this->conn->getAttribute(Doctrine::ATTR_LISTENER)->onTransactionCommit($this->conn);
261 262
            }
        }
lsmith's avatar
lsmith committed
263

264 265
        $this->transactionLevel--;

zYne's avatar
zYne committed
266
        return true;
267 268 269 270 271 272 273 274 275 276 277 278
    }
    /**
     * 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
279
     * @return boolean                          false if rollback couldn't be performed, true otherwise
280
     */
lsmith's avatar
lsmith committed
281 282
    public function rollback($savepoint = null)
    {
lsmith's avatar
lsmith committed
283
        if ($this->transactionLevel == 0)
zYne's avatar
zYne committed
284
            return false;
285 286 287

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

lsmith's avatar
lsmith committed
288
        if ( ! is_null($savepoint)) {
zYne's avatar
zYne committed
289 290
            $this->transactionLevel = $this->removeSavePoints($savepoint);

291 292
            $this->rollbackSavePoint($savepoint);
        } else {
293 294
            //$this->conn->unitOfWork->reset();
            $this->deteles = array();
295 296 297 298 299 300

            $this->transactionLevel = 0;

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

zYne's avatar
zYne committed
302
        return true;
303 304 305 306 307 308 309 310
    }
    /**
     * releaseSavePoint
     * creates a new savepoint
     *
     * @param string $savepoint     name of a savepoint to create
     * @return void
     */
lsmith's avatar
lsmith committed
311 312
    protected function createSavePoint($savepoint)
    {
313 314 315 316 317 318 319 320 321
        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
322 323
    protected function releaseSavePoint($savepoint)
    {
324 325 326 327 328 329 330 331 332
        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
333 334
    protected function rollbackSavePoint($savepoint)
    {
335 336
        throw new Doctrine_Transaction_Exception('Savepoints not supported by this driver.');
    }
zYne's avatar
zYne committed
337 338 339 340 341 342 343 344
    /**
     * 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
345 346
    private function removeSavePoints($savepoint)
    {
zYne's avatar
zYne committed
347 348 349 350
        $i = array_search($savepoint, $this->savePoints);

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

lsmith's avatar
lsmith committed
351
        for ($x = $i; $x < count($this->savePoints); $x++) {
zYne's avatar
zYne committed
352 353 354 355
            unset($this->savePoints[$x]);
        }
        return ($c - $i);
    }
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
    /**
     * 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)
     *
374
     * @throws Doctrine_Transaction_Exception           if the feature is not supported by the driver
375 376 377
     * @throws PDOException                             if something fails at the PDO level
     * @return void
     */
lsmith's avatar
lsmith committed
378 379
    public function setIsolation($isolation)
    {
380
        throw new Doctrine_Transaction_Exception('Transaction isolation levels not supported by this driver.');
381 382 383 384 385 386 387
    }

    /**
     * getTransactionIsolation
     *
     * fetches the current session transaction isolation level
     *
lsmith's avatar
lsmith committed
388
     * note: some drivers may support setting the transaction isolation level
389
     * but not fetching it
390 391
     *
     * @throws Doctrine_Transaction_Exception           if the feature is not supported by the driver
392 393 394
     * @throws PDOException                             if something fails at the PDO level
     * @return string                                   returns the current session transaction isolation level
     */
lsmith's avatar
lsmith committed
395 396
    public function getIsolation()
    {
397
        throw new Doctrine_Transaction_Exception('Fetching transaction isolation level not supported by this driver.');
398
    }
399
}