| Versionen | |
|---|---|
| drupal7 | public MergeQuery::execute() |
includes/
<?php
public function execute() {
// A merge query without any key field is invalid.
if (count($this->keyFields) == 0) {
throw new InvalidMergeQueryException("You need to specify key fields before executing a merge query");
}
// In the degenerate case of this query type, we have to run multiple
// queries as there is no universal single-query mechanism that will work.
// Our degenerate case is not designed for performance efficiency but
// for comprehensibility. Any practical database driver will override
// this method with database-specific logic, so this function serves only
// as a fallback to aid developers of new drivers.
// Wrap multiple queries in a transaction, if the database supports it.
$transaction = $this->connection->startTransaction();
// Manually check if the record already exists.
$select = $this->connection->select($this->table);
foreach ($this->keyFields as $field => $value) {
$select->condition($field, $value);
}
$select = $select->countQuery();
$sql = (string) $select;
$arguments = $select->getArguments();
$num_existing = db_query($sql, $arguments)->fetchField();
if ($num_existing) {
// If there is already an existing record, run an update query.
if ($this->updateFields) {
$update_fields = $this->updateFields;
}
else {
$update_fields = $this->insertFields;
// If there are no exclude fields, this is a no-op.
foreach ($this->excludeFields as $exclude_field) {
unset($update_fields[$exclude_field]);
}
}
if ($update_fields || $this->expressionFields) {
// Only run the update if there are no fields or expressions to update.
$update = $this->connection->update($this->table, $this->queryOptions)->fields($update_fields);
foreach ($this->keyFields as $field => $value) {
$update->condition($field, $value);
}
foreach ($this->expressionFields as $field => $expression) {
$update->expression($field, $expression['expression'], $expression['arguments']);
}
$update->execute();
}
}
else {
// If there is no existing record, run an insert query.
$insert_fields = $this->insertFields + $this->keyFields;
$this->connection->insert($this->table, $this->queryOptions)->fields($insert_fields)->execute();
}
// Transaction commits here where $transaction looses scope.
}
?>
Kommentare
Kommentar hinzufügen