Skip to content

Commit

Permalink
Allow primary key values to be set when creating records.
Browse files Browse the repository at this point in the history
When using UUIDs it is often helpful to allow external systems to define
your UUID values. This change lets entity data replace generated values.

Refs #6185
  • Loading branch information
markstory committed Mar 28, 2015
1 parent 80e2008 commit 7eb09b0
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 7 deletions.
2 changes: 1 addition & 1 deletion src/ORM/Table.php
Expand Up @@ -1487,7 +1487,7 @@ protected function _insert($entity, $data)
$id = (array)$this->_newId($primary) + $keys;
$primary = array_combine($primary, $id);
$filteredKeys = array_filter($primary, 'strlen');
$data = $filteredKeys + $data;
$data = $data + $filteredKeys;

if (count($primary) > 1) {
$schema = $this->schema();
Expand Down
32 changes: 26 additions & 6 deletions tests/TestCase/ORM/TableUuidTest.php
Expand Up @@ -17,9 +17,11 @@
use Cake\Core\Configure;
use Cake\Database\Expression\QueryExpression;
use Cake\Datasource\ConnectionManager;
use Cake\ORM\Entity;
use Cake\ORM\Table;
use Cake\ORM\TableRegistry;
use Cake\TestSuite\TestCase;
use Cake\Utility\Text;

/**
* Integration tests for Table class with uuid primary keys.
Expand Down Expand Up @@ -67,7 +69,7 @@ public function tearDown()
*/
public function testSaveNew()
{
$entity = new \Cake\ORM\Entity([
$entity = new Entity([
'name' => 'shiny new',
'published' => true,
]);
Expand All @@ -80,6 +82,28 @@ public function testSaveNew()
$this->assertEquals($entity->toArray(), $row->toArray());
}

/**
* Test saving new records allows manual uuids
*
* @return void
*/
public function testSaveNewSpecificId()
{
$id = Text::uuid();
$entity = new Entity([
'id' => $id,
'name' => 'shiny and new',
'published' => true,
]);
$table = TableRegistry::get('uuiditems');
$this->assertSame($entity, $table->save($entity));

$row = $table->find('all')->where(['id' => $id])->first();
$this->assertNotEmpty($row);
$this->assertSame($id, $row->id);
$this->assertSame($entity->name, $row->name);
}

/**
* Test saving existing records works
*
Expand All @@ -88,7 +112,7 @@ public function testSaveNew()
public function testSaveUpdate()
{
$id = '481fc6d0-b920-43e0-a40d-6d1740cf8569';
$entity = new \Cake\ORM\Entity([
$entity = new Entity([
'id' => $id,
'name' => 'shiny update',
'published' => true,
Expand Down Expand Up @@ -126,10 +150,6 @@ public function testDelete()
*/
public function testEmptyUuid()
{
$this->skipIf(
!$this->connection->driver() instanceof \Cake\Database\Driver\Sqlserver,
'Empty UUIDs only affect SQLServer uniqueidentifier field types'
);
$id = '';
$table = TableRegistry::get('uuiditems');
$entity = $table->find('all')
Expand Down

0 comments on commit 7eb09b0

Please sign in to comment.