diff --git a/lib/Cake/Model/CakeSchema.php b/lib/Cake/Model/CakeSchema.php index 529ceb5f8..51bab41ab 100644 --- a/lib/Cake/Model/CakeSchema.php +++ b/lib/Cake/Model/CakeSchema.php @@ -613,9 +613,16 @@ class CakeSchema extends CakeObject { $db = $Obj->getDataSource(); $fields = $Obj->schema(true); + $hasPrimaryAlready = false; + foreach ($fields as $value) { + if (isset($value['key']) && $value['key'] === 'primary') { + $hasPrimaryAlready = true; + } + } + $columns = array(); foreach ($fields as $name => $value) { - if ($Obj->primaryKey === $name) { + if ($Obj->primaryKey === $name && !$hasPrimaryAlready && !isset($value['key'])) { $value['key'] = 'primary'; } if (!isset($db->columns[$value['type']])) { diff --git a/lib/Cake/Test/Case/Model/CakeSchemaTest.php b/lib/Cake/Test/Case/Model/CakeSchemaTest.php index aedb6ef3d..bb9ddb7bb 100644 --- a/lib/Cake/Test/Case/Model/CakeSchemaTest.php +++ b/lib/Cake/Test/Case/Model/CakeSchemaTest.php @@ -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 * @@ -649,6 +682,36 @@ class CakeSchemaTest extends CakeTestCase { $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 *