Skip to content

Add transaction() methods to MysqlClient#216

Open
jdickinsondev91-stack wants to merge 2 commits intofriends-of-reactphp:0.7.xfrom
jdickinsondev91-stack:feature/transaction-method
Open

Add transaction() methods to MysqlClient#216
jdickinsondev91-stack wants to merge 2 commits intofriends-of-reactphp:0.7.xfrom
jdickinsondev91-stack:feature/transaction-method

Conversation

@jdickinsondev91-stack
Copy link
Copy Markdown

@jdickinsondev91-stack jdickinsondev91-stack commented Apr 5, 2026

Add transaction() convenience method to MysqlClient

Currently, every application that needs atomic operations must manually issue START TRANSACTION, COMMIT, and ROLLBACK as raw queries and handle the rollback logic in a try/catch:

$mysql->query('START TRANSACTION');
try {
$mysql->query('INSERT INTO user (name) VALUES (?)', ['Alice']);
$mysql->query('INSERT INTO user (name) VALUES (?)', ['Bob']);
$mysql->query('COMMIT');
} catch (\Throwable $e) {
$mysql->query('ROLLBACK');
throw $e;
}

This PR adds a transaction() method that handles this automatically:

$mysql->transaction(function (React\Mysql\MysqlClient $mysql) {
$mysql->query('INSERT INTO user (name) VALUES (?)', ['Alice']);
$mysql->query('INSERT INTO user (name) VALUES (?)', ['Bob']);
});

The method:

  • Starts a transaction before executing the callback
  • Commits on success, rolls back on failure
  • Handles both synchronous exceptions (fibers/await) and asynchronous promise rejections
  • Returns a PromiseInterface consistent with the existing query() and ping() API

This pattern is standard in other database libraries (DB::transaction() in Laravel, transactional() in Doctrine, BEGIN/COMMIT wrappers in node-postgres and Go's database/sql).

Changes:

  • src/MysqlClient.php — added transaction() method
  • tests/MysqlClientTest.php — 5 unit tests
  • README.md — usage documentation and table of contents
  • CHANGELOG.md — unreleased entry

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant