Skip to content

Commit 630079e

Browse files
Fix adding column to sqlite table created outside phinx
Co-authored-by: SlavaAurim <[email protected]>
1 parent 9973b35 commit 630079e

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

src/Phinx/Db/Adapter/SQLiteAdapter.php

+15
Original file line numberDiff line numberDiff line change
@@ -734,6 +734,21 @@ protected function getDeclaringSql($tableName)
734734
}
735735
}
736736

737+
$columnsInfo = $this->getTableInfo($tableName);
738+
739+
foreach ($columnsInfo as $column) {
740+
$columnName = $column['name'];
741+
$columnNamePattern = "\"$columnName\"|`$columnName`|\\[$columnName\\]|$columnName";
742+
$columnNamePattern = "#([\(,]+\\s*)($columnNamePattern)(\\s)#iU";
743+
744+
$sql = preg_replace($columnNamePattern, "$1`$columnName`$3", $sql);
745+
}
746+
747+
$tableNamePattern = "\"$tableName\"|`$tableName`|\\[$tableName\\]|$tableName";
748+
$tableNamePattern = "#^(CREATE TABLE)\s*($tableNamePattern)\s*(\()#Ui";
749+
750+
$sql = preg_replace($tableNamePattern, "$1 `$tableName` $3", $sql, 1);
751+
737752
return $sql;
738753
}
739754

tests/Phinx/Db/Adapter/SQLiteAdapterTest.php

+27
Original file line numberDiff line numberDiff line change
@@ -488,6 +488,33 @@ public function testAddColumnWithDefaultEmptyString()
488488
$this->assertEquals("''", $rows[1]['dflt_value']);
489489
}
490490

491+
public function irregularCreateTableProvider()
492+
{
493+
return [
494+
["CREATE TABLE \"users\"\n( `id` INTEGER NOT NULL )", ['id', 'foo']],
495+
['CREATE TABLE users ( id INTEGER NOT NULL )', ['id', 'foo']],
496+
["CREATE TABLE [users]\n(\nid INTEGER NOT NULL)", ['id', 'foo']],
497+
["CREATE TABLE \"users\" ([id] \n INTEGER NOT NULL\n, \"bar\" INTEGER)", ['id', 'bar', 'foo']],
498+
];
499+
}
500+
501+
/**
502+
* @dataProvider irregularCreateTableProvider
503+
*/
504+
public function testAddColumnToIrregularCreateTableStatements(string $createTableSql, array $expectedColumns): void
505+
{
506+
$this->adapter->execute($createTableSql);
507+
$table = new \Phinx\Db\Table('users', [], $this->adapter);
508+
$table->addColumn('foo', 'string');
509+
$table->update();
510+
511+
$columns = $this->adapter->getColumns('users');
512+
$columnCount = count($columns);
513+
for ($i = 0; $i < $columnCount; $i++) {
514+
$this->assertEquals($expectedColumns[$i], $columns[$i]->getName());
515+
}
516+
}
517+
491518
public function testAddDoubleColumn()
492519
{
493520
$table = new \Phinx\Db\Table('table1', [], $this->adapter);

0 commit comments

Comments
 (0)