Updated Drupal to 8.6. This goes with the following updates because it's possible...
[yaffs-website] / web / core / lib / Drupal / Core / Database / Driver / pgsql / Connection.php
1 <?php
2
3 namespace Drupal\Core\Database\Driver\pgsql;
4
5 use Drupal\Core\Database\Database;
6 use Drupal\Core\Database\Connection as DatabaseConnection;
7 use Drupal\Core\Database\DatabaseAccessDeniedException;
8 use Drupal\Core\Database\DatabaseNotFoundException;
9
10 /**
11  * @addtogroup database
12  * @{
13  */
14
15 /**
16  * PostgreSQL implementation of \Drupal\Core\Database\Connection.
17  */
18 class Connection extends DatabaseConnection {
19
20   /**
21    * The name by which to obtain a lock for retrieve the next insert id.
22    */
23   const POSTGRESQL_NEXTID_LOCK = 1000;
24
25   /**
26    * Error code for "Unknown database" error.
27    */
28   const DATABASE_NOT_FOUND = 7;
29
30   /**
31    * Error code for "Connection failure" errors.
32    *
33    * Technically this is an internal error code that will only be shown in the
34    * PDOException message. It will need to get extracted.
35    */
36   const CONNECTION_FAILURE = '08006';
37
38   /**
39    * A map of condition operators to PostgreSQL operators.
40    *
41    * In PostgreSQL, 'LIKE' is case-sensitive. ILIKE should be used for
42    * case-insensitive statements.
43    */
44   protected static $postgresqlConditionOperatorMap = [
45     'LIKE' => ['operator' => 'ILIKE'],
46     'LIKE BINARY' => ['operator' => 'LIKE'],
47     'NOT LIKE' => ['operator' => 'NOT ILIKE'],
48     'REGEXP' => ['operator' => '~*'],
49   ];
50
51   /**
52    * The list of PostgreSQL reserved key words.
53    *
54    * @see http://www.postgresql.org/docs/9.4/static/sql-keywords-appendix.html
55    */
56   protected $postgresqlReservedKeyWords = ['all', 'analyse', 'analyze', 'and',
57     'any', 'array', 'as', 'asc', 'asymmetric', 'authorization', 'binary', 'both',
58     'case', 'cast', 'check', 'collate', 'collation', 'column', 'concurrently',
59     'constraint', 'create', 'cross', 'current_catalog', 'current_date',
60     'current_role', 'current_schema', 'current_time', 'current_timestamp',
61     'current_user', 'default', 'deferrable', 'desc', 'distinct', 'do', 'else',
62     'end', 'except', 'false', 'fetch', 'for', 'foreign', 'freeze', 'from', 'full',
63     'grant', 'group', 'having', 'ilike', 'in', 'initially', 'inner', 'intersect',
64     'into', 'is', 'isnull', 'join', 'lateral', 'leading', 'left', 'like', 'limit',
65     'localtime', 'localtimestamp', 'natural', 'not', 'notnull', 'null', 'offset',
66     'on', 'only', 'or', 'order', 'outer', 'over', 'overlaps', 'placing',
67     'primary', 'references', 'returning', 'right', 'select', 'session_user',
68     'similar', 'some', 'symmetric', 'table', 'then', 'to', 'trailing', 'true',
69     'union', 'unique', 'user', 'using', 'variadic', 'verbose', 'when', 'where',
70     'window', 'with',
71   ];
72
73   /**
74    * Constructs a connection object.
75    */
76   public function __construct(\PDO $connection, array $connection_options) {
77     parent::__construct($connection, $connection_options);
78
79     // This driver defaults to transaction support, except if explicitly passed FALSE.
80     $this->transactionSupport = !isset($connection_options['transactions']) || ($connection_options['transactions'] !== FALSE);
81
82     // Transactional DDL is always available in PostgreSQL,
83     // but we'll only enable it if standard transactions are.
84     $this->transactionalDDLSupport = $this->transactionSupport;
85
86     $this->connectionOptions = $connection_options;
87
88     // Force PostgreSQL to use the UTF-8 character set by default.
89     $this->connection->exec("SET NAMES 'UTF8'");
90
91     // Execute PostgreSQL init_commands.
92     if (isset($connection_options['init_commands'])) {
93       $this->connection->exec(implode('; ', $connection_options['init_commands']));
94     }
95   }
96
97   /**
98    * {@inheritdoc}
99    */
100   public static function open(array &$connection_options = []) {
101     // Default to TCP connection on port 5432.
102     if (empty($connection_options['port'])) {
103       $connection_options['port'] = 5432;
104     }
105
106     // PostgreSQL in trust mode doesn't require a password to be supplied.
107     if (empty($connection_options['password'])) {
108       $connection_options['password'] = NULL;
109     }
110     // If the password contains a backslash it is treated as an escape character
111     // http://bugs.php.net/bug.php?id=53217
112     // so backslashes in the password need to be doubled up.
113     // The bug was reported against pdo_pgsql 1.0.2, backslashes in passwords
114     // will break on this doubling up when the bug is fixed, so check the version
115     // elseif (phpversion('pdo_pgsql') < 'version_this_was_fixed_in') {
116     else {
117       $connection_options['password'] = str_replace('\\', '\\\\', $connection_options['password']);
118     }
119
120     $connection_options['database'] = (!empty($connection_options['database']) ? $connection_options['database'] : 'template1');
121     $dsn = 'pgsql:host=' . $connection_options['host'] . ' dbname=' . $connection_options['database'] . ' port=' . $connection_options['port'];
122
123     // Allow PDO options to be overridden.
124     $connection_options += [
125       'pdo' => [],
126     ];
127     $connection_options['pdo'] += [
128       \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
129       // Prepared statements are most effective for performance when queries
130       // are recycled (used several times). However, if they are not re-used,
131       // prepared statements become inefficient. Since most of Drupal's
132       // prepared queries are not re-used, it should be faster to emulate
133       // the preparation than to actually ready statements for re-use. If in
134       // doubt, reset to FALSE and measure performance.
135       \PDO::ATTR_EMULATE_PREPARES => TRUE,
136       // Convert numeric values to strings when fetching.
137       \PDO::ATTR_STRINGIFY_FETCHES => TRUE,
138     ];
139
140     try {
141       $pdo = new \PDO($dsn, $connection_options['username'], $connection_options['password'], $connection_options['pdo']);
142     }
143     catch (\PDOException $e) {
144       if (static::getSQLState($e) == static::CONNECTION_FAILURE) {
145         if (strpos($e->getMessage(), 'password authentication failed for user') !== FALSE) {
146           throw new DatabaseAccessDeniedException($e->getMessage(), $e->getCode(), $e);
147         }
148         elseif (strpos($e->getMessage(), 'database') !== FALSE && strpos($e->getMessage(), 'does not exist') !== FALSE) {
149           throw new DatabaseNotFoundException($e->getMessage(), $e->getCode(), $e);
150         }
151       }
152       throw $e;
153     }
154
155     return $pdo;
156   }
157
158   /**
159    * {@inheritdoc}
160    */
161   public function query($query, array $args = [], $options = []) {
162     $options += $this->defaultOptions();
163
164     // The PDO PostgreSQL driver has a bug which doesn't type cast booleans
165     // correctly when parameters are bound using associative arrays.
166     // @see http://bugs.php.net/bug.php?id=48383
167     foreach ($args as &$value) {
168       if (is_bool($value)) {
169         $value = (int) $value;
170       }
171     }
172
173     // We need to wrap queries with a savepoint if:
174     // - Currently in a transaction.
175     // - A 'mimic_implicit_commit' does not exist already.
176     // - The query is not a savepoint query.
177     $wrap_with_savepoint = $this->inTransaction() &&
178       !isset($this->transactionLayers['mimic_implicit_commit']) &&
179       !(is_string($query) && (
180         stripos($query, 'ROLLBACK TO SAVEPOINT ') === 0 ||
181         stripos($query, 'RELEASE SAVEPOINT ') === 0 ||
182         stripos($query, 'SAVEPOINT ') === 0
183       )
184     );
185     if ($wrap_with_savepoint) {
186       // Create a savepoint so we can rollback a failed query. This is so we can
187       // mimic MySQL and SQLite transactions which don't fail if a single query
188       // fails. This is important for tables that are created on demand. For
189       // example, \Drupal\Core\Cache\DatabaseBackend.
190       $this->addSavepoint();
191       try {
192         $return = parent::query($query, $args, $options);
193         $this->releaseSavepoint();
194       }
195       catch (\Exception $e) {
196         $this->rollbackSavepoint();
197         throw $e;
198       }
199     }
200     else {
201       $return = parent::query($query, $args, $options);
202     }
203
204     return $return;
205   }
206
207   public function prepareQuery($query) {
208     // mapConditionOperator converts some operations (LIKE, REGEXP, etc.) to
209     // PostgreSQL equivalents (ILIKE, ~*, etc.). However PostgreSQL doesn't
210     // automatically cast the fields to the right type for these operators,
211     // so we need to alter the query and add the type-cast.
212     return parent::prepareQuery(preg_replace('/ ([^ ]+) +(I*LIKE|NOT +I*LIKE|~\*) /i', ' ${1}::text ${2} ', $query));
213   }
214
215   public function queryRange($query, $from, $count, array $args = [], array $options = []) {
216     return $this->query($query . ' LIMIT ' . (int) $count . ' OFFSET ' . (int) $from, $args, $options);
217   }
218
219   public function queryTemporary($query, array $args = [], array $options = []) {
220     $tablename = $this->generateTemporaryTableName();
221     $this->query('CREATE TEMPORARY TABLE {' . $tablename . '} AS ' . $query, $args, $options);
222     return $tablename;
223   }
224
225   /**
226    * {@inheritdoc}
227    */
228   public function escapeField($field) {
229     $escaped = parent::escapeField($field);
230
231     // Remove any invalid start character.
232     $escaped = preg_replace('/^[^A-Za-z0-9_]/', '', $escaped);
233
234     // The pgsql database driver does not support field names that contain
235     // periods (supported by PostgreSQL server) because this method may be
236     // called by a field with a table alias as part of SQL conditions or
237     // order by statements. This will consider a period as a table alias
238     // identifier, and split the string at the first period.
239     if (preg_match('/^([A-Za-z0-9_]+)"?[.]"?([A-Za-z0-9_.]+)/', $escaped, $parts)) {
240       $table = $parts[1];
241       $column = $parts[2];
242
243       // Use escape alias because escapeField may contain multiple periods that
244       // need to be escaped.
245       $escaped = $this->escapeTable($table) . '.' . $this->escapeAlias($column);
246     }
247     else {
248       $escaped = $this->doEscape($escaped);
249     }
250
251     return $escaped;
252   }
253
254   /**
255    * {@inheritdoc}
256    */
257   public function escapeAlias($field) {
258     $escaped = preg_replace('/[^A-Za-z0-9_]+/', '', $field);
259     $escaped = $this->doEscape($escaped);
260     return $escaped;
261   }
262
263   /**
264    * {@inheritdoc}
265    */
266   public function escapeTable($table) {
267     $escaped = parent::escapeTable($table);
268
269     // Ensure that each part (database, schema and table) of the table name is
270     // properly and independently escaped.
271     $parts = explode('.', $escaped);
272     $parts = array_map([$this, 'doEscape'], $parts);
273     $escaped = implode('.', $parts);
274
275     return $escaped;
276   }
277
278   /**
279    * Escape a string if needed.
280    *
281    * @param $string
282    *   The string to escape.
283    * @return string
284    *   The escaped string.
285    */
286   protected function doEscape($string) {
287     // Quote identifier to make it case-sensitive.
288     if (preg_match('/[A-Z]/', $string)) {
289       $string = '"' . $string . '"';
290     }
291     elseif (in_array(strtolower($string), $this->postgresqlReservedKeyWords)) {
292       // Quote the string for PostgreSQL reserved key words.
293       $string = '"' . $string . '"';
294     }
295     return $string;
296   }
297
298   public function driver() {
299     return 'pgsql';
300   }
301
302   public function databaseType() {
303     return 'pgsql';
304   }
305
306   /**
307    * Overrides \Drupal\Core\Database\Connection::createDatabase().
308    *
309    * @param string $database
310    *   The name of the database to create.
311    *
312    * @throws \Drupal\Core\Database\DatabaseNotFoundException
313    */
314   public function createDatabase($database) {
315     // Escape the database name.
316     $database = Database::getConnection()->escapeDatabase($database);
317
318     // If the PECL intl extension is installed, use it to determine the proper
319     // locale.  Otherwise, fall back to en_US.
320     if (class_exists('Locale')) {
321       $locale = \Locale::getDefault();
322     }
323     else {
324       $locale = 'en_US';
325     }
326
327     try {
328       // Create the database and set it as active.
329       $this->connection->exec("CREATE DATABASE $database WITH TEMPLATE template0 ENCODING='utf8' LC_CTYPE='$locale.utf8' LC_COLLATE='$locale.utf8'");
330     }
331     catch (\Exception $e) {
332       throw new DatabaseNotFoundException($e->getMessage());
333     }
334   }
335
336   public function mapConditionOperator($operator) {
337     return isset(static::$postgresqlConditionOperatorMap[$operator]) ? static::$postgresqlConditionOperatorMap[$operator] : NULL;
338   }
339
340   /**
341    * Retrieve a the next id in a sequence.
342    *
343    * PostgreSQL has built in sequences. We'll use these instead of inserting
344    * and updating a sequences table.
345    */
346   public function nextId($existing = 0) {
347
348     // Retrieve the name of the sequence. This information cannot be cached
349     // because the prefix may change, for example, like it does in simpletests.
350     $sequence_name = $this->makeSequenceName('sequences', 'value');
351
352     // When PostgreSQL gets a value too small then it will lock the table,
353     // retry the INSERT and if it's still too small then alter the sequence.
354     $id = $this->query("SELECT nextval('" . $sequence_name . "')")->fetchField();
355     if ($id > $existing) {
356       return $id;
357     }
358
359     // PostgreSQL advisory locks are simply locks to be used by an
360     // application such as Drupal. This will prevent other Drupal processes
361     // from altering the sequence while we are.
362     $this->query("SELECT pg_advisory_lock(" . self::POSTGRESQL_NEXTID_LOCK . ")");
363
364     // While waiting to obtain the lock, the sequence may have been altered
365     // so lets try again to obtain an adequate value.
366     $id = $this->query("SELECT nextval('" . $sequence_name . "')")->fetchField();
367     if ($id > $existing) {
368       $this->query("SELECT pg_advisory_unlock(" . self::POSTGRESQL_NEXTID_LOCK . ")");
369       return $id;
370     }
371
372     // Reset the sequence to a higher value than the existing id.
373     $this->query("ALTER SEQUENCE " . $sequence_name . " RESTART WITH " . ($existing + 1));
374
375     // Retrieve the next id. We know this will be as high as we want it.
376     $id = $this->query("SELECT nextval('" . $sequence_name . "')")->fetchField();
377
378     $this->query("SELECT pg_advisory_unlock(" . self::POSTGRESQL_NEXTID_LOCK . ")");
379
380     return $id;
381   }
382
383   /**
384    * {@inheritdoc}
385    */
386   public function getFullQualifiedTableName($table) {
387     $options = $this->getConnectionOptions();
388     $prefix = $this->tablePrefix($table);
389
390     // The fully qualified table name in PostgreSQL is in the form of
391     // <database>.<schema>.<table>, so we have to include the 'public' schema in
392     // the return value.
393     return $options['database'] . '.public.' . $prefix . $table;
394   }
395
396   /**
397    * Add a new savepoint with an unique name.
398    *
399    * The main use for this method is to mimic InnoDB functionality, which
400    * provides an inherent savepoint before any query in a transaction.
401    *
402    * @param $savepoint_name
403    *   A string representing the savepoint name. By default,
404    *   "mimic_implicit_commit" is used.
405    *
406    * @see Drupal\Core\Database\Connection::pushTransaction()
407    */
408   public function addSavepoint($savepoint_name = 'mimic_implicit_commit') {
409     if ($this->inTransaction()) {
410       $this->pushTransaction($savepoint_name);
411     }
412   }
413
414   /**
415    * Release a savepoint by name.
416    *
417    * @param $savepoint_name
418    *   A string representing the savepoint name. By default,
419    *   "mimic_implicit_commit" is used.
420    *
421    * @see Drupal\Core\Database\Connection::popTransaction()
422    */
423   public function releaseSavepoint($savepoint_name = 'mimic_implicit_commit') {
424     if (isset($this->transactionLayers[$savepoint_name])) {
425       $this->popTransaction($savepoint_name);
426     }
427   }
428
429   /**
430    * Rollback a savepoint by name if it exists.
431    *
432    * @param $savepoint_name
433    *   A string representing the savepoint name. By default,
434    *   "mimic_implicit_commit" is used.
435    */
436   public function rollbackSavepoint($savepoint_name = 'mimic_implicit_commit') {
437     if (isset($this->transactionLayers[$savepoint_name])) {
438       $this->rollBack($savepoint_name);
439     }
440   }
441
442   /**
443    * {@inheritdoc}
444    */
445   public function upsert($table, array $options = []) {
446     // Use the (faster) native Upsert implementation for PostgreSQL >= 9.5.
447     if (version_compare($this->version(), '9.5', '>=')) {
448       $class = $this->getDriverClass('NativeUpsert');
449     }
450     else {
451       $class = $this->getDriverClass('Upsert');
452     }
453
454     return new $class($this, $table, $options);
455   }
456
457 }
458
459 /**
460  * @} End of "addtogroup database".
461  */