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 on purge for all mysql versions #407

Open
wants to merge 10 commits into
base: 1.7.x
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 7 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
42 changes: 42 additions & 0 deletions lib/Doctrine/Common/DataFixtures/Purger/ORMPurger.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,18 @@
namespace Doctrine\Common\DataFixtures\Purger;

use Doctrine\Common\DataFixtures\Sorter\TopologicalSorter;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Platforms\AbstractMySQLPlatform;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Platforms\MySQLPlatform;
use Doctrine\DBAL\Schema\Identifier;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Mapping\ClassMetadata;

croensch marked this conversation as resolved.
Show resolved Hide resolved
use function array_reverse;
use function array_search;
use function assert;
use function class_exists;
use function count;
use function is_callable;
use function method_exists;
Expand Down Expand Up @@ -141,6 +145,8 @@ public function purge()
'getSchemaAssetsFilter'
) ? $connection->getConfiguration()->getSchemaAssetsFilter() : null;

$this->disableForeignKeyChecksForMySQL($connection);

foreach ($orderedTables as $tbl) {
// If we have a filter expression, check it and skip if necessary
if (! $emptyFilterExpression && ! preg_match($filterExpr, $tbl)) {
Expand All @@ -163,6 +169,8 @@ public function purge()
$connection->executeStatement($platform->getTruncateTableSQL($tbl, true));
}
}

$this->enableForeignKeyChecksForMySQL($connection);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If anything inside the foreach throws, we leave the connection in a state of disabled foreign key checks, don't we? We should do something about that.

}

/**
Expand Down Expand Up @@ -280,4 +288,38 @@ private function getDeleteFromTableSQL(string $tableName, AbstractPlatform $plat

return 'DELETE FROM ' . $tableIdentifier->getQuotedName($platform);
}

private function disableForeignKeyChecksForMySQL(Connection $connection)
croensch marked this conversation as resolved.
Show resolved Hide resolved
{
if ($this->purgeMode !== self::PURGE_MODE_TRUNCATE || ! $this->isMySQL($connection)) {
return;
}

// see MySQL TRUNCATE TABLE Statement: fails for an InnoDB or NDB table
// if there are any FOREIGN KEY constraints from other tables that
// reference the table.
$connection->executeStatement('SET @DOCTRINE_OLD_FOREIGN_KEY_CHECKS = @@FOREIGN_KEY_CHECKS');
$connection->executeStatement('SET FOREIGN_KEY_CHECKS = 0');
}

private function enableForeignKeyChecksForMySQL(Connection $connection)
croensch marked this conversation as resolved.
Show resolved Hide resolved
{
if ($this->purgeMode !== self::PURGE_MODE_TRUNCATE || ! $this->isMySQL($connection)) {
return;
}

$connection->executeStatement('SET FOREIGN_KEY_CHECKS = @DOCTRINE_OLD_FOREIGN_KEY_CHECKS');
}

private function isMySQL(Connection $connection): bool
{
$platform = $connection->getDatabasePlatform();

if (! class_exists(AbstractMySQLPlatform::class)) {
// before DBAL 3.3
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We don't need to support ancient DBAL versions anymore.

return $platform instanceof MySQLPlatform;
}

return $platform instanceof AbstractMySQLPlatform;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
<?php

declare(strict_types=1);

namespace Doctrine\Tests\Common\DataFixtures;

use Doctrine\Common\DataFixtures\Purger\ORMPurger;
use Doctrine\Common\EventManager;
use Doctrine\DBAL\Configuration;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Driver\Middleware\AbstractDriverMiddleware;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Platforms\MySQLPlatform;
use Doctrine\DBAL\Platforms\SqlitePlatform;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\ORMSetup;
use Doctrine\Persistence\Mapping\Driver\MappingDriver;
use Doctrine\Tests\Common\DataFixtures\TestEntity\Link;

class ORMPurgerForeignKeyCheckTest extends BaseTest
{
public const TEST_CLASS_NAME = Link::class;
public const TEST_TABLE_NAME = 'link';

/** @return MappingDriver */
croensch marked this conversation as resolved.
Show resolved Hide resolved
protected function getMockMetadataDriver()
croensch marked this conversation as resolved.
Show resolved Hide resolved
{
$metadataDriver = $this->createMock(MappingDriver::class);
$metadataDriver->method('getAllClassNames')->willReturn([self::TEST_CLASS_NAME]);
$metadataDriver->method('loadMetadataForClass')
->willReturnCallback(static function (string $className, ClassMetadata $metadata) {
croensch marked this conversation as resolved.
Show resolved Hide resolved
if ($className !== self::TEST_CLASS_NAME) {
return;
}

$metadata->setPrimaryTable(['name' => self::TEST_TABLE_NAME]);
$metadata->setIdentifier(['id']);
});
$metadataDriver->method('isTransient')->willReturn(false);

return $metadataDriver;
}

/** @return Connection */
protected function getMockConnectionForPlatform(AbstractPlatform $platform)
croensch marked this conversation as resolved.
Show resolved Hide resolved
{
$driver = $this->createMock(AbstractDriverMiddleware::class);
$driver->method('getDatabasePlatform')->willReturn($platform);

$connection = $this->createMock(Connection::class);
$connection->method('getDriver')->willReturn($driver);
$connection->method('getConfiguration')->willReturn(new Configuration());
$connection->method('getEventManager')->willReturn(new EventManager());
$connection->method('getDatabasePlatform')->willReturn($platform);

return $connection;
}

/** @dataProvider purgeForDifferentPlatformsProvider */
public function testPurgeForDifferentPlatforms(AbstractPlatform $platform, int $purgeMode, bool $hasForeignKeyCheckString): void
{
$metadataDriver = $this->getMockMetadataDriver();
$connection = $this->getMockConnectionForPlatform($platform);

$config = ORMSetup::createConfiguration(true);
$config->setMetadataDriverImpl($metadataDriver);

$em = EntityManager::create($connection, $config);
$purger = new ORMPurger($em);
$purger->setPurgeMode($purgeMode);

if ($hasForeignKeyCheckString) {
$connection
->expects($this->exactly(4))
->method('executeStatement')
->withConsecutive(
['SET @DOCTRINE_OLD_FOREIGN_KEY_CHECKS = @@FOREIGN_KEY_CHECKS'],
['SET FOREIGN_KEY_CHECKS = 0'],
[$this->stringContains(self::TEST_TABLE_NAME)],
['SET FOREIGN_KEY_CHECKS = @DOCTRINE_OLD_FOREIGN_KEY_CHECKS']
);
} else {
$connection
->expects($this->exactly(1))
->method('executeStatement')
->withConsecutive([$this->stringContains(self::TEST_TABLE_NAME)]);
}

$purger->purge();
}

/** @return list<array{AbstractPlatform, int, bool}> */
croensch marked this conversation as resolved.
Show resolved Hide resolved
public function purgeForDifferentPlatformsProvider()
croensch marked this conversation as resolved.
Show resolved Hide resolved
{
return [
[new MySQLPlatform(), ORMPurger::PURGE_MODE_TRUNCATE, true],
[new MySQLPlatform(), ORMPurger::PURGE_MODE_DELETE, false],
[new SqlitePlatform(), ORMPurger::PURGE_MODE_TRUNCATE, false],
[new SqlitePlatform(), ORMPurger::PURGE_MODE_DELETE, false],
];
}
}