app/DoctrineMigrations/Version20251022000000.php line 1

Open in your IDE?
  1. <?php
    
    declare(strict_types=1);
    
    namespace DoctrineMigrations;
    
    use Doctrine\DBAL\Schema\Schema;
    use Doctrine\Migrations\AbstractMigration;
    
    /**
     * データ移行履歴テーブルの作成
     * dtb_data_migrationテーブルを追加
     */
    final class Version20251022000000 extends AbstractMigration
    {
        public function getDescription(): string
        {
            return 'データ移行履歴を記録するdtb_data_migrationテーブルを作成';
        }
    
        public function up(Schema $schema): void
        {
            // dtb_data_migrationテーブルが存在するかチェック
            $schemaManager = $this->connection->createSchemaManager();
            $tables = $schemaManager->listTableNames();
            
            if (!in_array('dtb_data_migration', $tables)) {
                $this->addSql('
                    CREATE TABLE dtb_data_migration (
                        id INT UNSIGNED AUTO_INCREMENT NOT NULL,
                        update_type SMALLINT UNSIGNED NOT NULL,
                        update_date DATETIME NOT NULL,
                        discriminator_type VARCHAR(255) DEFAULT NULL,
                        PRIMARY KEY(id)
                    ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci ENGINE = InnoDB
                ');
            } else {
                // テーブルが存在する場合、discriminator_typeカラムを追加
                $columns = $schemaManager->listTableColumns('dtb_data_migration');
                $hasDiscriminator = false;
                foreach ($columns as $column) {
                    if ($column->getName() === 'discriminator_type') {
                        $hasDiscriminator = true;
                        break;
                    }
                }
                if (!$hasDiscriminator) {
                    $this->addSql('ALTER TABLE dtb_data_migration ADD discriminator_type VARCHAR(255) DEFAULT NULL');
                }
            }
        }
    
        public function down(Schema $schema): void
        {
            // rollback処理 - テーブルが存在する場合のみ削除
            $schemaManager = $this->connection->createSchemaManager();
            $tables = $schemaManager->listTableNames();
            
            if (in_array('dtb_data_migration', $tables)) {
                $this->addSql('DROP TABLE dtb_data_migration');
            }
        }
    }