Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

PHPLIB-373 Use DatabaseTransactionsManager in ManagesTransactions trait #3443

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

Open
paulinevos wants to merge 1 commit into mongodb:5.5
base: 5.5
Choose a base branch
Loading
from paulinevos:373_after-commit
Open
Show file tree
Hide file tree
Changes from all commits
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
73 changes: 70 additions & 3 deletions src/Concerns/ManagesTransactions.php
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
use MongoDB\Driver\Session;
use Throwable;

use function max;
use function MongoDB\with_transaction;

/**
Expand Down Expand Up @@ -55,32 +56,90 @@ private function getSessionOrThrow(): Session
*/
public function beginTransaction(array $options = []): void
{
$this->runCallbacksBeforeTransaction();

$this->getSessionOrCreate()->startTransaction($options);

$this->handleInitialTransactionState();
}

private function handleInitialTransactionState(): void
{
$this->transactions = 1;

$this->transactionsManager?->begin(
$this->getName(),
$this->transactions,
);

$this->fireConnectionEvent('beganTransaction');
}

/**
* Commit transaction in this session.
*/
public function commit(): void
{
$this->fireConnectionEvent('committing');
$this->getSessionOrThrow()->commitTransaction();
$this->transactions = 0;

$this->handleCommitState();
}

private function handleCommitState(): void
{
[$levelBeingCommitted, $this->transactions] = [
$this->transactions,
max(0, $this->transactions - 1),
];

$this->transactionsManager?->commit(
$this->getName(),
$levelBeingCommitted,
$this->transactions,
);

$this->fireConnectionEvent('committed');
}

/**
* Abort transaction in this session.
*/
public function rollBack($toLevel = null): void
{
$this->getSessionOrThrow()->abortTransaction();
$session = $this->getSessionOrThrow();
if ($session->isInTransaction()) {
$session->abortTransaction();
}

$this->handleRollbackState();
}

private function handleRollbackState(): void
{
$this->transactions = 0;

$this->transactionsManager?->rollback(
$this->getName(),
$this->transactions,
);

$this->fireConnectionEvent('rollingBack');
}

private function runCallbacksBeforeTransaction(): void
{
foreach ($this->beforeStartingTransaction as $beforeTransactionCallback) {
$beforeTransactionCallback($this);
}
}

