Skip to content

Transaction support #2465

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 14 commits into from
Nov 27, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 15 additions & 2 deletions src/Concerns/ManagesTransactions.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use MongoDB\Driver\Exception\RuntimeException;
use MongoDB\Driver\Session;
use function MongoDB\with_transaction;
use Throwable;

/**
* @see https://docs.mongodb.com/manual/core/transactions/
Expand Down Expand Up @@ -83,8 +84,9 @@ public function transaction(Closure $callback, $attempts = 1, array $options = [
{
$attemptsLeft = $attempts;
$callbackResult = null;
$throwable = null;

$callbackFunction = function (Session $session) use ($callback, &$attemptsLeft, &$callbackResult) {
$callbackFunction = function (Session $session) use ($callback, &$attemptsLeft, &$callbackResult, &$throwable) {
$attemptsLeft--;

if ($attemptsLeft < 0) {
Expand All @@ -93,11 +95,22 @@ public function transaction(Closure $callback, $attempts = 1, array $options = [
return;
}

$callbackResult = $callback($this);
// Catch, store and re-throw any exception thrown during execution
// of the callable. The last exception is re-thrown if the transaction
// was aborted because the number of callback attempts has been exceeded.
try {
$callbackResult = $callback($this);
} catch (Throwable $throwable) {
throw $throwable;
}
};

with_transaction($this->getSessionOrCreate(), $callbackFunction, $options);

if ($attemptsLeft < 0 && $throwable) {
throw $throwable;
}

return $callbackResult;
}
}
38 changes: 28 additions & 10 deletions tests/TransactionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
use Jenssegers\Mongodb\Connection;
use Jenssegers\Mongodb\Eloquent\Model;
use MongoDB\BSON\ObjectId;
use MongoDB\Driver\Exception\BulkWriteException;
use MongoDB\Driver\Server;

class TransactionTest extends TestCase
Expand Down Expand Up @@ -317,6 +318,8 @@ public function testTransaction(): void
{
User::create(['name' => 'klinson', 'age' => 20, 'title' => 'admin']);

// The $connection parameter may be unused, but is implicitly used to
// test that the closure is executed with the connection as an argument.
DB::transaction(function (Connection $connection): void {
User::create(['name' => 'alcaeus', 'age' => 38, 'title' => 'admin']);
User::where(['name' => 'klinson'])->update(['age' => 21]);
Expand All @@ -336,14 +339,18 @@ public function testTransactionRepeatsOnTransientFailure(): void
$timesRun = 0;

DB::transaction(function () use (&$timesRun): void {
User::where(['name' => 'klinson'])->update(['age' => 21]);
$timesRun++;

// Run a query to start the transaction on the server
User::create(['name' => 'alcaeus', 'age' => 38, 'title' => 'admin']);

// Update user during transaction to simulate a simultaneous update
if ($timesRun == 0) {
// Update user outside of the session
if ($timesRun == 1) {
DB::getCollection('users')->updateOne(['name' => 'klinson'], ['$set' => ['age' => 22]]);
}

$timesRun++;
// This update will create a write conflict, aborting the transaction
User::where(['name' => 'klinson'])->update(['age' => 21]);
}, 2);

$this->assertSame(2, $timesRun);
Expand All @@ -356,14 +363,25 @@ public function testTransactionRespectsRepetitionLimit(): void

$timesRun = 0;

DB::transaction(function () use (&$timesRun): void {
User::where(['name' => 'klinson'])->update(['age' => 21]);
try {
DB::transaction(function () use (&$timesRun): void {
$timesRun++;

// Update user during transaction to simulate a simultaneous update
DB::getCollection('users')->updateOne(['name' => 'klinson'], ['$inc' => ['age' => 2]]);
// Run a query to start the transaction on the server
User::create(['name' => 'alcaeus', 'age' => 38, 'title' => 'admin']);

$timesRun++;
}, 2);
// Update user outside of the session
DB::getCollection('users')->updateOne(['name' => 'klinson'], ['$inc' => ['age' => 2]]);

// This update will create a write conflict, aborting the transaction
User::where(['name' => 'klinson'])->update(['age' => 21]);
}, 2);

$this->fail('Expected exception during transaction');
} catch (BulkWriteException $e) {
$this->assertInstanceOf(BulkWriteException::class, $e);
$this->assertStringContainsString('WriteConflict', $e->getMessage());
}

$this->assertSame(2, $timesRun);

Expand Down