Transaction.php 8.9 KB

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