Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

225 lines
8.6KB

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