Completed
Push — 2.1 ( d4e7cf...610019 )
by Alexander
13:23
created

Transaction   A

Complexity

Total Complexity 20

Size/Duplication

Total Lines 180
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 70%

Importance

Changes 0
Metric Value
wmc 20
lcom 1
cbo 6
dl 0
loc 180
ccs 42
cts 60
cp 0.7
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A getIsActive() 0 4 3
A getLevel() 0 4 1
B begin() 0 29 6
B commit() 0 22 4
B rollBack() 0 26 4
A setIsolationLevel() 0 8 2
1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\db;
9
10
use Yii;
11
use yii\base\InvalidConfigException;
12
13
/**
14
 * Transaction represents a DB transaction.
15
 *
16
 * It is usually created by calling [[Connection::beginTransaction()]].
17
 *
18
 * The following code is a typical example of using transactions (note that some
19
 * DBMS may not support transactions):
20
 *
21
 * ```php
22
 * $transaction = $connection->beginTransaction();
23
 * try {
24
 *     $connection->createCommand($sql1)->execute();
25
 *     $connection->createCommand($sql2)->execute();
26
 *     //.... other SQL executions
27
 *     $transaction->commit();
28
 * } catch (\Throwable $e) {
29
 *     $transaction->rollBack();
30
 *     throw $e;
31
 * }
32
 * ```
33
 *
34
 * @property bool $isActive Whether this transaction is active. Only an active transaction can [[commit()]] or
35
 * [[rollBack()]]. This property is read-only.
36
 * @property string $isolationLevel The transaction isolation level to use for this transaction. This can be
37
 * one of [[READ_UNCOMMITTED]], [[READ_COMMITTED]], [[REPEATABLE_READ]] and [[SERIALIZABLE]] but also a string
38
 * containing DBMS specific syntax to be used after `SET TRANSACTION ISOLATION LEVEL`. This property is
39
 * write-only.
40
 * @property int $level The current nesting level of the transaction. This property is read-only.
41
 *
42
 * @author Qiang Xue <[email protected]>
43
 * @since 2.0
44
 */