/**
* Static transaction function realize the with_transaction functionality provided by MongoDB.
*
* @param int $attempts
* @param int $attempts
*
* @throws Throwable
*/
public function transaction(Closure $callback, $attempts = 1, array $options = []): mixed
{
Expand All @@ -93,15 +152,20 @@ public function transaction(Closure $callback, $attempts = 1, array $options = [

if ($attemptsLeft < 0) {
$session->abortTransaction();
$this->handleRollbackState();

return;
}

$this->runCallbacksBeforeTransaction();
$this->handleInitialTransactionState();

// 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);
$this->fireConnectionEvent('committing');
} catch (Throwable $throwable) {
throw $throwable;
}
Expand All @@ -110,9 +174,12 @@ public function transaction(Closure $callback, $attempts = 1, array $options = [
with_transaction($this->getSessionOrCreate(), $callbackFunction, $options);

if ($attemptsLeft < 0 && $throwable) {
$this->handleRollbackState();
throw $throwable;
}

$this->handleCommitState();

return $callbackResult;
}
}
221 changes: 221 additions & 0 deletions tests/Ticket/GH3328Test.php
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,221 @@
<?php

namespace MongoDB\Laravel\Tests\Ticket;

use Closure;
use Exception;
use Illuminate\Contracts\Database\ConcurrencyErrorDetector;
use Illuminate\Contracts\Events\ShouldDispatchAfterCommit;
use Illuminate\Database\Connection;
use Illuminate\Database\Events\TransactionBeginning;
use Illuminate\Database\Events\TransactionCommitted;
use Illuminate\Database\Events\TransactionCommitting;
use Illuminate\Database\Events\TransactionRolledBack;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Event;
use MongoDB\Driver\Exception\RuntimeException;
use MongoDB\Laravel\Tests\TestCase;
use Throwable;

use function event;

/**
* @see https://github.com/mongodb/laravel-mongodb/issues/3328
* @see https://jira.mongodb.org/browse/PHPORM-373
*/
class GH3328Test extends TestCase
{
public function testAfterCommitOnSuccessfulTransaction(): void
{
$callback = static function (): void {
event(new RegularEvent());
event(new AfterCommitEvent());
};

$assert = function (): void {
Event::assertDispatchedTimes(BeforeTransactionEvent::class);
Event::assertDispatchedTimes(RegularEvent::class);
Event::assertDispatchedTimes(AfterCommitEvent::class);

Event::assertDispatched(TransactionBeginning::class);
Event::assertDispatched(TransactionCommitting::class);
Event::assertDispatched(TransactionCommitted::class);
};

$this->assertTransactionCallbackResult($callback, $assert);
}

public function testAfterCommitOnFailedTransaction(): void
{
$this->app->bind(ConcurrencyErrorDetector::class, FakeConcurrencyErrorDetector::class);

$callback = static function (): void {
event(new RegularEvent());
event(new AfterCommitEvent());

// Transaction failed; after commit event should not be dispatched
throw new FakeException();
};

$assert = function (): void {
Event::assertDispatchedTimes(BeforeTransactionEvent::class, 3);
Event::assertDispatchedTimes(RegularEvent::class, 3);

Event::assertDispatchedTimes(TransactionBeginning::class, 3);
Event::assertDispatched(TransactionRolledBack::class);
Event::assertNotDispatched(TransactionCommitting::class);
Event::assertNotDispatched(TransactionCommitted::class);
};

$this->assertTransactionCallbackResult($callback, $assert, 3);
}

public function testAfterCommitOnSuccessfulManualTransaction(): void
{
$callback = function (): void {
event(new RegularEvent());
event(new AfterCommitEvent());
};

$assert = function (): void {
Event::assertDispatchedTimes(BeforeTransactionEvent::class);
Event::assertDispatchedTimes(RegularEvent::class);
Event::assertDispatchedTimes(AfterCommitEvent::class);

Event::assertDispatched(TransactionBeginning::class);
Event::assertNotDispatched(TransactionRolledBack::class);
Event::assertDispatched(TransactionCommitting::class);
Event::assertDispatched(TransactionCommitted::class);
};

$this->assertTransactionResult($callback, $assert);
}

public function testAfterCommitOnFailedManualTransaction(): void
{
$callback = function (): void {
event(new RegularEvent());
event(new AfterCommitEvent());

throw new FakeException();
};

$assert = function (): void {
Event::assertDispatchedTimes(BeforeTransactionEvent::class);
Event::assertDispatchedTimes(RegularEvent::class);
Event::assertNotDispatched(AfterCommitEvent::class);

Event::assertDispatched(TransactionBeginning::class);
Event::assertDispatched(TransactionRolledBack::class);
Event::assertNotDispatched(TransactionCommitting::class);
Event::assertNotDispatched(TransactionCommitted::class);
};

$this->assertTransactionResult($callback, $assert);
}

private function assertTransactionCallbackResult(Closure $callback, Closure $assert, ?int $attempts = 1): void
{
$this->assertCallbackResultForConnection(
DB::connection('sqlite'),
$callback,
$assert,
$attempts,
);

$this->assertCallbackResultForConnection(
DB::connection('mongodb'),
$callback,
$assert,
$attempts,
);
}

/**
* Ensure equal transaction behavior between SQLite (handled by Laravel) and MongoDB
*/
private function assertCallbackResultForConnection(Connection $connection, Closure $callback, Closure $assertions, int $attempts): void
{
$fake = Event::fake();
$connection->setEventDispatcher($fake);
$connection->beforeStartingTransaction(function () {
event(new BeforeTransactionEvent());
});

try {
$connection->transaction($callback, $attempts);
} catch (Exception) {
}

$assertions();
}

private function assertTransactionResult(Closure $callback, Closure $assert): void
{
$this->assertManualResultForConnection(
DB::connection('sqlite'),
$callback,
$assert,
);

$this->assertManualResultForConnection(
DB::connection('mongodb'),
$callback,
$assert,
);
}

/**
* Ensure equal transaction behavior between SQLite (handled by Laravel) and MongoDB
*/
private function assertManualResultForConnection(Connection $connection, Closure $callback, Closure $assert): void
{
$fake = Event::fake();
$connection->setEventDispatcher($fake);

$connection->beforeStartingTransaction(function () {
event(new BeforeTransactionEvent());
});

$connection->beginTransaction();

try {
$callback();
$connection->commit();
} catch (Exception) {
$connection->rollBack();
}

$assert();
}
}

class AfterCommitEvent implements ShouldDispatchAfterCommit
{
use Dispatchable;
}

class BeforeTransactionEvent
{
use Dispatchable;
}
class RegularEvent
{
use Dispatchable;
}
class FakeException extends RuntimeException

Check failure on line 207 in tests/Ticket/GH3328Test.php

View workflow job for this annotation

GitHub Actions / phpcs

Superfluous suffix "Exception".
{
public function __construct()
{
$this->errorLabels = ['TransientTransactionError'];
}
}

class FakeConcurrencyErrorDetector implements ConcurrencyErrorDetector
{
public function causedByConcurrencyError(Throwable $e): bool
{
return true;
}
}
Loading

AltStyle によって変換されたページ (->オリジナル) /