Security update for Core, with self-updated composer
[yaffs-website] / web / core / lib / Drupal / Core / Database / Driver / pgsql / Upsert.php
1 <?php
2
3 namespace Drupal\Core\Database\Driver\pgsql;
4
5 use Drupal\Core\Database\Query\Upsert as QueryUpsert;
6
7 /**
8  * PostgreSQL implementation of \Drupal\Core\Database\Query\Upsert.
9  */
10 class Upsert extends QueryUpsert {
11
12   /**
13    * {@inheritdoc}
14    */
15   public function execute() {
16     if (!$this->preExecute()) {
17       return NULL;
18     }
19
20     // Default options for upsert queries.
21     $this->queryOptions += [
22       'throw_exception' => TRUE,
23     ];
24
25     // Default fields are always placed first for consistency.
26     $insert_fields = array_merge($this->defaultFields, $this->insertFields);
27
28     $table = $this->connection->escapeTable($this->table);
29
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();
33
34     try {
35       // First, lock the table we're upserting into.
36       $this->connection->query('LOCK TABLE {' . $table . '} IN SHARE ROW EXCLUSIVE MODE', [], $this->queryOptions);
37
38       // Second, delete all items first so we can do one insert.
39       $unique_key_position = array_search($this->key, $insert_fields);
40       $delete_ids = [];
41       foreach ($this->insertValues as $insert_values) {
42         $delete_ids[] = $insert_values[$unique_key_position];
43       }
44
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')
49           ->execute();
50       }
51
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);
57       }
58       $insert->execute();
59     }
60     catch (\Exception $e) {
61       // One of the queries failed, rollback the whole batch.
62       $transaction->rollBack();
63
64       // Rethrow the exception for the calling code.
65       throw $e;
66     }
67
68     // Re-initialize the values array so that we can re-use this query.
69     $this->insertValues = [];
70
71     // Transaction commits here where $transaction looses scope.
72
73     return TRUE;
74   }
75
76   /**
77    * {@inheritdoc}
78    */
79   public function __toString() {
80     // Nothing to do.
81   }
82
83 }