Skip to content
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

[10.x] Fix "after commit" callbacks not running on nested transactions #48466

Closed
Closed
Show file tree
Hide file tree
Changes from 8 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
12 changes: 12 additions & 0 deletions src/Illuminate/Database/Connection.php
Original file line number Diff line number Diff line change
Expand Up @@ -1545,6 +1545,18 @@ public function unsetTransactionManager()
$this->transactionsManager = null;
}

/**
* Ignores the current transaction level when calling the callbacks.
*
* @return void
*/
public function ignoreLatestTransactionForCallbacks()
{
$this->transactionsManager?->callbacksShouldIgnore(
$this->transactionsManager?->getTransactions()?->last()
tonysm marked this conversation as resolved.
Show resolved Hide resolved
);
}

/**
* Determine if the connection is in a "dry run".
*
Expand Down
11 changes: 6 additions & 5 deletions src/Illuminate/Database/DatabaseTransactionsManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ class DatabaseTransactionsManager
/**
* The database transaction that should be ignored by callbacks.
*
* @var \Illuminate\Database\DatabaseTransactionRecord
* @var \Illuminate\Support\Collection
taylorotwell marked this conversation as resolved.
Show resolved Hide resolved
*/
protected $callbacksShouldIgnore;

Expand All @@ -26,6 +26,7 @@ class DatabaseTransactionsManager
public function __construct()
{
$this->transactions = collect();
$this->callbacksShouldIgnore = collect();
}

/**
Expand Down Expand Up @@ -56,7 +57,7 @@ public function rollback($connection, $level)
)->values();

if ($this->transactions->isEmpty()) {
$this->callbacksShouldIgnore = null;
$this->callbacksShouldIgnore = collect();
}
}

Expand All @@ -77,7 +78,7 @@ public function commit($connection)
$forThisConnection->map->executeCallbacks();

if ($this->transactions->isEmpty()) {
$this->callbacksShouldIgnore = null;
$this->callbacksShouldIgnore = collect();
}
}

Expand All @@ -104,7 +105,7 @@ public function addCallback($callback)
*/
public function callbacksShouldIgnore(DatabaseTransactionRecord $transaction)
crynobone marked this conversation as resolved.
Show resolved Hide resolved
{
$this->callbacksShouldIgnore = $transaction;
$this->callbacksShouldIgnore->push($transaction);

return $this;
}
Expand All @@ -117,7 +118,7 @@ public function callbacksShouldIgnore(DatabaseTransactionRecord $transaction)
public function callbackApplicableTransactions()
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This one too, should I add back the signature? We could probably implement it to return all transactions when not in test mode and, if in test mode, skip the first one.

Copy link
Contributor Author

@tonysm tonysm Sep 22, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've added this method back with an implementation I believe should work the same as the previous one. We're also marking the method as deprecated.

{
return $this->transactions->reject(function ($transaction) {
return $transaction === $this->callbacksShouldIgnore;
return $this->callbacksShouldIgnore->contains($transaction);
})->values();
}

Expand Down
14 changes: 11 additions & 3 deletions src/Illuminate/Database/Eloquent/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -1721,9 +1721,17 @@ public function withCasts($casts)
*/
public function withSavepointIfNeeded(Closure $scope): mixed
{
return $this->getQuery()->getConnection()->transactionLevel() > 0
? $this->getQuery()->getConnection()->transaction($scope)
: $scope();
$connection = $this->getQuery()->getConnection();

if ($connection->transactionLevel() === 0) {
return $scope();
}

return $connection->transaction(function () use ($connection, $scope) {
$connection->ignoreLatestTransactionForCallbacks();

return $scope();
});
}

/**
Expand Down
4 changes: 1 addition & 3 deletions src/Illuminate/Foundation/Testing/RefreshDatabase.php
Original file line number Diff line number Diff line change
Expand Up @@ -98,9 +98,7 @@ public function beginDatabaseTransaction()
$connection->setEventDispatcher($dispatcher);

if ($this->app->resolved('db.transactions')) {
$this->app->make('db.transactions')->callbacksShouldIgnore(
$this->app->make('db.transactions')->getTransactions()->first()
);
$connection->ignoreLatestTransactionForCallbacks();
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
<?php

namespace Illuminate\Tests\Integration\Database;

use Illuminate\Foundation\Auth\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Orchestra\Testbench\Concerns\WithLaravelMigrations;
use Orchestra\Testbench\Factories\UserFactory;

class EloquentTransactionUsingRefreshDatabaseTest extends DatabaseTestCase
{
use RefreshDatabase, WithLaravelMigrations;

protected function setUp(): void
{
$this->afterApplicationCreated(fn () => User::unguard());
$this->beforeApplicationDestroyed(fn () => User::reguard());

parent::setUp();
}

public function testObserverIsCalledOnTestsWithAfterCommit()
{
User::observe($observer = EloquentTransactionUsingRefreshDatabaseUserObserver::resetting());

$user1 = User::create(UserFactory::new()->raw());

$this->assertTrue($user1->exists);
$this->assertEquals(1, $observer::$calledTimes, 'Failed to assert the observer was called once.');
}

public function testObserverCalledWithAfterCommitWhenInsideTransaction()
{
User::observe($observer = EloquentTransactionUsingRefreshDatabaseUserObserver::resetting());

$user1 = DB::transaction(fn () => User::create(UserFactory::new()->raw()));

$this->assertTrue($user1->exists);
$this->assertEquals(1, $observer::$calledTimes, 'Failed to assert the observer was called once.');
}

public function testObserverIsCalledOnTestsWithAfterCommitWhenUsingSavepoint()
{
User::observe($observer = EloquentTransactionUsingRefreshDatabaseUserObserver::resetting());

$user1 = User::createOrFirst(UserFactory::new()->raw());

$this->assertTrue($user1->exists);
$this->assertEquals(1, $observer::$calledTimes, 'Failed to assert the observer was called once.');
}

public function testObserverIsCalledOnTestsWithAfterCommitWhenUsingSavepointAndInsideTransaction()
{
User::observe($observer = EloquentTransactionUsingRefreshDatabaseUserObserver::resetting());

$user1 = DB::transaction(fn () => User::createOrFirst(UserFactory::new()->raw()));

$this->assertTrue($user1->exists);
$this->assertEquals(1, $observer::$calledTimes, 'Failed to assert the observer was called once.');
}
}

class EloquentTransactionUsingRefreshDatabaseUserObserver
{
public static $calledTimes = 0;

public $afterCommit = true;

public static function resetting()
{
static::$calledTimes = 0;

return new static();
}

public function created($user)
{
static::$calledTimes++;
}
}