Skip to content

Commit

Permalink
Disable foreign key checks with truncating with MySQL (#73)
Browse files Browse the repository at this point in the history
Closes #63.
  • Loading branch information
theofidry authored Nov 25, 2017
1 parent eb7ea93 commit a4d611f
Showing 1 changed file with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions src/Bridge/Doctrine/Purger/Purger.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
use Doctrine\Common\DataFixtures\Purger\PHPCRPurger as DoctrinePhpCrPurger;
use Doctrine\Common\DataFixtures\Purger\PurgerInterface as DoctrinePurgerInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\DBAL\Driver\AbstractMySQLDriver;
use Doctrine\ODM\MongoDB\DocumentManager as DoctrineMongoDocumentManager;
use Doctrine\ODM\PHPCR\DocumentManager as DoctrinePhpCrDocumentManager;
use Doctrine\ORM\EntityManagerInterface;
Expand All @@ -38,11 +39,13 @@
use IsAServiceTrait;

private $manager;
private $purgeMode;
private $purger;

public function __construct(ObjectManager $manager, PurgeMode $purgeMode = null)
{
$this->manager = $manager;
$this->purgeMode = $purgeMode;

$this->purger = static::createPurger($manager, $purgeMode);
}
Expand Down Expand Up @@ -88,7 +91,27 @@ public function create(PurgeMode $mode, PurgerInterface $purger = null): PurgerI
*/
public function purge()
{
// Because MySQL rocks, you got to disable foreign key checks when doing a TRUNCATE unlike in for example
// PostgreSQL. This ideally should be done in the Purger of doctrine/data-fixtures but meanwhile we are doing
// it here.
// See the progress in https://github.com/doctrine/data-fixtures/pull/272
$truncateOrm = (
$this->purger instanceof DoctrineOrmPurger
&& PurgeMode::createTruncateMode()->getValue() === $this->purgeMode->getValue()
&& $this->purger->getObjectManager()->getConnection()->getDriver() instanceof AbstractMySQLDriver
);

if ($truncateOrm) {
$connection = $this->purger->getObjectManager()->getConnection();

$connection->exec('SET FOREIGN_KEY_CHECKS = 0;');
}

$this->purger->purge();

if ($truncateOrm && isset($connection)) {
$connection->exec('SET FOREIGN_KEY_CHECKS = 1;');
}
}

private static function createPurger(ObjectManager $manager, ?PurgeMode $purgeMode): DoctrinePurgerInterface
Expand Down

0 comments on commit a4d611f

Please sign in to comment.