View source
<?php
namespace Drupal\Core\Database\Driver\pgsql;
use Drupal\Core\Database\Database;
use Drupal\Core\Database\Query\Insert as QueryInsert;
class Insert extends QueryInsert {
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 = array();
$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 ($index == 0) {
$last_insert_id = $serial_value;
}
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 . "}", array(
':serial_value' => (int) $serial_value,
));
}
}
}
}
if (!empty($this->fromQuery)) {
$arguments = $this->fromQuery
->getArguments();
foreach ($arguments as $key => $value) {
$stmt
->bindParam($key, $arguments[$key]);
}
}
$options = $this->queryOptions;
if (!empty($table_information->sequences)) {
$options['sequence_name'] = $table_information->sequences[0];
}
elseif ($options['return'] == Database::RETURN_INSERT_ID) {
$options['return'] = Database::RETURN_NULL;
}
if (!empty($last_insert_id)) {
$this->connection
->query($stmt, array(), $options);
}
else {
$last_insert_id = $this->connection
->query($stmt, array(), $options);
}
$this->insertValues = array();
return $last_insert_id;
}
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);
if (!empty($this->fromQuery)) {
$insert_fields_string = $insert_fields ? ' (' . implode(', ', $insert_fields) . ') ' : ' ';
return $comments . 'INSERT INTO {' . $this->table . '}' . $insert_fields_string . $this->fromQuery;
}
$query = $comments . 'INSERT INTO {' . $this->table . '} (' . implode(', ', $insert_fields) . ') VALUES ';
$values = $this
->getInsertPlaceholderFragment($this->insertValues, $this->defaultFields);
$query .= implode(', ', $values);
return $query;
}
}