Fixed race condition in entity preparation

This commit is contained in:
Marcin Kurczewski 2014-11-11 19:24:05 +01:00
parent 399a648ed8
commit 13e622f9e7

View file

@ -131,14 +131,15 @@ abstract class AbstractDao implements ICrudDao, IBatchDao
public function create(Entity $entity) public function create(Entity $entity)
{ {
$sequencerQuery = $this->pdo->from('sequencer')->where('tableName', $this->tableName); $sql = 'UPDATE sequencer SET lastUsedId = (@lastUsedId := (lastUsedId + 1)) WHERE tableName = :tableName';
$lastUsedId = intval(iterator_to_array($sequencerQuery)[0]['lastUsedId']); $query = $this->pdo->prepare($sql);
$lastUsedId ++; $query->bindValue(':tableName', $this->tableName);
$query->execute();
$lastUsedId = $this->pdo->query('SELECT @lastUsedId')->fetchColumn();
$entity->setId($lastUsedId); $entity->setId($lastUsedId);
$arrayEntity = $this->entityConverter->toArray($entity); $arrayEntity = $this->entityConverter->toArray($entity);
$this->pdo->insertInto($this->tableName)->values($arrayEntity)->execute(); $this->pdo->insertInto($this->tableName)->values($arrayEntity)->execute();
$this->pdo->update('sequencer')->set(['lastUsedId' => $lastUsedId])->where('tableName', $this->tableName)->execute();
return $entity; return $entity;
} }