3 namespace Drupal\Core\Database;
6 * A wrapper class for creating and managing database transactions.
8 * Not all databases or database configurations support transactions. For
9 * example, MySQL MyISAM tables do not. It is also easy to begin a transaction
10 * and then forget to commit it, which can lead to connection errors when
11 * another transaction is started.
13 * This class acts as a wrapper for transactions. To begin a transaction,
14 * simply instantiate it. When the object goes out of scope and is destroyed
15 * it will automatically commit. It also will check to see if the specified
16 * connection supports transactions. If not, it will simply skip any transaction
17 * commands, allowing user-space code to proceed normally. The only difference
18 * is that rollbacks won't actually do anything.
20 * In the vast majority of cases, you should not instantiate this class
21 * directly. Instead, call ->startTransaction(), from the appropriate connection
27 * The connection object for this transaction.
29 * @var \Drupal\Core\Database\Connection
31 protected $connection;
34 * A boolean value to indicate whether this transaction has been rolled back.
38 protected $rolledBack = FALSE;
41 * The name of the transaction.
43 * This is used to label the transaction savepoint. It will be overridden to
44 * 'drupal_transaction' if there is no transaction depth.
48 public function __construct(Connection $connection, $name = NULL) {
49 $this->connection = $connection;
50 // If there is no transaction depth, then no transaction has started. Name
51 // the transaction 'drupal_transaction'.
52 if (!$depth = $connection->transactionDepth()) {
53 $this->name = 'drupal_transaction';
55 // Within transactions, savepoints are used. Each savepoint requires a
56 // name. So if no name is present we need to create one.
58 $this->name = 'savepoint_' . $depth;
63 $this->connection->pushTransaction($this->name);
66 public function __destruct() {
67 // If we rolled back then the transaction would have already been popped.
68 if (!$this->rolledBack) {
69 $this->connection->popTransaction($this->name);
74 * Retrieves the name of the transaction or savepoint.
76 public function name() {
81 * Rolls back the current transaction.
83 * This is just a wrapper method to rollback whatever transaction stack we are
84 * currently in, which is managed by the connection object itself. Note that
85 * logging (preferable with watchdog_exception()) needs to happen after a
86 * transaction has been rolled back or the log messages will be rolled back
89 * @see \Drupal\Core\Database\Connection::rollBack()
90 * @see watchdog_exception()
92 public function rollBack() {
93 $this->rolledBack = TRUE;
94 $this->connection->rollBack($this->name);