Skip to content

Commit 20d6b4b

Browse files
AJenbotaylorotwell
andauthored
[11.x] Improved Performance for Testing with In-Memory Databases (#47912)
* Transactional RefreshDatabase for in memory databases This provides a significant performance increase for running tests when using an in memory database. * formatting --------- Co-authored-by: Taylor Otwell <[email protected]>
1 parent 8813dcd commit 20d6b4b

File tree

2 files changed

+25
-20
lines changed

2 files changed

+25
-20
lines changed

src/Illuminate/Foundation/Testing/RefreshDatabase.php

Lines changed: 18 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,11 @@ public function refreshDatabase()
1818
{
1919
$this->beforeRefreshingDatabase();
2020

21-
$this->usingInMemoryDatabase()
22-
? $this->refreshInMemoryDatabase()
23-
: $this->refreshTestDatabase();
21+
if ($this->usingInMemoryDatabase()) {
22+
$this->restoreInMemoryDatabase();
23+
}
24+
25+
$this->refreshTestDatabase();
2426

2527
$this->afterRefreshingDatabase();
2628
}
@@ -38,28 +40,19 @@ protected function usingInMemoryDatabase()
3840
}
3941

4042
/**
41-
* Refresh the in-memory database.
43+
* Restore the in-memory database between tests.
4244
*
4345
* @return void
4446
*/
45-
protected function refreshInMemoryDatabase()
47+
protected function restoreInMemoryDatabase()
4648
{
47-
$this->artisan('migrate', $this->migrateUsing());
48-
49-
$this->app[Kernel::class]->setArtisan(null);
50-
}
49+
$database = $this->app->make('db');
5150

52-
/**
53-
* The parameters that should be used when running "migrate".
54-
*
55-
* @return array
56-
*/
57-
protected function migrateUsing()
58-
{
59-
return [
60-
'--seed' => $this->shouldSeed(),
61-
'--seeder' => $this->seeder(),
62-
];
51+
foreach ($this->connectionsToTransact() as $name) {
52+
if (isset(RefreshDatabaseState::$inMemoryConnections[$name])) {
53+
$database->connection($name)->setPdo(RefreshDatabaseState::$inMemoryConnections[$name]);
54+
}
55+
}
6356
}
6457

6558
/**
@@ -91,6 +84,11 @@ public function beginDatabaseTransaction()
9184

9285
foreach ($this->connectionsToTransact() as $name) {
9386
$connection = $database->connection($name);
87+
88+
if ($this->usingInMemoryDatabase()) {
89+
RefreshDatabaseState::$inMemoryConnections[$name] ??= $connection->getPdo();
90+
}
91+
9492
$dispatcher = $connection->getEventDispatcher();
9593

9694
$connection->unsetEventDispatcher();

src/Illuminate/Foundation/Testing/RefreshDatabaseState.php

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,13 @@
44

55
class RefreshDatabaseState
66
{
7+
/**
8+
* The current SQLite in-memory database connections.
9+
*
10+
* @var array<string, \PDO>
11+
*/
12+
public static $inMemoryConnections = [];
13+
714
/**
815
* Indicates if the test database has been migrated.
916
*

0 commit comments

Comments
 (0)