From ea41d72d8b993b7f762417b25c6df9f498d5dc8e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ra=C3=BAl=20Arellano?= Date: Thu, 22 Apr 2021 13:29:04 -0300 Subject: [PATCH] Fix: Restore foreign keys on schema load --- src/Command/SchemaLoadCommand.php | 1 + src/Table.php | 32 ++++++------------------------- 2 files changed, 7 insertions(+), 26 deletions(-) diff --git a/src/Command/SchemaLoadCommand.php b/src/Command/SchemaLoadCommand.php index ea06cd5..21b95c2 100644 --- a/src/Command/SchemaLoadCommand.php +++ b/src/Command/SchemaLoadCommand.php @@ -81,6 +81,7 @@ protected function _loadTables(ConsoleIo $io, array $tables) // Add all foreign key constraints foreach ($tableSchemes as $table) { + $table->restoreForeignKeys(); $foreignKeys = $table->addConstraintSql($db); $queries = array_merge($queries, $foreignKeys); } diff --git a/src/Table.php b/src/Table.php index 74fed96..120e208 100644 --- a/src/Table.php +++ b/src/Table.php @@ -18,13 +18,6 @@ class Table extends TableSchema */ protected $_foreignKeys = []; - /** - * Foreign keys constraints represented as SQL statements - * - * @var array - */ - protected $_foreignKeysSql = []; - /** * Generate the SQL to create the Table without foreign keys. * @@ -37,7 +30,7 @@ class Table extends TableSchema */ public function createSql(Connection $connection): array { - $this->_extractForeignKeys($connection); + $this->_extractForeignKeys(); return parent::createSql($connection); } @@ -45,39 +38,26 @@ public function createSql(Connection $connection): array /** * Returns list of ALTER TABLE statements to add foreign key constraints. * - * @param \Cake\Database\Connection $connection The connection to generate SQL for. - * @return array List of SQL statements to create the foreign keys. + * @return void */ - public function foreignKeysSql(Connection $connection) + public function restoreForeignKeys() { - $constraints = []; - foreach ($this->_foreignKeysSql as $statement) { - // TODO: Move this to the driver. SQLite is not supported. - $constraints[] = sprintf( - 'ALTER TABLE %s ADD %s', - $connection->quoteIdentifier($this->name()), - $statement - ); + foreach ($this->_foreignKeys as $name => $attrs) { + $this->_constraints[$name] = $attrs; } - - return $constraints; } /** * Refresh the protected foreign keys variable. * All foreign keys are removed from the original constraints. * - * @param \Cake\Database\Connection $connection Connection * @return void */ - protected function _extractForeignKeys(Connection $connection) + protected function _extractForeignKeys() { - $dialect = $connection->getDriver()->schemaDialect(); - foreach ($this->_constraints as $name => $attrs) { if ($attrs['type'] === static::CONSTRAINT_FOREIGN) { $this->_foreignKeys[$name] = $attrs; - $this->_foreignKeysSql[$name] = $dialect->constraintSql($this, $name); unset($this->_constraints[$name]); } }