Skip to content

Commit

Permalink
Fix constraint & foreign key reflection when columns are keywords
Browse files Browse the repository at this point in the history
Fixes #3348
  • Loading branch information
markstory committed Apr 18, 2014
1 parent faf7b18 commit 37d5323
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 3 deletions.
18 changes: 16 additions & 2 deletions src/Database/Schema/PostgresSchema.php
Expand Up @@ -195,7 +195,7 @@ public function convertIndexDescription(Table $table, $row) {
$type = Table::CONSTRAINT_UNIQUE;
}
preg_match('/\(([^\)]+)\)/', $row['statement'], $matches);
$columns = explode(', ', $matches[1]);
$columns = $this->_convertColumnList($matches[1]);
if ($type === Table::CONSTRAINT_PRIMARY || $type === Table::CONSTRAINT_UNIQUE) {
$table->addConstraint($name, [
'type' => $type,
Expand All @@ -220,6 +220,20 @@ public function convertIndexDescription(Table $table, $row) {
]);
}

/**
* Convert a column list into a clean array.
*
* @param string $columns comma separated column list.
* @return array
*/
protected function _convertColumnList($columns) {
$columns = explode(', ', $columns);
foreach ($columns as &$column) {
$column = trim($column, '"');
}
return $columns;
}

/**
* {@inheritdoc}
*
Expand Down Expand Up @@ -255,7 +269,7 @@ public function convertForeignKeyDescription(Table $table, $row) {
$column = $matches[2];

preg_match('/FOREIGN KEY \(([^\)]+)\) REFERENCES/', $row['definition'], $matches);
$columns = explode(',', $matches[1]);
$columns = $this->_convertColumnList($matches[1]);

$data = [
'type' => Table::CONSTRAINT_FOREIGN,
Expand Down
33 changes: 32 additions & 1 deletion tests/TestCase/Database/Schema/PostgresSchemaTest.php
Expand Up @@ -53,8 +53,10 @@ protected function _createTables($connection) {
id SERIAL,
name VARCHAR(50),
bio DATE,
position INT,
created TIMESTAMP,
PRIMARY KEY (id)
PRIMARY KEY (id),
CONSTRAINT "unique_position" UNIQUE ("position")
)
SQL;
$connection->execute($table);
Expand Down Expand Up @@ -320,6 +322,35 @@ public function testDescribeTable() {
}
}

/**
* Test describing a table with containing keywords
*
* @return void
*/
public function testDescribeTableConstraintsWithKeywords() {
$connection = ConnectionManager::get('test');
$this->_createTables($connection);

$schema = new SchemaCollection($connection);
$result = $schema->describe('schema_authors');
$this->assertInstanceOf('Cake\Database\Schema\Table', $result);
$expected = [
'primary' => [
'type' => 'primary',
'columns' => ['id'],
'length' => []
],
'unique_position' => [
'type' => 'unique',
'columns' => ['position'],
'length' => []
]
];
$this->assertCount(2, $result->constraints());
$this->assertEquals($expected['primary'], $result->constraint('primary'));
$this->assertEquals($expected['unique_position'], $result->constraint('unique_position'));
}

/**
* Test describing a table with indexes
*
Expand Down

0 comments on commit 37d5323

Please sign in to comment.