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] Adds seeding within transaction #49612

Closed
wants to merge 2 commits into from
Closed

[10.x] Adds seeding within transaction #49612

wants to merge 2 commits into from

Conversation

DarkGhostHunter
Copy link
Contributor

@DarkGhostHunter DarkGhostHunter commented Jan 8, 2024

What?

This PR adds the ability to declare a seeder run inside a database transaction by using the WithDatabaseTransaction trait. The aim is to avoid incomplete or orphaned records when the seeder fails during development, forcing the developer to truncate the tables affected manually.

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Database\Console\Seeds\WithDatabaseTransaction;
use App\Models\Post;
use App\Models\Comment;

class CommentSeeder extends Seeder
{
    use WithDatabaseTransaction;

    public function run()
    {
        return Comment::factory(1000000)
                      ->sequence(fn() => ['post_id' => Post::inRandomOrder()->value('id')])
                      ->create();
    }
}

While this can be done manually using DB::transaction, the trait allows the developer to programmatically wrap it. For example, the developer can disable them for SQLite :memory: database, or for others RDMS on large lists of seeded records.

public function useDatabaseTransaction()
{
    $connection = Post::query()->getConnection();

    // Only run transactions when SQLite uses a file database for better performance.
    return $connection->getDriverName() === 'sqlite'
        && $connection->getConfig('database') !== ':memory:';
}

@taylorotwell
Copy link
Member

Would rather just let developers have full control using DB::transaction.

@DarkGhostHunter DarkGhostHunter deleted the feat/seed-transaction branch January 20, 2024 20:19
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