<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20230508173513 extends AbstractMigration
{
private const GEOLOCATION_TABLE = 'geolocation';
private const FK_NAME = 'FK_9DC0E5B461220EA6';
public function getDescription(): string
{
return 'Delete location when creator is deleted';
}
public function up(Schema $schema): void
{
if ($this->foreignKeyExists(self::GEOLOCATION_TABLE, self::FK_NAME)) {
$this->addSql("ALTER TABLE `geolocation` DROP FOREIGN KEY `FK_9DC0E5B461220EA6`");
}
$this->addSql("
ALTER TABLE `geolocation`
ADD CONSTRAINT `FK_9DC0E5B461220EA6` FOREIGN KEY (`creator_id`) REFERENCES `creator` (`id`) ON DELETE CASCADE ON UPDATE RESTRICT
");
}
public function down(Schema $schema): void
{
if ($this->foreignKeyExists(self::GEOLOCATION_TABLE, self::FK_NAME)) {
$this->addSql("ALTER TABLE `geolocation` DROP FOREIGN KEY `FK_9DC0E5B461220EA6`");
}
$this->addSql("
ALTER TABLE `geolocation`
ADD CONSTRAINT `FK_9DC0E5B461220EA6` FOREIGN KEY (`creator_id`) REFERENCES `creator` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT
");
}
private function foreignKeyExists(string $tableName, string $constraintName): bool
{
$sql = <<<'SQL'
SELECT COUNT(*)
FROM information_schema.TABLE_CONSTRAINTS
WHERE CONSTRAINT_SCHEMA = DATABASE()
AND TABLE_NAME = :tableName
AND CONSTRAINT_NAME = :constraintName
AND CONSTRAINT_TYPE = 'FOREIGN KEY'
SQL;
return (int) $this->connection->fetchOne($sql, [
'tableName' => $tableName,
'constraintName' => $constraintName,
]) > 0;
}
}