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

Cache PDO in RefreshDatabase trait #45144

Closed
wants to merge 1 commit into from
Closed

Conversation

mzur
Copy link
Contributor

@mzur mzur commented Nov 30, 2022

This caches the PDO object in the RefreshDatabase trait for tests.

Originally, I implemented this for my own tests to fix the "too many connections" error which can occur if a database other than in-memory SQLite is used in the tests. But I noticed that this also substantially sped up my tests, too. I have 1152 feature tests and most of these use the database. With the default RefreshDatabase trait, these finish after an average 62 seconds. With the updated trait, the tests finish in an average 41 seconds, which is 65 % of the previous time!

This also may make the change from #22569 obsolete but I left the diconnect there because it had no noticable negative effect on the runtime.

@mzur
Copy link
Contributor Author

mzur commented Nov 30, 2022

Somebody please rerun the failed tests. The error is unrelated to my changes.

@mzur mzur mentioned this pull request Nov 30, 2022
@taylorotwell
Copy link
Member

This feels pretty risky to throw on a patch release. Feel free to add it to your own project if you find it helps.

@mzur
Copy link
Contributor Author

mzur commented Nov 30, 2022

Fair enough! If anyone is interested, this can be done directly in the TestCase class as well:

<?php

use App\Tests\CreatesApplication;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;

class TestCase extends BaseTestCase
{
    use CreatesApplication, RefreshDatabase;

    public static $cachedPdo;

    protected function beforeRefreshingDatabase()
    {
        if (static::$cachedPdo) {
            DB::setPdo(static::$cachedPdo);
        } else {
            static::$cachedPdo = DB::getPdo();
        }
    }
}

@mzur mzur deleted the 9.x-pdo-caching branch November 30, 2022 21:05
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.

2 participants