Skip to content

Commit

Permalink
Merge pull request #1965 from gnoddep/fix-foreign-key-error
Browse files Browse the repository at this point in the history
Fix error when creating a foreign key on a table without an autoincrementing primary key in SQlite
  • Loading branch information
dereuromark authored Mar 17, 2021
2 parents 00a6137 + 03c1255 commit a96c546
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 11 deletions.
24 changes: 13 additions & 11 deletions src/Phinx/Db/Adapter/SQLiteAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -1321,17 +1321,19 @@ protected function getAddForeignKeyInstructions(Table $table, ForeignKey $foreig
$tmpTableName = $state['tmpTableName'];
$indexes = $this->getIndexes($tableName);
foreach (array_keys($indexes) as $indexName) {
$sql .= sprintf(
'DROP INDEX %s%s; ',
$schema,
$this->quoteColumnName($indexName)
);
$createIndexSQL = $this->getDeclaringIndexSQL($tableName, $indexName);
$sql .= preg_replace(
"/\b${tableName}\b/",
$tmpTableName,
$createIndexSQL
);
if (strpos($indexName, 'sqlite_autoindex_') !== 0) {
$sql .= sprintf(
'DROP INDEX %s%s; ',
$schema,
$this->quoteColumnName($indexName)
);
$createIndexSQL = $this->getDeclaringIndexSQL($tableName, $indexName);
$sql .= preg_replace(
"/\b${tableName}\b/",
$tmpTableName,
$createIndexSQL
);
}
}

$this->execute($sql);
Expand Down
27 changes: 27 additions & 0 deletions tests/Phinx/Db/Adapter/SQLiteAdapterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,33 @@ public function testCreateTableWithIndexesAndForeignKey()
);
}

public function testCreateTableWithoutAutoIncrementingPrimaryKeyAndWithForeignKey()
{
$refTable = (new \Phinx\Db\Table('tbl_master', ['id' => false, 'primary_key' => 'id'], $this->adapter))
->addColumn('id', 'text');
$refTable->create();

$table = (new \Phinx\Db\Table('tbl_child', ['id' => false, 'primary_key' => 'master_id'], $this->adapter))
->addColumn('master_id', 'text')
->addForeignKey(
'master_id',
'tbl_master',
'id',
['delete' => 'NO_ACTION', 'update' => 'NO_ACTION', 'constraint' => 'fk_master_id']
);
$table->create();

$this->assertTrue($this->adapter->hasForeignKey('tbl_child', ['master_id']));

$row = $this->adapter->fetchRow(
"SELECT * FROM sqlite_master WHERE `type` = 'table' AND `tbl_name` = 'tbl_child'"
);
$this->assertStringContainsString(
'CONSTRAINT `fk_master_id` FOREIGN KEY (`master_id`) REFERENCES `tbl_master` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION',
$row['sql']
);
}

public function testAddPrimaryKey()
{
$table = new \Phinx\Db\Table('table1', ['id' => false], $this->adapter);
Expand Down

0 comments on commit a96c546

Please sign in to comment.