Allow explicit COMMIT in Transaction objects

Created on 2 November 2023, about 1 year ago

Problem/Motivation

Right now, a Transaction object in Drupal leads to a COMMIT or a RELEASE SAVEPOINT only when it goes out of scope. In practice, it's an autocommit.

We have code like

    try {
      $transaction = $this->connection->startTransaction();
      foreach ($this->insertValues as $insert_values) {
        $stmt->execute($insert_values, $this->queryOptions);
        ...
      }
    }
    catch (\Exception $e) {
      if (isset($transaction)) {
        // One of the INSERTs failed, rollback the whole batch.
        $transaction->rollBack();
      }
      // Rethrow the exception for the calling code.
      throw $e;
    }

or in other cases something like

    try {
      $transaction = $this->connection->startTransaction();
      foreach ($this->insertValues as $insert_values) {
        $stmt->execute($insert_values, $this->queryOptions);
        ...
      }
      unset($transaction);
    }
    catch (\Exception $e) {
      ....
    }

It works, but I personally find unset($transaction) counterintuitive as to be implying a COMMIT on the db.

I propose here to add the possibility to explicitly commit a Transaction object, as an opt-in vs. current behavior. Directionally, removing current behavior and requesting an explicit commit IMHO should be the final goal, but this is too far fetching now.

With the newly introduced TransactionManager, it may be simpler to achieve this now, and we would get into something like

    try {
      $transaction = $this->connection->startTransaction();
      foreach ($this->insertValues as $insert_values) {
        $stmt->execute($insert_values, $this->queryOptions);
        ...
      }
      $transaction->commit();
    }
    catch (\Exception $e) {
      // One of the INSERTs failed, rollback the whole batch and rethrow the exception for the calling code.
      $transaction->rollBack();
      throw $e;
    }

which is also more readable to me.

Proposed resolution

Remaining tasks

User interface changes

API changes

Data model changes

Release notes snippet

โœจ Feature request
Status

Active

Version

11.0 ๐Ÿ”ฅ

Component
Databaseย  โ†’

Last updated 2 days ago

  • Maintained by
  • ๐Ÿ‡ณ๐Ÿ‡ฑNetherlands @daffie
Created by

๐Ÿ‡ฎ๐Ÿ‡นItaly mondrake ๐Ÿ‡ฎ๐Ÿ‡น

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Merge Requests

Comments & Activities

Production build 0.71.5 2024