4

I'm trying to truncate a table, but everytime I try to run it through a test I get a PDOException: There is no active transaction

I'm using the RefreshDatabase trait.

My code looks like this:

Model::query()->truncate();
Ezrab_
  • 825
  • 5
  • 19
  • 44

2 Answers2

11

the error is caused by the truncate action

based on the answer on https://stackoverflow.com/a/1522974/6644975

when you execute a truncate statement the transaction is committed and then the TRUNCATE is executed and cannot be undone.

This affects the RefreshDatabase trait which uses a transaction for each and every test.

here's how it runs

  1. RefreshDatabase creates a transactions
  2. You do something here with the database
  3. you execute truncate
  4. Truncate commits the transaction
  5. RefreshDatabase tries to commit a transaction but will not be able to because it's already committed causing an error There is no active transaction
Sean Reyes
  • 1,636
  • 11
  • 19
  • Thank you for this answer, this makes sense. So how would one implement replacing all records in a database if truncate is not a good testing solution. – Ezrab_ Apr 01 '21 at 08:11
  • 1
    @Ezrab_ Are you using truncate to reset Incrementing ID? if NOT you can just use `DB::table('table_name')->delete();` which deletes all records in the database. – Sean Reyes Apr 05 '21 at 05:19
  • How we can prevent that? I need to reset autoincrement also – keizah7 Feb 22 '22 at 08:51
4

Try to use the trait DatabaseMigrations instead of RefreshDatabase

digout
  • 4,041
  • 1
  • 31
  • 38