fix duplicate primary keys for tables without models

This commit is contained in:
Sebastien Barre 2017-03-04 00:51:20 -05:00
parent 8d0e1fadf7
commit 3849df0f2f
2 changed files with 71 additions and 1 deletions

View file

@ -613,9 +613,16 @@ class CakeSchema extends CakeObject {
$db = $Obj->getDataSource(); $db = $Obj->getDataSource();
$fields = $Obj->schema(true); $fields = $Obj->schema(true);
$hasPrimaryAlready = false;
foreach ($fields as $value) {
if (isset($value['key']) && $value['key'] === 'primary') {
$hasPrimaryAlready = true;
}
}
$columns = array(); $columns = array();
foreach ($fields as $name => $value) { foreach ($fields as $name => $value) {
if ($Obj->primaryKey === $name) { if ($Obj->primaryKey === $name && !$hasPrimaryAlready && !isset($value['key'])) {
$value['key'] = 'primary'; $value['key'] = 'primary';
} }
if (!isset($db->columns[$value['type']])) { if (!isset($db->columns[$value['type']])) {

View file

@ -363,6 +363,39 @@ class SchemaCrossDatabaseFixture extends CakeTestFixture {
); );
} }
/**
* NonConventionalPrimaryKeyFixture class
*
* @package Cake.Test.Case.Model
*/
class NonConventionalPrimaryKeyFixture extends CakeTestFixture {
/**
* name property
*
* @var string
*/
public $name = 'NonConventional';
/**
* table property
*
* @var string
*/
public $table = 'non_conventional';
/**
* fields property
*
* @var array
*/
public $fields = array(
'version_id' => array('type' => 'integer', 'key' => 'primary'),
'id' => array('type' => 'integer'),
'name' => 'string'
);
}
/** /**
* SchemaPrefixAuthUser class * SchemaPrefixAuthUser class
* *
@ -649,6 +682,36 @@ class CakeSchemaTest extends CakeTestCase {
$fixture->drop($db); $fixture->drop($db);
} }
/**
* testSchemaRead method when a primary key is on a non-conventional column
*
* @return void
*/
public function testSchemaReadWithNonConventionalPrimaryKey() {
$db = ConnectionManager::getDataSource('test');
$fixture = new NonConventionalPrimaryKeyFixture();
$fixture->create($db);
$read = $this->Schema->read(array(
'connection' => 'test',
'name' => 'TestApp',
'models' => false
));
$fixture->drop($db);
$has_table = isset($read['tables']['non_conventional']);
$this->assertTrue($has_table, 'non_conventional table should appear');
if ($has_table) {
$version_id_has_key = isset($read['tables']['non_conventional']['version_id']['key']);
$this->assertTrue($version_id_has_key, 'version_id key should be set');
if ($version_id_has_key) {
$version_id_key_is_primary = $read['tables']['non_conventional']['version_id']['key'] === 'primary';
$this->assertTrue($version_id_key_is_primary, 'version_id key should be primary');
}
$this->assertFalse(isset($read['tables']['non_conventional']['id']['key']), 'id key should not be set');
}
}
/** /**
* test that tables are generated correctly * test that tables are generated correctly
* *