abortIf( $this->connection->getDatabasePlatform()->getName() != 'postgresql', 'Migration can only be executed safely on \'postgresql\'.' ); // retrieve center for setting a default center $centers = $this->connection->fetchAll('SELECT id FROM centers'); if (count($centers) > 0) { $defaultCenterId = $centers[0]['id']; } else { // if no center, performs other checks //check if there are data in person table $nbPeople = $this->connection->fetchColumn('SELECT count(*) FROM person'); if ($nbPeople > 0) { // we have data ! We have to create a center ! $newCenterId = $this->connection->fetchColumn('SELECT nextval(\'centers_id_seq\');'); $this->addSql( 'INSERT INTO centers (id, name) VALUES (:id, :name)', ['id' => $newCenterId, 'name' => 'Auto-created center'] ); $defaultCenterId = $newCenterId; } } $this->addSql('ALTER TABLE person ADD center_id INT'); if (isset($defaultCenterId)) { $this->addSql('UPDATE person SET center_id = :id', array('id' => $defaultCenterId)); } $this->addSql('ALTER TABLE person ' . 'ADD CONSTRAINT FK_person_center FOREIGN KEY (center_id) ' . 'REFERENCES centers (id) NOT DEFERRABLE INITIALLY IMMEDIATE'); $this->addSql('ALTER TABLE person ALTER center_id SET NOT NULL'); $this->addSql('CREATE INDEX IDX_person_center ON person (center_id)'); } /** * @param Schema $schema */ public function down(Schema $schema): void { $this->abortIf( $this->connection->getDatabasePlatform()->getName() != 'postgresql', 'Migration can only be executed safely on \'postgresql\'.' ); $this->addSql('ALTER TABLE Person DROP CONSTRAINT FK_person_center'); $this->addSql('DROP INDEX IDX_person_center'); $this->addSql('ALTER TABLE Person DROP center_id'); } }