Security update for Core, with self-updated composer
[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 indexExists($table, $name) {
635     // Details http://www.postgresql.org/docs/9.1/interactive/view-pg-indexes.html
636     $index_name = $this->ensureIdentifiersLength($table, $name, 'idx');
637     // Remove leading and trailing quotes because the index name is in a WHERE
638     // clause and not used as an identifier.
639     $index_name = str_replace('"', '', $index_name);
640     return (bool) $this->connection->query("SELECT 1 FROM pg_indexes WHERE indexname = '$index_name'")->fetchField();
641   }
642
643   /**
644    * Helper function: check if a constraint (PK, FK, UK) exists.
645    *
646    * @param string $table
647    *   The name of the table.
648    * @param string $name
649    *   The name of the constraint (typically 'pkey' or '[constraint]__key').
650    *
651    * @return bool
652    *   TRUE if the constraint exists, FALSE otherwise.
653    */
654   public function constraintExists($table, $name) {
655     // ::ensureIdentifiersLength() expects three parameters, although not
656     // explicitly stated in its signature, thus we split our constraint name in
657     // a proper name and a suffix.
658     if ($name == 'pkey') {
659       $suffix = $name;
660       $name = '';
661     }
662     else {
663       $pos = strrpos($name, '__');
664       $suffix = substr($name, $pos + 2);
665       $name = substr($name, 0, $pos);
666     }
667     $constraint_name = $this->ensureIdentifiersLength($table, $name, $suffix);
668     // Remove leading and trailing quotes because the index name is in a WHERE
669     // clause and not used as an identifier.
670     $constraint_name = str_replace('"', '', $constraint_name);
671     return (bool) $this->connection->query("SELECT 1 FROM pg_constraint WHERE conname = '$constraint_name'")->fetchField();
672   }
673
674   /**
675    * {@inheritdoc}
676    */
677   public function addPrimaryKey($table, $fields) {
678     if (!$this->tableExists($table)) {
679       throw new SchemaObjectDoesNotExistException(t("Cannot add primary key to table @table: table doesn't exist.", ['@table' => $table]));
680     }
681     if ($this->constraintExists($table, 'pkey')) {
682       throw new SchemaObjectExistsException(t("Cannot add primary key to table @table: primary key already exists.", ['@table' => $table]));
683     }
684
685     $this->connection->query('ALTER TABLE {' . $table . '} ADD CONSTRAINT ' . $this->ensureIdentifiersLength($table, '', 'pkey') . ' PRIMARY KEY (' . $this->createPrimaryKeySql($fields) . ')');
686     $this->resetTableInformation($table);
687   }
688
689   /**
690    * {@inheritdoc}
691    */
692   public function dropPrimaryKey($table) {
693     if (!$this->constraintExists($table, 'pkey')) {
694       return FALSE;
695     }
696
697     $this->connection->query('ALTER TABLE {' . $table . '} DROP CONSTRAINT ' . $this->ensureIdentifiersLength($table, '', 'pkey'));
698     $this->resetTableInformation($table);
699     return TRUE;
700   }
701
702   /**
703    * {@inheritdoc}
704    */
705   public function addUniqueKey($table, $name, $fields) {
706     if (!$this->tableExists($table)) {
707       throw new SchemaObjectDoesNotExistException(t("Cannot add unique key @name to table @table: table doesn't exist.", ['@table' => $table, '@name' => $name]));
708     }
709     if ($this->constraintExists($table, $name . '__key')) {
710       throw new SchemaObjectExistsException(t("Cannot add unique key @name to table @table: unique key already exists.", ['@table' => $table, '@name' => $name]));
711     }
712
713     $this->connection->query('ALTER TABLE {' . $table . '} ADD CONSTRAINT ' . $this->ensureIdentifiersLength($table, $name, 'key') . ' UNIQUE (' . implode(',', $fields) . ')');
714     $this->resetTableInformation($table);
715   }
716
717   /**
718    * {@inheritdoc}
719    */
720   public function dropUniqueKey($table, $name) {
721     if (!$this->constraintExists($table, $name . '__key')) {
722       return FALSE;
723     }
724
725     $this->connection->query('ALTER TABLE {' . $table . '} DROP CONSTRAINT ' . $this->ensureIdentifiersLength($table, $name, 'key'));
726     $this->resetTableInformation($table);
727     return TRUE;
728   }
729
730   /**
731    * {@inheritdoc}
732    */
733   public function addIndex($table, $name, $fields, array $spec) {
734     if (!$this->tableExists($table)) {
735       throw new SchemaObjectDoesNotExistException(t("Cannot add index @name to table @table: table doesn't exist.", ['@table' => $table, '@name' => $name]));
736     }
737     if ($this->indexExists($table, $name)) {
738       throw new SchemaObjectExistsException(t("Cannot add index @name to table @table: index already exists.", ['@table' => $table, '@name' => $name]));
739     }
740
741     $this->connection->query($this->_createIndexSql($table, $name, $fields));
742     $this->resetTableInformation($table);
743   }
744
745   /**
746    * {@inheritdoc}
747    */
748   public function dropIndex($table, $name) {
749     if (!$this->indexExists($table, $name)) {
750       return FALSE;
751     }
752
753     $this->connection->query('DROP INDEX ' . $this->ensureIdentifiersLength($table, $name, 'idx'));
754     $this->resetTableInformation($table);
755     return TRUE;
756   }
757
758   /**
759    * {@inheritdoc}
760    */
761   public function changeField($table, $field, $field_new, $spec, $new_keys = []) {
762     if (!$this->fieldExists($table, $field)) {
763       throw new SchemaObjectDoesNotExistException(t("Cannot change the definition of field @table.@name: field doesn't exist.", ['@table' => $table, '@name' => $field]));
764     }
765     if (($field != $field_new) && $this->fieldExists($table, $field_new)) {
766       throw new SchemaObjectExistsException(t("Cannot rename field @table.@name to @name_new: target field already exists.", ['@table' => $table, '@name' => $field, '@name_new' => $field_new]));
767     }
768
769     $spec = $this->processField($spec);
770
771     // Type 'serial' is known to PostgreSQL, but only during table creation,
772     // not when altering. Because of that, we create it here as an 'int'. After
773     // we create it we manually re-apply the sequence.
774     if (in_array($spec['pgsql_type'], ['serial', 'bigserial'])) {
775       $field_def = 'int';
776     }
777     else {
778       $field_def = $spec['pgsql_type'];
779     }
780
781     if (in_array($spec['pgsql_type'], ['varchar', 'character', 'text']) && isset($spec['length'])) {
782       $field_def .= '(' . $spec['length'] . ')';
783     }
784     elseif (isset($spec['precision']) && isset($spec['scale'])) {
785       $field_def .= '(' . $spec['precision'] . ', ' . $spec['scale'] . ')';
786     }
787
788     // Remove old check constraints.
789     $field_info = $this->queryFieldInformation($table, $field);
790
791     foreach ($field_info as $check) {
792       $this->connection->query('ALTER TABLE {' . $table . '} DROP CONSTRAINT "' . $check . '"');
793     }
794
795     // Remove old default.
796     $this->fieldSetNoDefault($table, $field);
797
798     // Convert field type.
799     // Usually, we do this via a simple typecast 'USING fieldname::type'. But
800     // the typecast does not work for conversions to bytea.
801     // @see http://www.postgresql.org/docs/current/static/datatype-binary.html
802     $table_information = $this->queryTableInformation($table);
803     $is_bytea = !empty($table_information->blob_fields[$field]);
804     if ($spec['pgsql_type'] != 'bytea') {
805       if ($is_bytea) {
806         $this->connection->query('ALTER TABLE {' . $table . '} ALTER "' . $field . '" TYPE ' . $field_def . ' USING convert_from("' . $field . '"' . ", 'UTF8')");
807       }
808       else {
809         $this->connection->query('ALTER TABLE {' . $table . '} ALTER "' . $field . '" TYPE ' . $field_def . ' USING "' . $field . '"::' . $field_def);
810       }
811     }
812     else {
813       // Do not attempt to convert a field that is bytea already.
814       if (!$is_bytea) {
815         // Convert to a bytea type by using the SQL replace() function to
816         // convert any single backslashes in the field content to double
817         // backslashes ('\' to '\\').
818         $this->connection->query('ALTER TABLE {' . $table . '} ALTER "' . $field . '" TYPE ' . $field_def . ' USING decode(replace("' . $field . '"' . ", E'\\\\', E'\\\\\\\\'), 'escape');");
819       }
820     }
821
822     if (isset($spec['not null'])) {
823       if ($spec['not null']) {
824         $nullaction = 'SET NOT NULL';
825       }
826       else {
827         $nullaction = 'DROP NOT NULL';
828       }
829       $this->connection->query('ALTER TABLE {' . $table . '} ALTER "' . $field . '" ' . $nullaction);
830     }
831
832     if (in_array($spec['pgsql_type'], ['serial', 'bigserial'])) {
833       // Type "serial" is known to PostgreSQL, but *only* during table creation,
834       // not when altering. Because of that, the sequence needs to be created
835       // and initialized by hand.
836       $seq = "{" . $table . "}_" . $field_new . "_seq";
837       $this->connection->query("CREATE SEQUENCE " . $seq);
838       // Set sequence to maximal field value to not conflict with existing
839       // entries.
840       $this->connection->query("SELECT setval('" . $seq . "', MAX(\"" . $field . '")) FROM {' . $table . "}");
841       $this->connection->query('ALTER TABLE {' . $table . '} ALTER ' . $field . ' SET DEFAULT nextval(' . $this->connection->quote($seq) . ')');
842     }
843
844     // Rename the column if necessary.
845     if ($field != $field_new) {
846       $this->connection->query('ALTER TABLE {' . $table . '} RENAME "' . $field . '" TO "' . $field_new . '"');
847     }
848
849     // Add unsigned check if necessary.
850     if (!empty($spec['unsigned'])) {
851       $this->connection->query('ALTER TABLE {' . $table . '} ADD CHECK ("' . $field_new . '" >= 0)');
852     }
853
854     // Add default if necessary.
855     if (isset($spec['default'])) {
856       $this->fieldSetDefault($table, $field_new, $spec['default']);
857     }
858
859     // Change description if necessary.
860     if (!empty($spec['description'])) {
861       $this->connection->query('COMMENT ON COLUMN {' . $table . '}."' . $field_new . '" IS ' . $this->prepareComment($spec['description']));
862     }
863
864     if (isset($new_keys)) {
865       $this->_createKeys($table, $new_keys);
866     }
867     $this->resetTableInformation($table);
868   }
869
870   protected function _createIndexSql($table, $name, $fields) {
871     $query = 'CREATE INDEX ' . $this->ensureIdentifiersLength($table, $name, 'idx') . ' ON {' . $table . '} (';
872     $query .= $this->_createKeySql($fields) . ')';
873     return $query;
874   }
875
876   protected function _createKeys($table, $new_keys) {
877     if (isset($new_keys['primary key'])) {
878       $this->addPrimaryKey($table, $new_keys['primary key']);
879     }
880     if (isset($new_keys['unique keys'])) {
881       foreach ($new_keys['unique keys'] as $name => $fields) {
882         $this->addUniqueKey($table, $name, $fields);
883       }
884     }
885     if (isset($new_keys['indexes'])) {
886       foreach ($new_keys['indexes'] as $name => $fields) {
887         // Even though $new_keys is not a full schema it still has 'indexes' and
888         // so is a partial schema. Technically addIndex() doesn't do anything
889         // with it so passing an empty array would work as well.
890         $this->addIndex($table, $name, $fields, $new_keys);
891       }
892     }
893   }
894
895   /**
896    * Retrieve a table or column comment.
897    */
898   public function getComment($table, $column = NULL) {
899     $info = $this->getPrefixInfo($table);
900     // Don't use {} around pg_class, pg_attribute tables.
901     if (isset($column)) {
902       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();
903     }
904     else {
905       return $this->connection->query('SELECT obj_description(oid, ?) FROM pg_class WHERE relname = ?', ['pg_class', $info['table']])->fetchField();
906     }
907   }
908
909   /**
910    * Calculates a base-64 encoded, PostgreSQL-safe sha-256 hash per PostgreSQL
911    * documentation: 4.1. Lexical Structure.
912    *
913    * @param $data
914    *   String to be hashed.
915    * @return string
916    *   A base-64 encoded sha-256 hash, with + and / replaced with _ and any =
917    *   padding characters removed.
918    */
919   protected function hashBase64($data) {
920     $hash = base64_encode(hash('sha256', $data, TRUE));
921     // Modify the hash so it's safe to use in PostgreSQL identifiers.
922     return strtr($hash, ['+' => '_', '/' => '_', '=' => '']);
923   }
924
925 }
926
927 /**
928  * @} End of "addtogroup schemaapi".
929  */