3 namespace Drupal\Core\Database\Driver\pgsql;
5 use Drupal\Core\Database\Query\Upsert as QueryUpsert;
8 * PostgreSQL implementation of \Drupal\Core\Database\Query\Upsert.
10 class Upsert extends QueryUpsert {
15 public function execute() {
16 if (!$this->preExecute()) {
20 // Default options for upsert queries.
21 $this->queryOptions += [
22 'throw_exception' => TRUE,
25 // Default fields are always placed first for consistency.
26 $insert_fields = array_merge($this->defaultFields, $this->insertFields);
28 $table = $this->connection->escapeTable($this->table);
30 // We have to execute multiple queries, therefore we wrap everything in a
31 // transaction so that it is atomic where possible.
32 $transaction = $this->connection->startTransaction();
35 // First, lock the table we're upserting into.
36 $this->connection->query('LOCK TABLE {' . $table . '} IN SHARE ROW EXCLUSIVE MODE', [], $this->queryOptions);
38 // Second, delete all items first so we can do one insert.
39 $unique_key_position = array_search($this->key, $insert_fields);
41 foreach ($this->insertValues as $insert_values) {
42 $delete_ids[] = $insert_values[$unique_key_position];
45 // Delete in chunks when a large array is passed.
46 foreach (array_chunk($delete_ids, 1000) as $delete_ids_chunk) {
47 $this->connection->delete($this->table, $this->queryOptions)
48 ->condition($this->key, $delete_ids_chunk, 'IN')
52 // Third, insert all the values.
53 $insert = $this->connection->insert($this->table, $this->queryOptions)
54 ->fields($insert_fields);
55 foreach ($this->insertValues as $insert_values) {
56 $insert->values($insert_values);
60 catch (\Exception $e) {
61 // One of the queries failed, rollback the whole batch.
62 $transaction->rollBack();
64 // Rethrow the exception for the calling code.
68 // Re-initialize the values array so that we can re-use this query.
69 $this->insertValues = [];
71 // Transaction commits here where $transaction looses scope.
79 public function __toString() {