3 namespace Drupal\Core\Database\Driver\pgsql;
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;
11 * @addtogroup database
16 * PostgreSQL implementation of \Drupal\Core\Database\Connection.
18 class Connection extends DatabaseConnection {
21 * The name by which to obtain a lock for retrieve the next insert id.
23 const POSTGRESQL_NEXTID_LOCK = 1000;
26 * Error code for "Unknown database" error.
28 const DATABASE_NOT_FOUND = 7;
31 * Error code for "Connection failure" errors.
33 * Technically this is an internal error code that will only be shown in the
34 * PDOException message. It will need to get extracted.
36 const CONNECTION_FAILURE = '08006';
39 * A map of condition operators to PostgreSQL operators.
41 * In PostgreSQL, 'LIKE' is case-sensitive. ILIKE should be used for
42 * case-insensitive statements.
44 protected static $postgresqlConditionOperatorMap = [
45 'LIKE' => ['operator' => 'ILIKE'],
46 'LIKE BINARY' => ['operator' => 'LIKE'],
47 'NOT LIKE' => ['operator' => 'NOT ILIKE'],
48 'REGEXP' => ['operator' => '~*'],
52 * The list of PostgreSQL reserved key words.
54 * @see http://www.postgresql.org/docs/9.4/static/sql-keywords-appendix.html
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',
74 * Constructs a connection object.
76 public function __construct(\PDO $connection, array $connection_options) {
77 parent::__construct($connection, $connection_options);
79 // This driver defaults to transaction support, except if explicitly passed FALSE.
80 $this->transactionSupport = !isset($connection_options['transactions']) || ($connection_options['transactions'] !== FALSE);
82 // Transactional DDL is always available in PostgreSQL,
83 // but we'll only enable it if standard transactions are.
84 $this->transactionalDDLSupport = $this->transactionSupport;
86 $this->connectionOptions = $connection_options;
88 // Force PostgreSQL to use the UTF-8 character set by default.
89 $this->connection->exec("SET NAMES 'UTF8'");
91 // Execute PostgreSQL init_commands.
92 if (isset($connection_options['init_commands'])) {
93 $this->connection->exec(implode('; ', $connection_options['init_commands']));
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;
106 // PostgreSQL in trust mode doesn't require a password to be supplied.
107 if (empty($connection_options['password'])) {
108 $connection_options['password'] = NULL;
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') {
117 $connection_options['password'] = str_replace('\\', '\\\\', $connection_options['password']);
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'];
123 // Allow PDO options to be overridden.
124 $connection_options += [
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,
141 $pdo = new \PDO($dsn, $connection_options['username'], $connection_options['password'], $connection_options['pdo']);
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);
148 elseif (strpos($e->getMessage(), 'database') !== FALSE && strpos($e->getMessage(), 'does not exist') !== FALSE) {
149 throw new DatabaseNotFoundException($e->getMessage(), $e->getCode(), $e);
161 public function query($query, array $args = [], $options = []) {
162 $options += $this->defaultOptions();
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;
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
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();
192 $return = parent::query($query, $args, $options);
193 $this->releaseSavepoint();
195 catch (\Exception $e) {
196 $this->rollbackSavepoint();
201 $return = parent::query($query, $args, $options);
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));
215 public function queryRange($query, $from, $count, array $args = [], array $options = []) {
216 return $this->query($query . ' LIMIT ' . (int) $count . ' OFFSET ' . (int) $from, $args, $options);
219 public function queryTemporary($query, array $args = [], array $options = []) {
220 $tablename = $this->generateTemporaryTableName();
221 $this->query('CREATE TEMPORARY TABLE {' . $tablename . '} AS ' . $query, $args, $options);
228 public function escapeField($field) {
229 $escaped = parent::escapeField($field);
231 // Remove any invalid start character.
232 $escaped = preg_replace('/^[^A-Za-z0-9_]/', '', $escaped);
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)) {
243 // Use escape alias because escapeField may contain multiple periods that
244 // need to be escaped.
245 $escaped = $this->escapeTable($table) . '.' . $this->escapeAlias($column);
248 $escaped = $this->doEscape($escaped);
257 public function escapeAlias($field) {
258 $escaped = preg_replace('/[^A-Za-z0-9_]+/', '', $field);
259 $escaped = $this->doEscape($escaped);
266 public function escapeTable($table) {
267 $escaped = parent::escapeTable($table);
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);
279 * Escape a string if needed.
282 * The string to escape.
284 * The escaped string.
286 protected function doEscape($string) {
287 // Quote identifier to make it case-sensitive.
288 if (preg_match('/[A-Z]/', $string)) {
289 $string = '"' . $string . '"';
291 elseif (in_array(strtolower($string), $this->postgresqlReservedKeyWords)) {
292 // Quote the string for PostgreSQL reserved key words.
293 $string = '"' . $string . '"';
298 public function driver() {
302 public function databaseType() {
307 * Overrides \Drupal\Core\Database\Connection::createDatabase().
309 * @param string $database
310 * The name of the database to create.
312 * @throws \Drupal\Core\Database\DatabaseNotFoundException
314 public function createDatabase($database) {
315 // Escape the database name.
316 $database = Database::getConnection()->escapeDatabase($database);
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();
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'");
331 catch (\Exception $e) {
332 throw new DatabaseNotFoundException($e->getMessage());
336 public function mapConditionOperator($operator) {
337 return isset(static::$postgresqlConditionOperatorMap[$operator]) ? static::$postgresqlConditionOperatorMap[$operator] : NULL;
341 * Retrieve a the next id in a sequence.
343 * PostgreSQL has built in sequences. We'll use these instead of inserting
344 * and updating a sequences table.
346 public function nextId($existing = 0) {
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');
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) {
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 . ")");
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 . ")");
372 // Reset the sequence to a higher value than the existing id.
373 $this->query("ALTER SEQUENCE " . $sequence_name . " RESTART WITH " . ($existing + 1));
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();
378 $this->query("SELECT pg_advisory_unlock(" . self::POSTGRESQL_NEXTID_LOCK . ")");
386 public function getFullQualifiedTableName($table) {
387 $options = $this->getConnectionOptions();
388 $prefix = $this->tablePrefix($table);
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
393 return $options['database'] . '.public.' . $prefix . $table;
397 * Add a new savepoint with an unique name.
399 * The main use for this method is to mimic InnoDB functionality, which
400 * provides an inherent savepoint before any query in a transaction.
402 * @param $savepoint_name
403 * A string representing the savepoint name. By default,
404 * "mimic_implicit_commit" is used.
406 * @see Drupal\Core\Database\Connection::pushTransaction()
408 public function addSavepoint($savepoint_name = 'mimic_implicit_commit') {
409 if ($this->inTransaction()) {
410 $this->pushTransaction($savepoint_name);
415 * Release a savepoint by name.
417 * @param $savepoint_name
418 * A string representing the savepoint name. By default,
419 * "mimic_implicit_commit" is used.
421 * @see Drupal\Core\Database\Connection::popTransaction()
423 public function releaseSavepoint($savepoint_name = 'mimic_implicit_commit') {
424 if (isset($this->transactionLayers[$savepoint_name])) {
425 $this->popTransaction($savepoint_name);
430 * Rollback a savepoint by name if it exists.
432 * @param $savepoint_name
433 * A string representing the savepoint name. By default,
434 * "mimic_implicit_commit" is used.
436 public function rollbackSavepoint($savepoint_name = 'mimic_implicit_commit') {
437 if (isset($this->transactionLayers[$savepoint_name])) {
438 $this->rollBack($savepoint_name);
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');
451 $class = $this->getDriverClass('Upsert');
454 return new $class($this, $table, $options);
460 * @} End of "addtogroup database".