Skip to content

Commit

Permalink
Fix: Restore foreign keys on schema load
Browse files Browse the repository at this point in the history
  • Loading branch information
raul338 committed Apr 22, 2021
1 parent 32149dd commit ea41d72
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 26 deletions.
1 change: 1 addition & 0 deletions src/Command/SchemaLoadCommand.php
Expand Up @@ -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);
}
Expand Down
32 changes: 6 additions & 26 deletions src/Table.php
Expand Up @@ -18,13 +18,6 @@ class Table extends TableSchema
*/
protected $_foreignKeys = [];

/**
* Foreign keys constraints represented as SQL statements
*
* @var array<string>
*/
protected $_foreignKeysSql = [];

/**
* Generate the SQL to create the Table without foreign keys.
*
Expand All @@ -37,47 +30,34 @@ class Table extends TableSchema
*/
public function createSql(Connection $connection): array
{
$this->_extractForeignKeys($connection);
$this->_extractForeignKeys();

return parent::createSql($connection);
}

/**
* Returns list of ALTER TABLE statements to add foreign key constraints.
*
* @param \Cake\Database\Connection $connection The connection to generate SQL for.
* @return array<string> 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]);
}
}
Expand Down

0 comments on commit ea41d72

Please sign in to comment.