Browse Source

Merge pull request #3956 from markstory/issue-3950

Add error message when a table has no primary key.
José Lorenzo Rodríguez 11 years ago
parent
commit
1ad01259dd
2 changed files with 27 additions and 1 deletions
  1. 8 1
      src/ORM/Table.php
  2. 19 0
      tests/TestCase/ORM/TableTest.php

+ 8 - 1
src/ORM/Table.php

@@ -1231,10 +1231,17 @@ class Table implements RepositoryInterface, EventListener {
  * @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);

+ 19 - 0
tests/TestCase/ORM/TableTest.php

@@ -1365,6 +1365,25 @@ class TableTest extends \Cake\TestSuite\TestCase {
 	}
 
 /**
+ * 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
  *
  * @group save