Permalink
Browse files

fix duplicate primary keys for tables without models

  • Loading branch information...
sebastienbarre committed Mar 4, 2017
1 parent 8d0e1fa commit 3849df0f2f55e161767b16b2af45830e2cd7b3cb
Showing with 71 additions and 1 deletion.
  1. +8 −1 lib/Cake/Model/CakeSchema.php
  2. +63 −0 lib/Cake/Test/Case/Model/CakeSchemaTest.php
@@ -613,9 +613,16 @@ protected function _columns(&$Obj) {
$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']])) {
@@ -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 @@ public function testSchemaReadWithCrossDatabase() {
$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
*

0 comments on commit 3849df0

Please sign in to comment.