Transaction.php 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  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. namespace yii\db;
  8. use Yii;
  9. use yii\base\InvalidConfigException;
  10. use yii\base\NotSupportedException;
  11. /**
  12. * Transaction represents a DB transaction.
  13. *
  14. * It is usually created by calling [[Connection::beginTransaction()]].
  15. *
  16. * The following code is a typical example of using transactions (note that some
  17. * DBMS may not support transactions):
  18. *
  19. * ```php
  20. * $transaction = $connection->beginTransaction();
  21. * try {
  22. * $connection->createCommand($sql1)->execute();
  23. * $connection->createCommand($sql2)->execute();
  24. * //.... other SQL executions
  25. * $transaction->commit();
  26. * } catch (\Exception $e) {
  27. * $transaction->rollBack();
  28. * throw $e;
  29. * } catch (\Throwable $e) {
  30. * $transaction->rollBack();
  31. * throw $e;
  32. * }
  33. * ```
  34. *
  35. * > Note: in the above code we have two catch-blocks for compatibility
  36. * > with PHP 5.x and PHP 7.x. `\Exception` implements the [`\Throwable` interface](https://secure.php.net/manual/en/class.throwable.php)
  37. * > since PHP 7.0, so you can skip the part with `\Exception` if your app uses only PHP 7.0 and higher.
  38. *
  39. * @property bool $isActive Whether this transaction is active. Only an active transaction can [[commit()]] or
  40. * [[rollBack()]]. This property is read-only.
  41. * @property string $isolationLevel The transaction isolation level to use for this transaction. This can be
  42. * one of [[READ_UNCOMMITTED]], [[READ_COMMITTED]], [[REPEATABLE_READ]] and [[SERIALIZABLE]] but also a string
  43. * containing DBMS specific syntax to be used after `SET TRANSACTION ISOLATION LEVEL`. This property is
  44. * write-only.
  45. * @property int $level The current nesting level of the transaction. This property is read-only.
  46. *
  47. * @author Qiang Xue <qiang.xue@gmail.com>
  48. * @since 2.0
  49. */
  50. class Transaction extends \yii\base\BaseObject
  51. {
  52. /**
  53. * A constant representing the transaction isolation level `READ UNCOMMITTED`.
  54. * @see http://en.wikipedia.org/wiki/Isolation_%28database_systems%29#Isolation_levels
  55. */
  56. const READ_UNCOMMITTED = 'READ UNCOMMITTED';
  57. /**
  58. * A constant representing the transaction isolation level `READ COMMITTED`.
  59. * @see http://en.wikipedia.org/wiki/Isolation_%28database_systems%29#Isolation_levels
  60. */
  61. const READ_COMMITTED = 'READ COMMITTED';
  62. /**
  63. * A constant representing the transaction isolation level `REPEATABLE READ`.
  64. * @see http://en.wikipedia.org/wiki/Isolation_%28database_systems%29#Isolation_levels
  65. */
  66. const REPEATABLE_READ = 'REPEATABLE READ';
  67. /**
  68. * A constant representing the transaction isolation level `SERIALIZABLE`.
  69. * @see http://en.wikipedia.org/wiki/Isolation_%28database_systems%29#Isolation_levels
  70. */
  71. const SERIALIZABLE = 'SERIALIZABLE';
  72. /**
  73. * @var Connection the database connection that this transaction is associated with.
  74. */
  75. public $db;
  76. /**
  77. * @var int the nesting level of the transaction. 0 means the outermost level.
  78. */
  79. private $_level = 0;
  80. /**
  81. * Returns a value indicating whether this transaction is active.
  82. * @return bool whether this transaction is active. Only an active transaction
  83. * can [[commit()]] or [[rollBack()]].
  84. */
  85. public function getIsActive()
  86. {
  87. return $this->_level > 0 && $this->db && $this->db->isActive;
  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. *
  106. * Starting from version 2.0.16, this method throws exception when beginning nested transaction and underlying DBMS
  107. * does not support savepoints.
  108. * @throws InvalidConfigException if [[db]] is `null`
  109. * @throws NotSupportedException if the DBMS does not support nested transactions
  110. * @throws Exception if DB connection fails
  111. */
  112. public function begin($isolationLevel = null)
  113. {
  114. if ($this->db === null) {
  115. throw new InvalidConfigException('Transaction::db must be set.');
  116. }
  117. $this->db->open();
  118. if ($this->_level === 0) {
  119. if ($isolationLevel !== null) {
  120. $this->db->getSchema()->setTransactionIsolationLevel($isolationLevel);
  121. }
  122. Yii::debug('Begin transaction' . ($isolationLevel ? ' with isolation level ' . $isolationLevel : ''), __METHOD__);
  123. $this->db->trigger(Connection::EVENT_BEGIN_TRANSACTION);
  124. $this->db->pdo->beginTransaction();
  125. $this->_level = 1;
  126. return;
  127. }
  128. $schema = $this->db->getSchema();
  129. if ($schema->supportsSavepoint()) {
  130. Yii::debug('Set savepoint ' . $this->_level, __METHOD__);
  131. $schema->createSavepoint('LEVEL' . $this->_level);
  132. } else {
  133. Yii::info('Transaction not started: nested transaction not supported', __METHOD__);
  134. throw new NotSupportedException('Transaction not started: nested transaction not supported.');
  135. }
  136. $this->_level++;
  137. }
  138. /**
  139. * Commits a transaction.
  140. * @throws Exception if the transaction is not active
  141. */
  142. public function commit()
  143. {
  144. if (!$this->getIsActive()) {
  145. throw new Exception('Failed to commit transaction: transaction was inactive.');
  146. }
  147. $this->_level--;
  148. if ($this->_level === 0) {
  149. Yii::debug('Commit transaction', __METHOD__);
  150. $this->db->pdo->commit();
  151. $this->db->trigger(Connection::EVENT_COMMIT_TRANSACTION);
  152. return;
  153. }
  154. $schema = $this->db->getSchema();
  155. if ($schema->supportsSavepoint()) {
  156. Yii::debug('Release savepoint ' . $this->_level, __METHOD__);
  157. $schema->releaseSavepoint('LEVEL' . $this->_level);
  158. } else {
  159. Yii::info('Transaction not committed: nested transaction not supported', __METHOD__);
  160. }
  161. }
  162. /**
  163. * Rolls back a transaction.
  164. */
  165. public function rollBack()
  166. {
  167. if (!$this->getIsActive()) {
  168. // do nothing if transaction is not active: this could be the transaction is committed
  169. // but the event handler to "commitTransaction" throw an exception
  170. return;
  171. }
  172. $this->_level--;
  173. if ($this->_level === 0) {
  174. Yii::debug('Roll back transaction', __METHOD__);
  175. $this->db->pdo->rollBack();
  176. $this->db->trigger(Connection::EVENT_ROLLBACK_TRANSACTION);
  177. return;
  178. }
  179. $schema = $this->db->getSchema();
  180. if ($schema->supportsSavepoint()) {
  181. Yii::debug('Roll back to savepoint ' . $this->_level, __METHOD__);
  182. $schema->rollBackSavepoint('LEVEL' . $this->_level);
  183. } else {
  184. Yii::info('Transaction not rolled back: nested transaction not supported', __METHOD__);
  185. }
  186. }
  187. /**
  188. * Sets the transaction isolation level for this transaction.
  189. *
  190. * This method can be used to set the isolation level while the transaction is already active.
  191. * However this is not supported by all DBMS so you might rather specify the isolation level directly
  192. * when calling [[begin()]].
  193. * @param string $level The transaction isolation level to use for this transaction.
  194. * This can be one of [[READ_UNCOMMITTED]], [[READ_COMMITTED]], [[REPEATABLE_READ]] and [[SERIALIZABLE]] but
  195. * also a string containing DBMS specific syntax to be used after `SET TRANSACTION ISOLATION LEVEL`.
  196. * @throws Exception if the transaction is not active
  197. * @see http://en.wikipedia.org/wiki/Isolation_%28database_systems%29#Isolation_levels
  198. */
  199. public function setIsolationLevel($level)
  200. {
  201. if (!$this->getIsActive()) {
  202. throw new Exception('Failed to set isolation level: transaction was inactive.');
  203. }
  204. Yii::debug('Setting transaction isolation level to ' . $level, __METHOD__);
  205. $this->db->getSchema()->setTransactionIsolationLevel($level);
  206. }
  207. /**
  208. * @return int The current nesting level of the transaction.
  209. * @since 2.0.8
  210. */
  211. public function getLevel()
  212. {
  213. return $this->_level;
  214. }
  215. }