Skip to content

Commit

Permalink
Only saving properties that were marked as dirty
Browse files Browse the repository at this point in the history
  • Loading branch information
lorenzo committed Oct 26, 2013
1 parent 67571cf commit bcf66a2
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 1 deletion.
11 changes: 10 additions & 1 deletion Cake/ORM/Table.php
Expand Up @@ -711,8 +711,16 @@ protected function _processSave($entity, $options) {

$schema = $this->schema();
$data = array_intersect_key($data, array_flip($schema->columns()));
$keys = array_keys($data);

foreach ($keys as $i => $property) {
if (!$entity->dirty($property)) {
unset($keys[$i], $data[$property]);
}
}

$query = $this->_buildQuery();
$statement = $query->insert($this->table(), array_keys($data))
$statement = $query->insert($this->table(), $keys)
->values($data)
->executeStatement();

Expand All @@ -721,6 +729,7 @@ protected function _processSave($entity, $options) {
$primary = $this->primaryKey();
$id = $statement->lastInsertId($this->table(), $primary);
$entity->set($primary, $id);
$entity->clean();
$success = $entity;
}

Expand Down
47 changes: 47 additions & 0 deletions Cake/Test/TestCase/ORM/TableTest.php
Expand Up @@ -1238,4 +1238,51 @@ public function testAtomicSaveRollbackOnFailure() {
$table->save($data);
}

/**
* Tests that only the properties marked as dirty are actually saved
* to the database
*
* @return void
*/
public function testSaveOnlyDirtyProperties() {
$entity = new \Cake\ORM\Entity([
'username' => 'superuser',
'password' => 'root',
'created' => new \DateTime('2013-10-10 00:00'),
'updated' => new \DateTime('2013-10-10 00:00')
]);
$entity->clean();
$entity->dirty('username', true);
$entity->dirty('created', true);
$entity->dirty('updated', true);

$table = TableRegistry::get('users');
$this->assertSame($entity, $table->save($entity));
$this->assertEquals($entity->id, 5);

$row = $table->find('all')->where(['id' => 5])->first();
$entity->set('password', null);
$this->assertEquals($entity->toArray(), $row->toArray());
}

/**
* Tests that a recently saved entity is marked as clean
*
* @return void
*/
public function testsASavedEntityIsClean() {
$entity = new \Cake\ORM\Entity([
'username' => 'superuser',
'password' => 'root',
'created' => new \DateTime('2013-10-10 00:00'),
'updated' => new \DateTime('2013-10-10 00:00')
]);
$table = TableRegistry::get('users');
$this->assertSame($entity, $table->save($entity));
$this->assertFalse($entity->dirty('usermane'));
$this->assertFalse($entity->dirty('password'));
$this->assertFalse($entity->dirty('created'));
$this->assertFalse($entity->dirty('updated'));
}

}

0 comments on commit bcf66a2

Please sign in to comment.