[referenced table, ON DELETE action]. * * parent_id is gone since 0.13.0 (the parent/child tree was replaced by the dependency graph), * so only plan_id is repaired here. */ private const FOREIGN_KEYS = [ 'plan_id' => [Initiative::TABLE_NAME, 'CASCADE'], ]; protected function isApplicable(Schema $schema): bool { // Historical migration: its changes were applied on every install that ran // it before 0.16.0 (this plugin renamed Plan→Program/Initiative in 0.16.0), and // a fresh install creates the current tables from the entity mapping. Never // applicable anymore. return false; } protected function up(): void { $schema = $this->entityManager->getConnection()->createSchemaManager()->introspectSchema(); $tasks = $this->concatPrefix(Task::TABLE_NAME); $missingFk = self::FOREIGN_KEYS; if (!$schema->hasTable($tasks)) { $this->addSql($this->getCreateTableSql()); } else { $missingFk = $this->getMissingForeignKeys($schema->getTable($tasks)); } foreach ($missingFk as $column => [$referenceTable, $onDelete]) { $this->addSql($this->generateAlterTableForeignKeyStatement( Task::TABLE_NAME, [$column], $referenceTable, ['id'], 'ON DELETE '.$onDelete )); } } private function getCreateTableSql(): string { $schemaTool = new SchemaTool($this->entityManager); $prefix = 'CREATE TABLE '.$this->concatPrefix(Task::TABLE_NAME).' '; foreach ($schemaTool->getCreateSchemaSql([$this->entityManager->getClassMetadata(Task::class)]) as $sql) { if (str_starts_with($sql, $prefix)) { return $sql; } } throw new \RuntimeException('SchemaTool returned no CREATE TABLE statement for '.Task::TABLE_NAME.'.'); } /** * @return array */ private function getMissingForeignKeys(Table $table): array { $missing = self::FOREIGN_KEYS; foreach ($table->getForeignKeys() as $foreignKey) { foreach ($foreignKey->getLocalColumns() as $column) { unset($missing[$column]); } } return $missing; } }