Skip to content

Commit

Permalink
Making save atomic
Browse files Browse the repository at this point in the history
  • Loading branch information
lorenzo committed Oct 24, 2013
1 parent 6d9b73d commit 2b51e89
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 8 deletions.
33 changes: 25 additions & 8 deletions Cake/ORM/Table.php
Expand Up @@ -775,7 +775,7 @@ public function deleteAll($conditions) {
}

public function save(Entity $entity, array $options = []) {
$options = new \ArrayObject($options);
$options = new \ArrayObject($options + ['atomic' => true]);
$event = new Event('Model.beforeSave', $this, compact('entity', 'options'));
$this->getEventManager()->dispatch($event);

Expand All @@ -790,23 +790,40 @@ public function save(Entity $entity, array $options = []) {
$schema = $this->schema();
$data = array_intersect_key($data, array_flip($schema->columns()));
$query = $this->_buildQuery();
$statement = $query->insert($this->table(), array_keys($data))

$connection = $this->connection();
if ($options['atomic']) {
$connection->begin();
}

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

$success = false;
if ($statement->rowCount() > 0) {
$primary = $this->primaryKey();
$id = $statement->lastInsertId($this->table(), $primary);
$entity->set($primary, $id);
$success = $entity;
$success = false;
if ($statement->rowCount() > 0) {
$primary = $this->primaryKey();
$id = $statement->lastInsertId($this->table(), $primary);
$entity->set($primary, $id);
$success = $entity;
}
} catch (\Exception $e) {
if ($options['atomic']) {
$connection->rollback();
}
throw $e;
}

if ($success) {
$event = new Event('Model.afterSave', $this, compact('entity', 'options'));
$this->getEventManager()->dispatch($event);
}

if ($options['atomic']) {
$connection->commit();
}

return $success;
}

Expand Down
26 changes: 26 additions & 0 deletions Cake/Test/TestCase/ORM/TableTest.php
Expand Up @@ -1136,4 +1136,30 @@ public function testAfterSaveNotCalled() {
$this->assertFalse($called);
}

/**
* Tests that save is wrapped around a transaction
*
* @return void
*/
public function testAtomicSave() {
$connection = $this->getMock(
'\Cake\Database\Connection',
['begin', 'commit'],
[ConnectionManager::config('test')]
);
$connection->driver(ConnectionManager::get('test')->driver());
$table = $this->getMock('\Cake\ORM\Table', ['connection'], [['table' => 'users']]);
$table->expects($this->any())->method('connection')
->will($this->returnValue($connection));

$connection->expects($this->once())->method('begin');
$connection->expects($this->once())->method('commit');
$data = new \Cake\ORM\Entity([
'username' => 'superuser',
'created' => new \DateTime('2013-10-10 00:00'),
'updated' => new \DateTime('2013-10-10 00:00')
]);
$this->assertSame($data, $table->save($data));
}

}

0 comments on commit 2b51e89

Please sign in to comment.