Browse Source

Do not allow updates to tables with no primary key

Raise exceptions instead of allowing updates to tables without primary
keys.

Refs #11726
Mark Story 8 years ago
parent
commit
f21c436df4
2 changed files with 25 additions and 0 deletions
  1. 7 0
      src/ORM/Table.php
  2. 18 0
      tests/TestCase/ORM/TableRegressionTest.php

+ 7 - 0
src/ORM/Table.php

@@ -1989,6 +1989,13 @@ class Table implements RepositoryInterface, EventListenerInterface, EventDispatc
             return $entity;
         }
 
+        if (empty($primaryColumns)) {
+            $entityClass = get_class($entity);
+            $table = $this->getTable();
+            $message = "Cannot update `$entityClass` the `$table` has no primary key.";
+            throw new InvalidArgumentException($message);
+        }
+
         if (!$entity->has($primaryColumns)) {
             $message = 'All primary key value(s) are needed for updating, ';
             $message .= get_class($entity) . ' is missing ' . implode(', ', $primaryColumns);

+ 18 - 0
tests/TestCase/ORM/TableRegressionTest.php

@@ -16,6 +16,7 @@ namespace Cake\Test\TestCase\ORM;
 
 use Cake\ORM\TableRegistry;
 use Cake\TestSuite\TestCase;
+use InvalidArgumentException;
 
 /**
  * Contains regression test for the Table class
@@ -64,4 +65,21 @@ class TableRegressionTest extends TestCase
         $entity = $table->newEntity(['name' => 'Jon']);
         $table->save($entity);
     }
+
+    /**
+     * Ensure that saving to a table with no primary key fails.
+     *
+     * @return void
+     */
+    public function testSaveNoPrimaryKeyException()
+    {
+        $this->expectException(InvalidArgumentException::class);
+        $this->expectExceptionMessage('primary key');
+        $table = TableRegistry::get('Authors');
+        $table->getSchema()->dropConstraint('primary');
+
+        $entity = $table->find()->first();
+        $entity->name = 'new name';
+        $table->save($entity);
+    }
 }