45
class Transaction extends \yii\base\BaseObject
46
{
47
    /**
48
     * A constant representing the transaction isolation level `READ UNCOMMITTED`.
49
     * @see http://en.wikipedia.org/wiki/Isolation_%28database_systems%29#Isolation_levels
50
     */
51
    const READ_UNCOMMITTED = 'READ UNCOMMITTED';
52
    /**
53
     * A constant representing the transaction isolation level `READ COMMITTED`.
54
     * @see http://en.wikipedia.org/wiki/Isolation_%28database_systems%29#Isolation_levels
55
     */
56
    const READ_COMMITTED = 'READ COMMITTED';
57
    /**
58
     * A constant representing the transaction isolation level `REPEATABLE READ`.
59
     * @see http://en.wikipedia.org/wiki/Isolation_%28database_systems%29#Isolation_levels
60
     */
61
    const REPEATABLE_READ = 'REPEATABLE READ';
62
    /**
63
     * A constant representing the transaction isolation level `SERIALIZABLE`.
64
     * @see http://en.wikipedia.org/wiki/Isolation_%28database_systems%29#Isolation_levels
65
     */
66
    const SERIALIZABLE = 'SERIALIZABLE';
67
68
    /**
69
     * @var Connection the database connection that this transaction is associated with.
70
     */
71
    public $db;
72
73
    /**
74
     * @var int the nesting level of the transaction. 0 means the outermost level.
75
     */
76
    private $_level = 0;
77
78
79
    /**
80
     * Returns a value indicating whether this transaction is active.
81
     * @return bool whether this transaction is active. Only an active transaction
82
     * can [[commit()]] or [[rollBack()]].
83
     */
84 30
    public function getIsActive()
85
    {
86 30
        return $this->_level > 0 && $this->db && $this->db->isActive;
87
    }
88
89
    /**
90
     * Begins a transaction.
91
     * @param string|null $isolationLevel The [isolation level][] to use for this transaction.
92
     * This can be one of [[READ_UNCOMMITTED]], [[READ_COMMITTED]], [[REPEATABLE_READ]] and [[SERIALIZABLE]] but
93
     * also a string containing DBMS specific syntax to be used after `SET TRANSACTION ISOLATION LEVEL`.
94
     * If not specified (`null`) the isolation level will not be set explicitly and the DBMS default will be used.
95
     *
96
     * > Note: This setting does not work for PostgreSQL, where setting the isolation level before the transaction
97
     * has no effect. You have to call [[setIsolationLevel()]] in this case after the transaction has started.
98
     *
99
     * > Note: Some DBMS allow setting of the isolation level only for the whole connection so subsequent transactions
100
     * may get the same isolation level even if you did not specify any. When using this feature
101
     * you may need to set the isolation level for all transactions explicitly to avoid conflicting settings.
102
     * At the time of this writing affected DBMS are MSSQL and SQLite.
103
     *
104
     * [isolation level]: http://en.wikipedia.org/wiki/Isolation_%28database_systems%29#Isolation_levels
105
     * @throws InvalidConfigException if [[db]] is `null`.
106
     */
107 30
    public function begin($isolationLevel = null)
108
    {
109 30
        if ($this->db === null) {
110
            throw new InvalidConfigException('Transaction::db must be set.');
111
        }
112 30
        $this->db->open();
113
114 30
        if ($this->_level === 0) {
115 30
            if ($isolationLevel !== null) {
116 6
                $this->db->getSchema()->setTransactionIsolationLevel($isolationLevel);
117
            }
118 30
            Yii::trace('Begin transaction' . ($isolationLevel ? ' with isolation level ' . $isolationLevel : ''), __METHOD__);
119
120 30
            $this->db->trigger(Connection::EVENT_BEGIN_TRANSACTION);
121 30
            $this->db->pdo->beginTransaction();
122 30
            $this->_level = 1;
123
124 30
            return;
125
        }
126
127 4
        $schema = $this->db->getSchema();
128 4
        if ($schema->supportsSavepoint()) {
129 4
            Yii::trace('Set savepoint ' . $this->_level, __METHOD__);
130 4
            $schema->createSavepoint('LEVEL' . $this->_level);
131
        } else {
132
            Yii::info('Transaction not started: nested transaction not supported', __METHOD__);
133
        }
134 4
        $this->_level++;
135 4
    }
136
137
    /**
138
     * Commits a transaction.
139
     * @throws Exception if the transaction is not active
140
     */
141 19
    public function commit()
142
    {
143 19
        if (!$this->getIsActive()) {
144
            throw new Exception('Failed to commit transaction: transaction was inactive.');
145
        }
146
147 19
        $this->_level--;
148 19
        if ($this->_level === 0) {
149 19
            Yii::trace('Commit transaction', __METHOD__);
150 19
            $this->db->pdo->commit();
151 19
            $this->db->trigger(Connection::EVENT_COMMIT_TRANSACTION);
152 19
            return;
153
        }
154
155
        $schema = $this->db->getSchema();
156
        if ($schema->supportsSavepoint()) {
157
            Yii::trace('Release savepoint ' . $this->_level, __METHOD__);
158
            $schema->releaseSavepoint('LEVEL' . $this->_level);
159
        } else {
160
            Yii::info('Transaction not committed: nested transaction not supported', __METHOD__);
161
        }
162
    }
163
164
    /**
165
     * Rolls back a transaction.
166
     * @throws Exception if the transaction is not active
167
     */
168 15
    public function rollBack()
169
    {
170 15
        if (!$this->getIsActive()) {
171
            // do nothing if transaction is not active: this could be the transaction is committed
172
            // but the event handler to "commitTransaction" throw an exception
173
            return;
174
        }
175
176 15
        $this->_level--;
177 15
        if ($this->_level === 0) {
178 11
            Yii::trace('Roll back transaction', __METHOD__);
179 11
            $this->db->pdo->rollBack();
180 11
            $this->db->trigger(Connection::EVENT_ROLLBACK_TRANSACTION);
181 11
            return;
182
        }
183
184 4
        $schema = $this->db->getSchema();
185 4
        if ($schema->supportsSavepoint()) {
186 4
            Yii::trace('Roll back to savepoint ' . $this->_level, __METHOD__);
187 4
            $schema->rollBackSavepoint('LEVEL' . $this->_level);
188
        } else {
189
            Yii::info('Transaction not rolled back: nested transaction not supported', __METHOD__);
190
            // throw an exception to fail the outer transaction
191
            throw new Exception('Roll back failed: nested transaction not supported.');
192
        }
193 4
    }
194
195
    /**
196
     * Sets the transaction isolation level for this transaction.
197
     *
198
     * This method can be used to set the isolation level while the transaction is already active.
199
     * However this is not supported by all DBMS so you might rather specify the isolation level directly
200
     * when calling [[begin()]].
201
     * @param string $level The transaction isolation level to use for this transaction.
202
     * This can be one of [[READ_UNCOMMITTED]], [[READ_COMMITTED]], [[REPEATABLE_READ]] and [[SERIALIZABLE]] but
203
     * also a string containing DBMS specific syntax to be used after `SET TRANSACTION ISOLATION LEVEL`.
204
     * @throws Exception if the transaction is not active
205
     * @see http://en.wikipedia.org/wiki/Isolation_%28database_systems%29#Isolation_levels
206
     */
207
    public function setIsolationLevel($level)
208
    {
209
        if (!$this->getIsActive()) {
210
            throw new Exception('Failed to set isolation level: transaction was inactive.');
211
        }
212
        Yii::trace('Setting transaction isolation level to ' . $level, __METHOD__);
213
        $this->db->getSchema()->setTransactionIsolationLevel($level);
214
    }
215
216
    /**
217
     * @return int The current nesting level of the transaction.
218
     * @since 2.0.8
219
     */
220 16
    public function getLevel()
221
    {
222 16
        return $this->_level;
223
    }
224
}
225