Skip to content

Commit

Permalink
Add error message when a table has no primary key.
Browse files Browse the repository at this point in the history
If we don't have a primary key we cannot safely insert/update records.

Refs #3950
  • Loading branch information
markstory committed Jul 12, 2014
1 parent 48e457e commit f0f52b4
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
9 changes: 8 additions & 1 deletion src/ORM/Table.php
Expand Up @@ -1231,10 +1231,17 @@ protected function _processSave($entity, $options) {
* @param array $data The actual data that needs to be saved
* @return \Cake\Datasource\EntityInterface|bool
* @throws \RuntimeException if not all the primary keys where supplied or could
* be generated when the table has composite primary keys
* be generated when the table has composite primary keys. Or when the table has no primary key.
*/
protected function _insert($entity, $data) {
$primary = (array)$this->primaryKey();
if (empty($primary)) {
$msg = sprintf(
'Cannot insert row in "%s", it has no primary key.',
$this->table()
);
throw new \RuntimeException($msg);
}
$keys = array_fill(0, count($primary), null);
$id = (array)$this->_newId($primary) + $keys;
$primary = array_combine($primary, $id);
Expand Down
19 changes: 19 additions & 0 deletions tests/TestCase/ORM/TableTest.php
Expand Up @@ -1364,6 +1364,25 @@ public function testAfterSaveNotCalled() {
$this->assertFalse($called);
}

/**
* Test that you cannot save rows without a primary key.
*
* @group save
* @expectedException \RuntimeException
* @expectedExceptionMessage Cannot insert row in "users", it has no primary key
* @return void
*/
public function testSaveNewErrorOnNoPrimaryKey() {
$entity = new \Cake\ORM\Entity();
$table = TableRegistry::get('users', [
'schema' => [
'id' => ['type' => 'integer'],
'username' => ['type' => 'string'],
]
]);
$table->save($entity);
}

/**
* Tests that save is wrapped around a transaction
*
Expand Down

0 comments on commit f0f52b4

Please sign in to comment.