app/DoctrineMigrations/Version20251022000000.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.  * データ移行履歴テーブルの作成
  8.  * dtb_data_migrationテーブルを追加
  9.  */
  10. final class Version20251022000000 extends AbstractMigration
  11. {
  12.     public function getDescription(): string
  13.     {
  14.         return 'データ移行履歴を記録するdtb_data_migrationテーブルを作成';
  15.     }
  16.     public function up(Schema $schema): void
  17.     {
  18.         // dtb_data_migrationテーブルが存在するかチェック
  19.         $schemaManager $this->connection->createSchemaManager();
  20.         $tables $schemaManager->listTableNames();
  21.         
  22.         if (!in_array('dtb_data_migration'$tables)) {
  23.             $this->addSql('
  24.                 CREATE TABLE dtb_data_migration (
  25.                     id INT UNSIGNED AUTO_INCREMENT NOT NULL,
  26.                     update_type SMALLINT UNSIGNED NOT NULL,
  27.                     update_date DATETIME NOT NULL,
  28.                     discriminator_type VARCHAR(255) DEFAULT NULL,
  29.                     PRIMARY KEY(id)
  30.                 ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci ENGINE = InnoDB
  31.             ');
  32.         } else {
  33.             // テーブルが存在する場合、discriminator_typeカラムを追加
  34.             $columns $schemaManager->listTableColumns('dtb_data_migration');
  35.             $hasDiscriminator false;
  36.             foreach ($columns as $column) {
  37.                 if ($column->getName() === 'discriminator_type') {
  38.                     $hasDiscriminator true;
  39.                     break;
  40.                 }
  41.             }
  42.             if (!$hasDiscriminator) {
  43.                 $this->addSql('ALTER TABLE dtb_data_migration ADD discriminator_type VARCHAR(255) DEFAULT NULL');
  44.             }
  45.         }
  46.     }
  47.     public function down(Schema $schema): void
  48.     {
  49.         // rollback処理 - テーブルが存在する場合のみ削除
  50.         $schemaManager $this->connection->createSchemaManager();
  51.         $tables $schemaManager->listTableNames();
  52.         
  53.         if (in_array('dtb_data_migration'$tables)) {
  54.             $this->addSql('DROP TABLE dtb_data_migration');
  55.         }
  56.     }
  57. }