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

Disable foreign key checks with truncating with MySQL #73

Merged
merged 1 commit into from
Nov 25, 2017
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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