DbObject: allow specific objects to change their

...autoinc ID
This commit is contained in:
Thomas Gelf 2018-10-08 08:29:37 +02:00
parent 77c4997b88
commit affcc54ba3

View File

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