NativeUpsert.php in Drupal 8
File
core/lib/Drupal/Core/Database/Driver/pgsql/NativeUpsert.php
View source
<?php
namespace Drupal\Core\Database\Driver\pgsql;
use Drupal\Core\Database\Query\Upsert as QueryUpsert;
class NativeUpsert extends QueryUpsert {
public function execute() {
if (!$this
->preExecute()) {
return NULL;
}
$stmt = $this->connection
->prepareQuery((string) $this);
$table_information = $this->connection
->schema()
->queryTableInformation($this->table);
$max_placeholder = 0;
$blobs = [];
$blob_count = 0;
foreach ($this->insertValues as $insert_values) {
foreach ($this->insertFields as $idx => $field) {
if (isset($table_information->blob_fields[$field])) {
$blobs[$blob_count] = fopen('php://memory', 'a');
fwrite($blobs[$blob_count], $insert_values[$idx]);
rewind($blobs[$blob_count]);
$stmt
->bindParam(':db_insert_placeholder_' . $max_placeholder++, $blobs[$blob_count], \PDO::PARAM_LOB);
++$blob_count;
}
else {
$stmt
->bindParam(':db_insert_placeholder_' . $max_placeholder++, $insert_values[$idx]);
}
}
if (!empty($table_information->serial_fields)) {
foreach ($table_information->serial_fields as $index => $serial_field) {
$serial_key = array_search($serial_field, $this->insertFields);
if ($serial_key !== FALSE) {
$serial_value = $insert_values[$serial_key];
if ($serial_value === NULL || !$serial_value) {
$serial_value = 1;
}
$this->connection
->query("SELECT setval('" . $table_information->sequences[$index] . "', GREATEST(MAX(" . $serial_field . "), :serial_value)) FROM {" . $this->table . "}", [
':serial_value' => (int) $serial_value,
]);
}
}
}
}
$options = $this->queryOptions;
if (!empty($table_information->sequences)) {
$options['sequence_name'] = $table_information->sequences[0];
}
$this->insertValues = [];
$this->connection
->addSavepoint();
try {
$this->connection
->query($stmt, [], $options);
$this->connection
->releaseSavepoint();
} catch (\Exception $e) {
$this->connection
->rollbackSavepoint();
throw $e;
}
return TRUE;
}
public function __toString() {
$comments = $this->connection
->makeComment($this->comments);
$insert_fields = array_merge($this->defaultFields, $this->insertFields);
$insert_fields = array_map(function ($f) {
return $this->connection
->escapeField($f);
}, $insert_fields);
$query = $comments . 'INSERT INTO {' . $this->table . '} (' . implode(', ', $insert_fields) . ') VALUES ';
$values = $this
->getInsertPlaceholderFragment($this->insertValues, $this->defaultFields);
$query .= implode(', ', $values);
unset($insert_fields[$this->key]);
$update = [];
foreach ($insert_fields as $field) {
$update[] = "{$field} = EXCLUDED.{$field}";
}
$query .= ' ON CONFLICT (' . $this->connection
->escapeField($this->key) . ') DO UPDATE SET ' . implode(', ', $update);
return $query;
}
}