96dea950f0342e6e765c7a51355b3ccd651f8507
[yaffs-website] / web / core / lib / Drupal / Core / Database / Driver / pgsql / Schema.php
1 <?php
2
3 namespace Drupal\Core\Database\Driver\pgsql;
4
5 use Drupal\Component\Utility\Unicode;
6 use Drupal\Core\Database\SchemaObjectExistsException;
7 use Drupal\Core\Database\SchemaObjectDoesNotExistException;
8 use Drupal\Core\Database\Schema as DatabaseSchema;
9
10 /**
11  * @addtogroup schemaapi
12  * @{
13  */
14
15 /**
16  * PostgreSQL implementation of \Drupal\Core\Database\Schema.
17  */
18 class Schema extends DatabaseSchema {
19
20   /**
21    * A cache of information about blob columns and sequences of tables.
22    *
23    * This is collected by Schema::queryTableInformation(), by introspecting the
24    * database.
25    *
26    * @see \Drupal\Core\Database\Driver\pgsql\Schema::queryTableInformation()
27    * @var array
28    */
29   protected $tableInformation = [];
30
31   /**
32    * The maximum allowed length for index, primary key and constraint names.
33    *
34    * Value will usually be set to a 63 chars limit but PostgreSQL allows
35    * to higher this value before compiling, so we need to check for that.
36    *
37    * @var int
38    */
39   protected $maxIdentifierLength;
40
41   /**
42    * PostgreSQL's temporary namespace name.
43    *
44    * @var string
45    */
46   protected $tempNamespaceName;
47
48   /**
49    * Make sure to limit identifiers according to PostgreSQL compiled in length.
50    *
51    * PostgreSQL allows in standard configuration no longer identifiers than 63
52    * chars for table/relation names, indexes, primary keys, and constraints. So
53    * we map all identifiers that are too long to drupal_base64hash_tag, where
54    * tag is one of:
55    *   - idx for indexes
56    *   - key for constraints
57    *   - pkey for primary keys
58    *
59    * @param $identifiers
60    *   The arguments to build the identifier string
61    * @return
62    *   The index/constraint/pkey identifier
63    */
64   protected function ensureIdentifiersLength($identifier) {
65     $args = func_get_args();
66     $info = $this->getPrefixInfo($identifier);
67     $args[0] = $info['table'];
68     $identifierName = implode('__', $args);
69
70     // Retrieve the max identifier length which is usually 63 characters
71     // but can be altered before PostgreSQL is compiled so we need to check.
72     $this->maxIdentifierLength = $this->connection->query("SHOW max_identifier_length")->fetchField();
73
74     if (strlen($identifierName) > $this->maxIdentifierLength) {
75       $saveIdentifier = '"drupal_' . $this->hashBase64($identifierName) . '_' . $args[2] . '"';
76     }
77     else {
78       $saveIdentifier = $identifierName;
79     }
80     return $saveIdentifier;
81   }
82
83   /**
84    * Fetch the list of blobs and sequences used on a table.
85    *
86    * We introspect the database to collect the information required by insert
87    * and update queries.
88    *
89    * @param $table_name
90    *   The non-prefixed name of the table.
91    * @return
92    *   An object with two member variables:
93    *     - 'blob_fields' that lists all the blob fields in the table.
94    *     - 'sequences' that lists the sequences used in that table.
95    */
96   public function queryTableInformation($table) {
97     // Generate a key to reference this table's information on.
98     $key = $this->connection->prefixTables('{' . $table . '}');
99
100     // Take into account that temporary tables are stored in a different schema.
101     // \Drupal\Core\Database\Connection::generateTemporaryTableName() sets the
102     // 'db_temporary_' prefix to all temporary tables.
103     if (strpos($key, '.') === FALSE && strpos($table, 'db_temporary_') === FALSE) {
104       $key = 'public.' . $key;
105     }
106     else {
107       $key = $this->getTempNamespaceName() . '.' . $key;
108     }
109
110     if (!isset($this->tableInformation[$key])) {
111       $table_information = (object) [
112         'blob_fields' => [],
113         'sequences' => [],
114       ];
115       $this->connection->addSavepoint();
116
117       try {
118         // The bytea columns and sequences for a table can be found in
119         // pg_attribute, which is significantly faster than querying the
120         // information_schema. The data type of a field can be found by lookup
121         // of the attribute ID, and the default value must be extracted from the
122         // node tree for the attribute definition instead of the historical
123         // human-readable column, adsrc.
124         $sql = <<<'EOD'
125 SELECT pg_attribute.attname AS column_name, format_type(pg_attribute.atttypid, pg_attribute.atttypmod) AS data_type, pg_get_expr(pg_attrdef.adbin, pg_attribute.attrelid) AS column_default
126 FROM pg_attribute
127 LEFT JOIN pg_attrdef ON pg_attrdef.adrelid = pg_attribute.attrelid AND pg_attrdef.adnum = pg_attribute.attnum
128 WHERE pg_attribute.attnum > 0
129 AND NOT pg_attribute.attisdropped
130 AND pg_attribute.attrelid = :key::regclass
131 AND (format_type(pg_attribute.atttypid, pg_attribute.atttypmod) = 'bytea'
132 OR pg_attrdef.adsrc LIKE 'nextval%')
133 EOD;
134         $result = $this->connection->query($sql, [
135           ':key' => $key,
136         ]);
137       }
138       catch (\Exception $e) {
139         $this->connection->rollbackSavepoint();
140         throw $e;
141       }
142       $this->connection->releaseSavepoint();
143
144       // If the table information does not yet exist in the PostgreSQL
145       // metadata, then return the default table information here, so that it
146       // will not be cached.
147       if (empty($result)) {
148         return $table_information;
149       }
150
151       foreach ($result as $column) {
152         if ($column->data_type == 'bytea') {
153           $table_information->blob_fields[$column->column_name] = TRUE;
154         }
155         elseif (preg_match("/nextval\('([^']+)'/", $column->column_default, $matches)) {
156           // We must know of any sequences in the table structure to help us
157           // return the last insert id. If there is more than 1 sequences the
158           // first one (index 0 of the sequences array) will be used.
159           $table_information->sequences[] = $matches[1];
160           $table_information->serial_fields[] = $column->column_name;
161         }
162       }
163       $this->tableInformation[$key] = $table_information;
164     }
165     return $this->tableInformation[$key];
166   }
167
168   /**
169    * Gets PostgreSQL's temporary namespace name.
170    *
171    * @return string
172    *   PostgreSQL's temporary namespace name.
173    */
174   protected function getTempNamespaceName() {
175     if (!isset($this->tempNamespaceName)) {
176       $this->tempNamespaceName = $this->connection->query('SELECT nspname FROM pg_namespace WHERE oid = pg_my_temp_schema()')->fetchField();
177     }
178     return $this->tempNamespaceName;
179   }
180
181   /**
182    * Resets information about table blobs, sequences and serial fields.
183    *
184    * @param $table
185    *   The non-prefixed name of the table.
186    */
187   protected function resetTableInformation($table) {
188     $key = $this->connection->prefixTables('{' . $table . '}');
189     if (strpos($key, '.') === FALSE) {
190       $key = 'public.' . $key;
191     }
192     unset($this->tableInformation[$key]);
193   }
194
195   /**
196    * Fetch the list of CHECK constraints used on a field.
197    *
198    * We introspect the database to collect the information required by field
199    * alteration.
200    *
201    * @param $table
202    *   The non-prefixed name of the table.
203    * @param $field
204    *   The name of the field.
205    * @return
206    *   An array of all the checks for the field.
207    */
208   public function queryFieldInformation($table, $field) {
209     $prefixInfo = $this->getPrefixInfo($table, TRUE);
210
211     // Split the key into schema and table for querying.
212     $schema = $prefixInfo['schema'];
213     $table_name = $prefixInfo['table'];
214
215     $this->connection->addSavepoint();
216
217     try {
218       $checks = $this->connection->query("SELECT conname FROM pg_class cl INNER JOIN pg_constraint co ON co.conrelid = cl.oid INNER JOIN pg_attribute attr ON attr.attrelid = cl.oid AND attr.attnum = ANY (co.conkey) INNER JOIN pg_namespace ns ON cl.relnamespace = ns.oid WHERE co.contype = 'c' AND ns.nspname = :schema AND cl.relname = :table AND attr.attname = :column", [
219         ':schema' => $schema,
220         ':table' => $table_name,
221         ':column' => $field,
222       ]);
223     }
224     catch (\Exception $e) {
225       $this->connection->rollbackSavepoint();
226       throw $e;
227     }
228
229     $this->connection->releaseSavepoint();
230
231     $field_information = $checks->fetchCol();
232
233     return $field_information;
234   }
235
236   /**
237    * Generate SQL to create a new table from a Drupal schema definition.
238    *
239    * @param $name
240    *   The name of the table to create.
241    * @param $table
242    *   A Schema API table definition array.
243    * @return
244    *   An array of SQL statements to create the table.
245    */
246   protected function createTableSql($name, $table) {
247     $sql_fields = [];
248     foreach ($table['fields'] as $field_name => $field) {
249       $sql_fields[] = $this->createFieldSql($field_name, $this->processField($field));
250     }
251
252     $sql_keys = [];
253     if (isset($table['primary key']) && is_array($table['primary key'])) {
254       $sql_keys[] = 'CONSTRAINT ' . $this->ensureIdentifiersLength($name, '', 'pkey') . ' PRIMARY KEY (' . $this->createPrimaryKeySql($table['primary key']) . ')';
255     }
256     if (isset($table['unique keys']) && is_array($table['unique keys'])) {
257       foreach ($table['unique keys'] as $key_name => $key) {
258         $sql_keys[] = 'CONSTRAINT ' . $this->ensureIdentifiersLength($name, $key_name, 'key') . ' UNIQUE (' . implode(', ', $key) . ')';
259       }
260     }
261
262     $sql = "CREATE TABLE {" . $name . "} (\n\t";
263     $sql .= implode(",\n\t", $sql_fields);
264     if (count($sql_keys) > 0) {
265       $sql .= ",\n\t";
266     }
267     $sql .= implode(",\n\t", $sql_keys);
268     $sql .= "\n)";
269     $statements[] = $sql;
270
271     if (isset($table['indexes']) && is_array($table['indexes'])) {
272       foreach ($table['indexes'] as $key_name => $key) {
273         $statements[] = $this->_createIndexSql($name, $key_name, $key);
274       }
275     }
276
277     // Add table comment.
278     if (!empty($table['description'])) {
279       $statements[] = 'COMMENT ON TABLE {' . $name . '} IS ' . $this->prepareComment($table['description']);
280     }
281
282     // Add column comments.
283     foreach ($table['fields'] as $field_name => $field) {
284       if (!empty($field['description'])) {
285         $statements[] = 'COMMENT ON COLUMN {' . $name . '}.' . $field_name . ' IS ' . $this->prepareComment($field['description']);
286       }
287     }
288
289     return $statements;
290   }
291
292   /**
293    * Create an SQL string for a field to be used in table creation or
294    * alteration.
295    *
296    * Before passing a field out of a schema definition into this
297    * function it has to be processed by _db_process_field().
298    *
299    * @param $name
300    *   Name of the field.
301    * @param $spec
302    *   The field specification, as per the schema data structure format.
303    */
304   protected function createFieldSql($name, $spec) {
305     // The PostgreSQL server converts names into lowercase, unless quoted.
306     $sql = '"' . $name . '" ' . $spec['pgsql_type'];
307
308     if (isset($spec['type']) && $spec['type'] == 'serial') {
309       unset($spec['not null']);
310     }
311
312     if (in_array($spec['pgsql_type'], ['varchar', 'character']) && isset($spec['length'])) {
313       $sql .= '(' . $spec['length'] . ')';
314     }
315     elseif (isset($spec['precision']) && isset($spec['scale'])) {
316       $sql .= '(' . $spec['precision'] . ', ' . $spec['scale'] . ')';
317     }
318
319     if (!empty($spec['unsigned'])) {
320       $sql .= " CHECK ($name >= 0)";
321     }
322
323     if (isset($spec['not null'])) {
324       if ($spec['not null']) {
325         $sql .= ' NOT NULL';
326       }
327       else {
328         $sql .= ' NULL';
329       }
330     }
331     if (array_key_exists('default', $spec)) {
332       $default = $this->escapeDefaultValue($spec['default']);
333       $sql .= " default $default";
334     }
335
336     return $sql;
337   }
338
339   /**
340    * Set database-engine specific properties for a field.
341    *
342    * @param $field
343    *   A field description array, as specified in the schema documentation.
344    */
345   protected function processField($field) {
346     if (!isset($field['size'])) {
347       $field['size'] = 'normal';
348     }
349
350     // Set the correct database-engine specific datatype.
351     // In case one is already provided, force it to lowercase.
352     if (isset($field['pgsql_type'])) {
353       $field['pgsql_type'] = Unicode::strtolower($field['pgsql_type']);
354     }
355     else {
356       $map = $this->getFieldTypeMap();
357       $field['pgsql_type'] = $map[$field['type'] . ':' . $field['size']];
358     }
359
360     if (!empty($field['unsigned'])) {
361       // Unsigned datatypes are not supported in PostgreSQL 9.1. In MySQL,
362       // they are used to ensure a positive number is inserted and it also
363       // doubles the maximum integer size that can be stored in a field.
364       // The PostgreSQL schema in Drupal creates a check constraint
365       // to ensure that a value inserted is >= 0. To provide the extra
366       // integer capacity, here, we bump up the column field size.
367       if (!isset($map)) {
368         $map = $this->getFieldTypeMap();
369       }
370       switch ($field['pgsql_type']) {
371         case 'smallint':
372           $field['pgsql_type'] = $map['int:medium'];
373           break;
374         case 'int' :
375           $field['pgsql_type'] = $map['int:big'];
376           break;
377       }
378     }
379     if (isset($field['type']) && $field['type'] == 'serial') {
380       unset($field['not null']);
381     }
382     return $field;
383   }
384
385   /**
386    * {@inheritdoc}
387    */
388   public function getFieldTypeMap() {
389     // Put :normal last so it gets preserved by array_flip. This makes
390     // it much easier for modules (such as schema.module) to map
391     // database types back into schema types.
392     // $map does not use drupal_static as its value never changes.
393     static $map = [
394       'varchar_ascii:normal' => 'varchar',
395
396       'varchar:normal' => 'varchar',
397       'char:normal' => 'character',
398
399       'text:tiny' => 'text',
400       'text:small' => 'text',
401       'text:medium' => 'text',
402       'text:big' => 'text',
403       'text:normal' => 'text',
404
405       'int:tiny' => 'smallint',
406       'int:small' => 'smallint',
407       'int:medium' => 'int',
408       'int:big' => 'bigint',
409       'int:normal' => 'int',
410
411       'float:tiny' => 'real',
412       'float:small' => 'real',
413       'float:medium' => 'real',
414       'float:big' => 'double precision',
415       'float:normal' => 'real',
416
417       'numeric:normal' => 'numeric',
418
419       'blob:big' => 'bytea',
420       'blob:normal' => 'bytea',
421
422       'serial:tiny' => 'serial',
423       'serial:small' => 'serial',
424       'serial:medium' => 'serial',
425       'serial:big' => 'bigserial',
426       'serial:normal' => 'serial',
427       ];
428     return $map;
429   }
430
431   protected function _createKeySql($fields) {
432     $return = [];
433     foreach ($fields as $field) {
434       if (is_array($field)) {
435         $return[] = 'substr(' . $field[0] . ', 1, ' . $field[1] . ')';
436       }
437       else {
438         $return[] = '"' . $field . '"';
439       }
440     }
441     return implode(', ', $return);
442   }
443
444   /**
445    * Create the SQL expression for primary keys.
446    *
447    * Postgresql does not support key length. It does support fillfactor, but
448    * that requires a separate database lookup for each column in the key. The
449    * key length defined in the schema is ignored.
450    */
451   protected function createPrimaryKeySql($fields) {
452     $return = [];
453     foreach ($fields as $field) {
454       if (is_array($field)) {
455         $return[] = '"' . $field[0] . '"';
456       }
457       else {
458         $return[] = '"' . $field . '"';
459       }
460     }
461     return implode(', ', $return);
462   }
463
464   /**
465    * {@inheritdoc}
466    */
467   public function tableExists($table) {
468     $prefixInfo = $this->getPrefixInfo($table, TRUE);
469
470     return (bool) $this->connection->query("SELECT 1 FROM pg_tables WHERE schemaname = :schema AND tablename = :table", [':schema' => $prefixInfo['schema'], ':table' => $prefixInfo['table']])->fetchField();
471   }
472
473   /**
474    * {@inheritdoc}
475    */
476   public function renameTable($table, $new_name) {
477     if (!$this->tableExists($table)) {
478       throw new SchemaObjectDoesNotExistException(t("Cannot rename @table to @table_new: table @table doesn't exist.", ['@table' => $table, '@table_new' => $new_name]));
479     }
480     if ($this->tableExists($new_name)) {
481       throw new SchemaObjectExistsException(t("Cannot rename @table to @table_new: table @table_new already exists.", ['@table' => $table, '@table_new' => $new_name]));
482     }
483
484     // Get the schema and tablename for the old table.
485     $old_full_name = $this->connection->prefixTables('{' . $table . '}');
486     list($old_schema, $old_table_name) = strpos($old_full_name, '.') ? explode('.', $old_full_name) : ['public', $old_full_name];
487
488     // Index names and constraint names are global in PostgreSQL, so we need to
489     // rename them when renaming the table.
490     $indexes = $this->connection->query('SELECT indexname FROM pg_indexes WHERE schemaname = :schema AND tablename = :table', [':schema' => $old_schema, ':table' => $old_table_name]);
491
492     foreach ($indexes as $index) {
493       // Get the index type by suffix, e.g. idx/key/pkey
494       $index_type = substr($index->indexname, strrpos($index->indexname, '_') + 1);
495
496       // If the index is already rewritten by ensureIdentifiersLength() to not
497       // exceed the 63 chars limit of PostgreSQL, we need to take care of that.
498       // Example (drupal_Gk7Su_T1jcBHVuvSPeP22_I3Ni4GrVEgTYlIYnBJkro_idx).
499       if (strpos($index->indexname, 'drupal_') !== FALSE) {
500         preg_match('/^drupal_(.*)_' . preg_quote($index_type) . '/', $index->indexname, $matches);
501         $index_name = $matches[1];
502       }
503       else {
504         // Make sure to remove the suffix from index names, because
505         // $this->ensureIdentifiersLength() will add the suffix again and thus
506         // would result in a wrong index name.
507         preg_match('/^' . preg_quote($old_full_name) . '__(.*)__' . preg_quote($index_type) . '/', $index->indexname, $matches);
508         $index_name = $matches[1];
509       }
510       $this->connection->query('ALTER INDEX "' . $index->indexname . '" RENAME TO ' . $this->ensureIdentifiersLength($new_name, $index_name, $index_type) . '');
511     }
512
513     // Ensure the new table name does not include schema syntax.
514     $prefixInfo = $this->getPrefixInfo($new_name);
515
516     // Rename sequences if there's a serial fields.
517     $info = $this->queryTableInformation($table);
518     if (!empty($info->serial_fields)) {
519       foreach ($info->serial_fields as $field) {
520         $old_sequence = $this->prefixNonTable($table, $field, 'seq');
521         $new_sequence = $this->prefixNonTable($new_name, $field, 'seq');
522         $this->connection->query('ALTER SEQUENCE ' . $old_sequence . ' RENAME TO ' . $new_sequence);
523       }
524     }
525     // Now rename the table.
526     $this->connection->query('ALTER TABLE {' . $table . '} RENAME TO ' . $prefixInfo['table']);
527     $this->resetTableInformation($table);
528   }
529
530   /**
531    * {@inheritdoc}
532    */
533   public function dropTable($table) {
534     if (!$this->tableExists($table)) {
535       return FALSE;
536     }
537
538     $this->connection->query('DROP TABLE {' . $table . '}');
539     $this->resetTableInformation($table);
540     return TRUE;
541   }
542
543   /**
544    * {@inheritdoc}
545    */
546   public function addField($table, $field, $spec, $new_keys = []) {
547     if (!$this->tableExists($table)) {
548       throw new SchemaObjectDoesNotExistException(t("Cannot add field @table.@field: table doesn't exist.", ['@field' => $field, '@table' => $table]));
549     }
550     if ($this->fieldExists($table, $field)) {
551       throw new SchemaObjectExistsException(t("Cannot add field @table.@field: field already exists.", ['@field' => $field, '@table' => $table]));
552     }
553
554     // Fields that are part of a PRIMARY KEY must be added as NOT NULL.
555     $is_primary_key = isset($keys_new['primary key']) && in_array($field, $keys_new['primary key'], TRUE);
556
557     $fixnull = FALSE;
558     if (!empty($spec['not null']) && !isset($spec['default']) && !$is_primary_key) {
559       $fixnull = TRUE;
560       $spec['not null'] = FALSE;
561     }
562     $query = 'ALTER TABLE {' . $table . '} ADD COLUMN ';
563     $query .= $this->createFieldSql($field, $this->processField($spec));
564     $this->connection->query($query);
565     if (isset($spec['initial'])) {
566       $this->connection->update($table)
567         ->fields([$field => $spec['initial']])
568         ->execute();
569     }
570     if (isset($spec['initial_from_field'])) {
571       $this->connection->update($table)
572         ->expression($field, $spec['initial_from_field'])
573         ->execute();
574     }
575     if ($fixnull) {
576       $this->connection->query("ALTER TABLE {" . $table . "} ALTER $field SET NOT NULL");
577     }
578     if (isset($new_keys)) {
579       // Make sure to drop the existing primary key before adding a new one.
580       // This is only needed when adding a field because this method, unlike
581       // changeField(), is supposed to handle primary keys automatically.
582       if (isset($new_keys['primary key']) && $this->constraintExists($table, 'pkey')) {
583         $this->dropPrimaryKey($table);
584       }
585       $this->_createKeys($table, $new_keys);
586     }
587     // Add column comment.
588     if (!empty($spec['description'])) {
589       $this->connection->query('COMMENT ON COLUMN {' . $table . '}.' . $field . ' IS ' . $this->prepareComment($spec['description']));
590     }
591     $this->resetTableInformation($table);
592   }
593
594   /**
595    * {@inheritdoc}
596    */
597   public function dropField($table, $field) {
598     if (!$this->fieldExists($table, $field)) {
599       return FALSE;
600     }
601
602     $this->connection->query('ALTER TABLE {' . $table . '} DROP COLUMN "' . $field . '"');
603     $this->resetTableInformation($table);
604     return TRUE;
605   }
606
607   /**
608    * {@inheritdoc}
609    */
610   public function fieldSetDefault($table, $field, $default) {
611     if (!$this->fieldExists($table, $field)) {
612       throw new SchemaObjectDoesNotExistException(t("Cannot set default value of field @table.@field: field doesn't exist.", ['@table' => $table, '@field' => $field]));
613     }
614
615     $default = $this->escapeDefaultValue($default);
616
617     $this->connection->query('ALTER TABLE {' . $table . '} ALTER COLUMN "' . $field . '" SET DEFAULT ' . $default);
618   }
619
620   /**
621    * {@inheritdoc}
622    */
623   public function fieldSetNoDefault($table, $field) {
624     if (!$this->fieldExists($table, $field)) {
625       throw new SchemaObjectDoesNotExistException(t("Cannot remove default value of field @table.@field: field doesn't exist.", ['@table' => $table, '@field' => $field]));
626     }
627
628     $this->connection->query('ALTER TABLE {' . $table . '} ALTER COLUMN "' . $field . '" DROP DEFAULT');
629   }
630
631   /**
632    * {@inheritdoc}
633    */
634   public function fieldExists($table, $column) {
635     $prefixInfo = $this->getPrefixInfo($table);
636
637     return (bool) $this->connection->query("SELECT 1 FROM pg_attribute WHERE attrelid = :key::regclass AND attname = :column AND NOT attisdropped AND attnum > 0", [':key' => $prefixInfo['schema'] . '.' . $prefixInfo['table'], ':column' => $column])->fetchField();
638   }
639
640   /**
641    * {@inheritdoc}
642    */
643   public function indexExists($table, $name) {
644     // Details http://www.postgresql.org/docs/9.1/interactive/view-pg-indexes.html
645     $index_name = $this->ensureIdentifiersLength($table, $name, 'idx');
646     // Remove leading and trailing quotes because the index name is in a WHERE
647     // clause and not used as an identifier.
648     $index_name = str_replace('"', '', $index_name);
649     return (bool) $this->connection->query("SELECT 1 FROM pg_indexes WHERE indexname = '$index_name'")->fetchField();
650   }
651
652   /**
653    * Helper function: check if a constraint (PK, FK, UK) exists.
654    *
655    * @param string $table
656    *   The name of the table.
657    * @param string $name
658    *   The name of the constraint (typically 'pkey' or '[constraint]__key').
659    *
660    * @return bool
661    *   TRUE if the constraint exists, FALSE otherwise.
662    */
663   public function constraintExists($table, $name) {
664     // ::ensureIdentifiersLength() expects three parameters, although not
665     // explicitly stated in its signature, thus we split our constraint name in
666     // a proper name and a suffix.
667     if ($name == 'pkey') {
668       $suffix = $name;
669       $name = '';
670     }
671     else {
672       $pos = strrpos($name, '__');
673       $suffix = substr($name, $pos + 2);
674       $name = substr($name, 0, $pos);
675     }
676     $constraint_name = $this->ensureIdentifiersLength($table, $name, $suffix);
677     // Remove leading and trailing quotes because the index name is in a WHERE
678     // clause and not used as an identifier.
679     $constraint_name = str_replace('"', '', $constraint_name);
680     return (bool) $this->connection->query("SELECT 1 FROM pg_constraint WHERE conname = '$constraint_name'")->fetchField();
681   }
682
683   /**
684    * {@inheritdoc}
685    */
686   public function addPrimaryKey($table, $fields) {
687     if (!$this->tableExists($table)) {
688       throw new SchemaObjectDoesNotExistException(t("Cannot add primary key to table @table: table doesn't exist.", ['@table' => $table]));
689     }
690     if ($this->constraintExists($table, 'pkey')) {
691       throw new SchemaObjectExistsException(t("Cannot add primary key to table @table: primary key already exists.", ['@table' => $table]));
692     }
693
694     $this->connection->query('ALTER TABLE {' . $table . '} ADD CONSTRAINT ' . $this->ensureIdentifiersLength($table, '', 'pkey') . ' PRIMARY KEY (' . $this->createPrimaryKeySql($fields) . ')');
695     $this->resetTableInformation($table);
696   }
697
698   /**
699    * {@inheritdoc}
700    */
701   public function dropPrimaryKey($table) {
702     if (!$this->constraintExists($table, 'pkey')) {
703       return FALSE;
704     }
705
706     $this->connection->query('ALTER TABLE {' . $table . '} DROP CONSTRAINT ' . $this->ensureIdentifiersLength($table, '', 'pkey'));
707     $this->resetTableInformation($table);
708     return TRUE;
709   }
710
711   /**
712    * {@inheritdoc}
713    */
714   public function addUniqueKey($table, $name, $fields) {
715     if (!$this->tableExists($table)) {
716       throw new SchemaObjectDoesNotExistException(t("Cannot add unique key @name to table @table: table doesn't exist.", ['@table' => $table, '@name' => $name]));
717     }
718     if ($this->constraintExists($table, $name . '__key')) {
719       throw new SchemaObjectExistsException(t("Cannot add unique key @name to table @table: unique key already exists.", ['@table' => $table, '@name' => $name]));
720     }
721
722     $this->connection->query('ALTER TABLE {' . $table . '} ADD CONSTRAINT ' . $this->ensureIdentifiersLength($table, $name, 'key') . ' UNIQUE (' . implode(',', $fields) . ')');
723     $this->resetTableInformation($table);
724   }
725
726   /**
727    * {@inheritdoc}
728    */
729   public function dropUniqueKey($table, $name) {
730     if (!$this->constraintExists($table, $name . '__key')) {
731       return FALSE;
732     }
733
734     $this->connection->query('ALTER TABLE {' . $table . '} DROP CONSTRAINT ' . $this->ensureIdentifiersLength($table, $name, 'key'));
735     $this->resetTableInformation($table);
736     return TRUE;
737   }
738
739   /**
740    * {@inheritdoc}
741    */
742   public function addIndex($table, $name, $fields, array $spec) {
743     if (!$this->tableExists($table)) {
744       throw new SchemaObjectDoesNotExistException(t("Cannot add index @name to table @table: table doesn't exist.", ['@table' => $table, '@name' => $name]));
745     }
746     if ($this->indexExists($table, $name)) {
747       throw new SchemaObjectExistsException(t("Cannot add index @name to table @table: index already exists.", ['@table' => $table, '@name' => $name]));
748     }
749
750     $this->connection->query($this->_createIndexSql($table, $name, $fields));
751     $this->resetTableInformation($table);
752   }
753
754   /**
755    * {@inheritdoc}
756    */
757   public function dropIndex($table, $name) {
758     if (!$this->indexExists($table, $name)) {
759       return FALSE;
760     }
761
762     $this->connection->query('DROP INDEX ' . $this->ensureIdentifiersLength($table, $name, 'idx'));
763     $this->resetTableInformation($table);
764     return TRUE;
765   }
766
767   /**
768    * {@inheritdoc}
769    */
770   public function changeField($table, $field, $field_new, $spec, $new_keys = []) {
771     if (!$this->fieldExists($table, $field)) {
772       throw new SchemaObjectDoesNotExistException(t("Cannot change the definition of field @table.@name: field doesn't exist.", ['@table' => $table, '@name' => $field]));
773     }
774     if (($field != $field_new) && $this->fieldExists($table, $field_new)) {
775       throw new SchemaObjectExistsException(t("Cannot rename field @table.@name to @name_new: target field already exists.", ['@table' => $table, '@name' => $field, '@name_new' => $field_new]));
776     }
777
778     $spec = $this->processField($spec);
779
780     // Type 'serial' is known to PostgreSQL, but only during table creation,
781     // not when altering. Because of that, we create it here as an 'int'. After
782     // we create it we manually re-apply the sequence.
783     if (in_array($spec['pgsql_type'], ['serial', 'bigserial'])) {
784       $field_def = 'int';
785     }
786     else {
787       $field_def = $spec['pgsql_type'];
788     }
789
790     if (in_array($spec['pgsql_type'], ['varchar', 'character', 'text']) && isset($spec['length'])) {
791       $field_def .= '(' . $spec['length'] . ')';
792     }
793     elseif (isset($spec['precision']) && isset($spec['scale'])) {
794       $field_def .= '(' . $spec['precision'] . ', ' . $spec['scale'] . ')';
795     }
796
797     // Remove old check constraints.
798     $field_info = $this->queryFieldInformation($table, $field);
799
800     foreach ($field_info as $check) {
801       $this->connection->query('ALTER TABLE {' . $table . '} DROP CONSTRAINT "' . $check . '"');
802     }
803
804     // Remove old default.
805     $this->fieldSetNoDefault($table, $field);
806
807     // Convert field type.
808     // Usually, we do this via a simple typecast 'USING fieldname::type'. But
809     // the typecast does not work for conversions to bytea.
810     // @see http://www.postgresql.org/docs/current/static/datatype-binary.html
811     $table_information = $this->queryTableInformation($table);
812     $is_bytea = !empty($table_information->blob_fields[$field]);
813     if ($spec['pgsql_type'] != 'bytea') {
814       if ($is_bytea) {
815         $this->connection->query('ALTER TABLE {' . $table . '} ALTER "' . $field . '" TYPE ' . $field_def . ' USING convert_from("' . $field . '"' . ", 'UTF8')");
816       }
817       else {
818         $this->connection->query('ALTER TABLE {' . $table . '} ALTER "' . $field . '" TYPE ' . $field_def . ' USING "' . $field . '"::' . $field_def);
819       }
820     }
821     else {
822       // Do not attempt to convert a field that is bytea already.
823       if (!$is_bytea) {
824         // Convert to a bytea type by using the SQL replace() function to
825         // convert any single backslashes in the field content to double
826         // backslashes ('\' to '\\').
827         $this->connection->query('ALTER TABLE {' . $table . '} ALTER "' . $field . '" TYPE ' . $field_def . ' USING decode(replace("' . $field . '"' . ", E'\\\\', E'\\\\\\\\'), 'escape');");
828       }
829     }
830
831     if (isset($spec['not null'])) {
832       if ($spec['not null']) {
833         $nullaction = 'SET NOT NULL';
834       }
835       else {
836         $nullaction = 'DROP NOT NULL';
837       }
838       $this->connection->query('ALTER TABLE {' . $table . '} ALTER "' . $field . '" ' . $nullaction);
839     }
840
841     if (in_array($spec['pgsql_type'], ['serial', 'bigserial'])) {
842       // Type "serial" is known to PostgreSQL, but *only* during table creation,
843       // not when altering. Because of that, the sequence needs to be created
844       // and initialized by hand.
845       $seq = "{" . $table . "}_" . $field_new . "_seq";
846       $this->connection->query("CREATE SEQUENCE " . $seq);
847       // Set sequence to maximal field value to not conflict with existing
848       // entries.
849       $this->connection->query("SELECT setval('" . $seq . "', MAX(\"" . $field . '")) FROM {' . $table . "}");
850       $this->connection->query('ALTER TABLE {' . $table . '} ALTER ' . $field . ' SET DEFAULT nextval(' . $this->connection->quote($seq) . ')');
851     }
852
853     // Rename the column if necessary.
854     if ($field != $field_new) {
855       $this->connection->query('ALTER TABLE {' . $table . '} RENAME "' . $field . '" TO "' . $field_new . '"');
856     }
857
858     // Add unsigned check if necessary.
859     if (!empty($spec['unsigned'])) {
860       $this->connection->query('ALTER TABLE {' . $table . '} ADD CHECK ("' . $field_new . '" >= 0)');
861     }
862
863     // Add default if necessary.
864     if (isset($spec['default'])) {
865       $this->fieldSetDefault($table, $field_new, $spec['default']);
866     }
867
868     // Change description if necessary.
869     if (!empty($spec['description'])) {
870       $this->connection->query('COMMENT ON COLUMN {' . $table . '}."' . $field_new . '" IS ' . $this->prepareComment($spec['description']));
871     }
872
873     if (isset($new_keys)) {
874       $this->_createKeys($table, $new_keys);
875     }
876     $this->resetTableInformation($table);
877   }
878
879   protected function _createIndexSql($table, $name, $fields) {
880     $query = 'CREATE INDEX ' . $this->ensureIdentifiersLength($table, $name, 'idx') . ' ON {' . $table . '} (';
881     $query .= $this->_createKeySql($fields) . ')';
882     return $query;
883   }
884
885   protected function _createKeys($table, $new_keys) {
886     if (isset($new_keys['primary key'])) {
887       $this->addPrimaryKey($table, $new_keys['primary key']);
888     }
889     if (isset($new_keys['unique keys'])) {
890       foreach ($new_keys['unique keys'] as $name => $fields) {
891         $this->addUniqueKey($table, $name, $fields);
892       }
893     }
894     if (isset($new_keys['indexes'])) {
895       foreach ($new_keys['indexes'] as $name => $fields) {
896         // Even though $new_keys is not a full schema it still has 'indexes' and
897         // so is a partial schema. Technically addIndex() doesn't do anything
898         // with it so passing an empty array would work as well.
899         $this->addIndex($table, $name, $fields, $new_keys);
900       }
901     }
902   }
903
904   /**
905    * Retrieve a table or column comment.
906    */
907   public function getComment($table, $column = NULL) {
908     $info = $this->getPrefixInfo($table);
909     // Don't use {} around pg_class, pg_attribute tables.
910     if (isset($column)) {
911       return $this->connection->query('SELECT col_description(oid, attnum) FROM pg_class, pg_attribute WHERE attrelid = oid AND relname = ? AND attname = ?', [$info['table'], $column])->fetchField();
912     }
913     else {
914       return $this->connection->query('SELECT obj_description(oid, ?) FROM pg_class WHERE relname = ?', ['pg_class', $info['table']])->fetchField();
915     }
916   }
917
918   /**
919    * Calculates a base-64 encoded, PostgreSQL-safe sha-256 hash per PostgreSQL
920    * documentation: 4.1. Lexical Structure.
921    *
922    * @param $data
923    *   String to be hashed.
924    * @return string
925    *   A base-64 encoded sha-256 hash, with + and / replaced with _ and any =
926    *   padding characters removed.
927    */
928   protected function hashBase64($data) {
929     $hash = base64_encode(hash('sha256', $data, TRUE));
930     // Modify the hash so it's safe to use in PostgreSQL identifiers.
931     return strtr($hash, ['+' => '_', '/' => '_', '=' => '']);
932   }
933
934 }
935
936 /**
937  * @} End of "addtogroup schemaapi".
938  */