migrations/Version20230508173513.php line 1

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace DoctrineMigrations;
  4. use Doctrine\DBAL\Schema\Schema;
  5. use Doctrine\Migrations\AbstractMigration;
  6. /**
  7.  * Auto-generated Migration: Please modify to your needs!
  8.  */
  9. final class Version20230508173513 extends AbstractMigration
  10. {
  11.     private const GEOLOCATION_TABLE 'geolocation';
  12.     private const FK_NAME 'FK_9DC0E5B461220EA6';
  13.     public function getDescription(): string
  14.     {
  15.         return 'Delete location when creator is deleted';
  16.     }
  17.     public function up(Schema $schema): void
  18.     {
  19.         if ($this->foreignKeyExists(self::GEOLOCATION_TABLEself::FK_NAME)) {
  20.             $this->addSql("ALTER TABLE `geolocation` DROP FOREIGN KEY `FK_9DC0E5B461220EA6`");
  21.         }
  22.         $this->addSql("
  23.             ALTER TABLE `geolocation`
  24.             ADD CONSTRAINT `FK_9DC0E5B461220EA6` FOREIGN KEY (`creator_id`) REFERENCES `creator` (`id`) ON DELETE CASCADE ON UPDATE RESTRICT
  25.         ");
  26.     }
  27.     public function down(Schema $schema): void
  28.     {
  29.         if ($this->foreignKeyExists(self::GEOLOCATION_TABLEself::FK_NAME)) {
  30.             $this->addSql("ALTER TABLE `geolocation` DROP FOREIGN KEY `FK_9DC0E5B461220EA6`");
  31.         }
  32.         $this->addSql("
  33.             ALTER TABLE `geolocation`
  34.             ADD CONSTRAINT `FK_9DC0E5B461220EA6` FOREIGN KEY (`creator_id`) REFERENCES `creator` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT
  35.         ");
  36.     }
  37.     private function foreignKeyExists(string $tableNamestring $constraintName): bool
  38.     {
  39.         $sql = <<<'SQL'
  40.             SELECT COUNT(*)
  41.             FROM information_schema.TABLE_CONSTRAINTS
  42.             WHERE CONSTRAINT_SCHEMA = DATABASE()
  43.               AND TABLE_NAME = :tableName
  44.               AND CONSTRAINT_NAME = :constraintName
  45.               AND CONSTRAINT_TYPE = 'FOREIGN KEY'
  46.         SQL;
  47.         return (int) $this->connection->fetchOne($sql, [
  48.             'tableName' => $tableName,
  49.             'constraintName' => $constraintName,
  50.         ]) > 0;
  51.     }
  52. }