Transaction.php 9.9 KB

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