Saturday, 3 March 2012

Symfony 2 Doctrine Fixtures TRUNCATE (rather than DELETE) hack

Symfony2 fixtures clears database tables prior to populating them with fixture data. In the (earlier) version of doctrine-fixtures we tried, tables would refuse to be cleared if there were foreign keys, or indexes would not reset due to using SQL DELETE versus TRUNCATE.

This behavior might be fixed by now, but just in case you have an older version, here's a quick hack around this problem.

Warning: don't do this hack if you're not sure what you're doing! These instructions aren't comprehensive. They're only complete enough for someone to figure out why the changes should work.

1) locate your ORM Purger
it should be in:

2) make the purge() function truncate
There should be some loop in purge() that looks like:
foreach($orderedTables as $tbl) {
            ... (old code for deleting tables) ...

update this to be something like the following, commenting out old code so you can undo if you messed up:
foreach($orderedTables as $tbl) {
  // stupid hack
  $this->em->getConnection()->executeUpdate("SET foreign_key_checks = 0;");
  $this->em->getConnection()->executeUpdate($platform->getTruncateTableSQL($tbl, true));
  $this->em->getConnection()->executeUpdate("SET foreign_key_checks = 1;");

The disabling of the foreign key checks is done so the tables can be truncated, otherwise SQL will not allow the truncate operation if your database have foreign key constraints set.

3) how to undo
Un-comment the old code if you commented it out, or reinstall doctrine-fixtures.

4) final thoughts
This isn't the best way around this doctrine-fixtures behavior, and it's only meant as a hack for the impatient.

No comments:

Post a Comment