Skip to content

Instantly share code, notes, and snippets.

@morontt
Created March 21, 2014 17:14
Show Gist options
  • Save morontt/9691036 to your computer and use it in GitHub Desktop.
Save morontt/9691036 to your computer and use it in GitHub Desktop.
Enable/Disable foreign_key_checks for MySQL in doctrine migrations
<?php
/**
* Created by PhpStorm.
* User: morontt
* Date: 21.03.14
* Time: 19:08
*/
namespace Application\Migrations;
use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Platforms\MySqlPlatform;
use Doctrine\DBAL\Schema\Schema;
/**
* Auto-generated Migration
*/
class Version20140321190821 extends AbstractMigration
{
/**
* @param Schema $schema
*/
public function preUp(Schema $schema)
{
parent::preUp($schema);
$this->setForeignKeyChecks(false);
}
/**
* @param Schema $schema
*/
public function postUp(Schema $schema)
{
parent::postUp($schema);
$this->setForeignKeyChecks(true);
}
/**
* @param Schema $schema
*/
public function preDown(Schema $schema)
{
parent::preDown($schema);
$this->setForeignKeyChecks(false);
}
/**
* @param Schema $schema
*/
public function postDown(Schema $schema)
{
parent::postDown($schema);
$this->setForeignKeyChecks(true);
}
public function up(Schema $schema)
{
$this->abortIf(
$this->connection->getDatabasePlatform()->getName() != "mysql",
"Migration can only be executed safely on 'mysql'."
);
$this->addSql("ALTER TABLE super_puper DROP hyper_id");
}
public function down(Schema $schema)
{
$this->abortIf(
$this->connection->getDatabasePlatform()->getName() != "mysql",
"Migration can only be executed safely on 'mysql'."
);
$this->addSql("ALTER TABLE super_puper ADD hyper_id INT UNSIGNED NOT NULL");
}
/**
* @param boolean $enabled
*/
protected function setForeignKeyChecks($enabled)
{
$connection = $this->connection;
$platform = $connection->getDatabasePlatform();
if ($platform instanceof MySqlPlatform) {
$connection->exec(sprintf('SET foreign_key_checks = %s;', (int)$enabled));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment