Skip to content
Permalink
Browse files

Add error message when a table has no primary key.

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 f0f52b4af6cab46cb134911fe1aea4629ae63e22
Showing with 27 additions and 1 deletion.
  1. +8 −1 src/ORM/Table.php
  2. +19 −0 tests/TestCase/ORM/TableTest.php
@@ -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);
@@ -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
*

0 comments on commit f0f52b4

Please sign in to comment.
You can’t perform that action at this time.