diff --git a/library/Director/Data/Db/DbObject.php b/library/Director/Data/Db/DbObject.php index cf53d627..1d3e101e 100644 --- a/library/Director/Data/Db/DbObject.php +++ b/library/Director/Data/Db/DbObject.php @@ -69,6 +69,9 @@ abstract class DbObject */ protected $autoincKeyName; + /** @var bool forbid updates to autoinc values */ + protected $protectAutoinc = true; + /** * Filled with object instances when prefetchAll is used */ @@ -447,7 +450,7 @@ abstract class DbObject { $props = array(); foreach (array_keys($this->modifiedProperties) as $key) { - if ($key === $this->autoincKeyName) { + if ($this->protectAutoinc && $key === $this->autoincKeyName) { continue; } @@ -727,7 +730,7 @@ abstract class DbObject protected function insertIntoDb() { $properties = $this->getPropertiesForDb(); - if ($this->autoincKeyName !== null) { + if ($this->autoincKeyName !== null && $this->protectAutoinc) { unset($properties[$this->autoincKeyName]); } // TODO: Remove this! @@ -785,15 +788,20 @@ abstract class DbObject } } else { if ($id && $this->existsInDb()) { + $logId = '"' . $this->getLogId() . '"'; + + if ($autoId = $this->getAutoincId()) { + $logId .= sprintf(', %s=%s', $this->autoincKeyName, $autoId); + } throw new DuplicateKeyException( 'Trying to recreate %s (%s)', $table, - $this->getLogId() + $logId ); } if ($this->insertIntoDb()) { - if ($this->autoincKeyName) { + if ($this->autoincKeyName && $this->getProperty($this->autoincKeyName) === null) { if ($this->connection->isPgsql()) { $this->properties[$this->autoincKeyName] = $this->db->lastInsertId( $table, @@ -885,6 +893,12 @@ abstract class DbObject public function createWhere() { if ($id = $this->getAutoincId()) { + if ($originalId = $this->getOriginalProperty($this->autoincKeyName)) { + return $this->db->quoteInto( + sprintf('%s = ?', $this->autoincKeyName), + $originalId + ); + } return $this->db->quoteInto( sprintf('%s = ?', $this->autoincKeyName), $id