8d01d5e9bd1dc957b58b82c6e68bf4ed94bbfab0
[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\Core\Database\SchemaObjectExistsException;
6 use Drupal\Core\Database\SchemaObjectDoesNotExistException;
7 use Drupal\Core\Database\Schema as DatabaseSchema;
8
9 /**
10  * @addtogroup schemaapi
11  * @{
12  */
13
14 /**
15  * PostgreSQL implementation of \Drupal\Core\Database\Schema.
16  */
17 class Schema extends DatabaseSchema {
18
19   /**
20    * A cache of information about blob columns and sequences of tables.
21    *
22    * This is collected by Schema::queryTableInformation(), by introspecting the
23    * database.
24    *
25    * @see \Drupal\Core\Database\Driver\pgsql\Schema::queryTableInformation()
26    * @var array
27    */
28   protected $tableInformation = [];
29
30   /**
31    * The maximum allowed length for index, primary key and constraint names.
32    *
33    * Value will usually be set to a 63 chars limit but PostgreSQL allows
34    * to higher this value before compiling, so we need to check for that.
35    *
36    * @var int
37    */
38   protected $maxIdentifierLength;
39
40   /**
41    * PostgreSQL's temporary namespace name.
42    *
43    * @var string
44    */
45   protected $tempNamespaceName;
46
47   /**
48    * Make sure to limit identifiers according to PostgreSQL compiled in length.
49    *
50    * PostgreSQL allows in standard configuration no longer identifiers than 63
51    * chars for table/relation names, indexes, primary keys, and constraints. So
52    * we map all identifiers that are too long to drupal_base64hash_tag, where
53    * tag is one of:
54    *   - idx for indexes
55    *   - key for constraints
56    *   - pkey for primary keys
57    *
58    * @param $identifiers
59    *   The arguments to build the identifier string
60    * @return
61    *   The index/constraint/pkey identifier
62    */
63   protected function ensureIdentifiersLength($identifier) {
64     $args = func_get_args();
65     $info = $this->getPrefixInfo($identifier);
66     $args[0] = $info['table'];
67     $identifierName = implode('__', $args);
68
69     // Retrieve the max identifier length which is usually 63 characters
70     // but can be altered before PostgreSQL is compiled so we need to check.
71     $this->maxIdentifierLength = $this->connection->query("SHOW max_identifier_length")->fetchField();
72
73     if (strlen($identifierName) > $this->maxIdentifierLength) {
74       $saveIdentifier = '"drupal_' . $this->hashBase64($identifierName) . '_' . $args[2] . '"';
75     }
76     else {
77       $saveIdentifier = $identifierName;
78     }
79     return $saveIdentifier;
80   }
81
82   /**
83    * Fetch the list of blobs and sequences used on a table.
84    *
85    * We introspect the database to collect the information required by insert
86    * and update queries.
87    *
88    * @param $table_name
89    *   The non-prefixed name of the table.
90    * @return
91    *   An object with two member variables:
92    *     - 'blob_fields' that lists all the blob fields in the table.
93    *     - 'sequences' that lists the sequences used in that table.
94    */
95   public function queryTableInformation($table) {
96     // Generate a key to reference this table's information on.
97     $key = $this->connection->prefixTables('{' . $table . '}');
98
99     // Take into account that temporary tables are stored in a different schema.
100     // \Drupal\Core\Database\Connection::generateTemporaryTableName() sets the
101     // 'db_temporary_' prefix to all temporary tables.
102     if (strpos($key, '.') === FALSE && strpos($table, 'db_temporary_') === FALSE) {
103       $key = 'public.' . $key;
104     }
105     else {
106       $key = $this->getTempNamespaceName() . '.' . $key;
107     }
108
109     if (!isset($this->tableInformation[$key])) {
110       $table_information = (object) [
111         'blob_fields' => [],
112         'sequences' => [],
113       ];
114       $this->connection->addSavepoint();
115
116       try {
117         // The bytea columns and sequences for a table can be found in
118         // pg_attribute, which is significantly faster than querying the
119         // information_schema. The data type of a field can be found by lookup
120         // of the attribute ID, and the default value must be extracted from the
121         // node tree for the attribute definition instead of the historical
122         // human-readable column, adsrc.
123         $sql = <<<'EOD'
124 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
125 FROM pg_attribute
126 LEFT JOIN pg_attrdef ON pg_attrdef.adrelid = pg_attribute.attrelid AND pg_attrdef.adnum = pg_attribute.attnum
127 WHERE pg_attribute.attnum > 0
128 AND NOT pg_attribute.attisdropped
129 AND pg_attribute.attrelid = :key::regclass
130 AND (format_type(pg_attribute.atttypid, pg_attribute.atttypmod) = 'bytea'
131 OR pg_attrdef.adsrc LIKE 'nextval%')
132 EOD;
133         $result = $this->connection->query($sql, [
134           ':key' => $key,
135         ]);
136       }
137       catch (\Exception $e) {
138         $this->connection->rollbackSavepoint();
139         throw $e;
140       }
141       $this->connection->releaseSavepoint();
142
143       // If the table information does not yet exist in the PostgreSQL
144       // metadata, then return the default table information here, so that it
145       // will not be cached.
146       if (empty($result)) {
147         return $table_information;
148       }
149
150       foreach ($result as $column) {
151         if ($column->data_type == 'bytea') {
152           $table_information->blob_fields[$column->column_name] = TRUE;
153         }
154         elseif (preg_match("/nextval\('([^']+)'/", $column->column_default, $matches)) {
155           // We must know of any sequences in the table structure to help us
156           // return the last insert id. If there is more than 1 sequences the
157           // first one (index 0 of the sequences array) will be used.
158           $table_information->sequences[] = $matches[1];
159           $table_information->serial_fields[] = $column->column_name;
160         }
161       }
162       $this->tableInformation[$key] = $table_information;
163     }
164     return $this->tableInformation[$key];
165   }
166
167   /**
168    * Gets PostgreSQL's temporary namespace name.
169    *
170    * @return string
171    *   PostgreSQL's temporary namespace name.
172    */
173   protected function getTempNamespaceName() {
174     if (!isset($this->tempNamespaceName)) {
175       $this->tempNamespaceName = $this->connection->query('SELECT nspname FROM pg_namespace WHERE oid = pg_my_temp_schema()')->fetchField();
176     }
177     return $this->tempNamespaceName;
178   }
179
180   /**
181    * Resets information about table blobs, sequences and serial fields.
182    *
183    * @param $table
184    *   The non-prefixed name of the table.
185    */
186   protected function resetTableInformation($table) {
187     $key = $this->connection->prefixTables('{' . $table . '}');
188     if (strpos($key, '.') === FALSE) {
189       $key = 'public.' . $key;
190     }
191     unset($this->tableInformation[$key]);
192   }
193
194   /**
195    * Fetch the list of CHECK constraints used on a field.
196    *
197    * We introspect the database to collect the information required by field
198    * alteration.
199    *
200    * @param $table
201    *   The non-prefixed name of the table.
202    * @param $field
203    *   The name of the field.
204    * @return
205    *   An array of all the checks for the field.
206    */
207   public function queryFieldInformation($table, $field) {
208     $prefixInfo = $this->getPrefixInfo($table, TRUE);
209
210     // Split the key into schema and table for querying.
211     $schema = $prefixInfo['schema'];
212     $table_name = $prefixInfo['table'];
213
214     $this->connection->addSavepoint();
215
216     try {
217       $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", [
218         ':schema' => $schema,
219         ':table' => $table_name,
220         ':column' => $field,
221       ]);
222     }
223     catch (\Exception $e) {
224       $this->connection->rollbackSavepoint();
225       throw $e;
226     }
227
228     $this->connection->releaseSavepoint();
229
230     $field_information = $checks->fetchCol();
231
232     return $field_information;
233   }
234
235   /**
236    * Generate SQL to create a new table from a Drupal schema definition.
237    *
238    * @param $name
239    *   The name of the table to create.
240    * @param $table
241    *   A Schema API table definition array.
242    * @return
243    *   An array of SQL statements to create the table.
244    */
245   protected function createTableSql($name, $table) {
246     $sql_fields = [];
247     foreach ($table['fields'] as $field_name => $field) {
248       $sql_fields[] = $this->createFieldSql($field_name, $this->processField($field));
249     }
250
251     $sql_keys = [];
252     if (!empty($table['primary key']) && is_array($table['primary key'])) {
253       $this->ensureNotNullPrimaryKey($table['primary key'], $table['fields']);
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'] = mb_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 data types 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($new_keys['primary key']) && in_array($field, $new_keys['primary key'], TRUE);
556     if ($is_primary_key) {
557       $this->ensureNotNullPrimaryKey($new_keys['primary key'], [$field => $spec]);
558     }
559
560     $fixnull = FALSE;
561     if (!empty($spec['not null']) && !isset($spec['default']) && !$is_primary_key) {
562       $fixnull = TRUE;
563       $spec['not null'] = FALSE;
564     }
565     $query = 'ALTER TABLE {' . $table . '} ADD COLUMN ';
566     $query .= $this->createFieldSql($field, $this->processField($spec));
567     $this->connection->query($query);
568     if (isset($spec['initial_from_field'])) {
569       if (isset($spec['initial'])) {
570         $expression = 'COALESCE(' . $spec['initial_from_field'] . ', :default_initial_value)';
571         $arguments = [':default_initial_value' => $spec['initial']];
572       }
573       else {
574         $expression = $spec['initial_from_field'];
575         $arguments = [];
576       }
577       $this->connection->update($table)
578         ->expression($field, $expression, $arguments)
579         ->execute();
580     }
581     elseif (isset($spec['initial'])) {
582       $this->connection->update($table)
583         ->fields([$field => $spec['initial']])
584         ->execute();
585     }
586     if ($fixnull) {
587       $this->connection->query("ALTER TABLE {" . $table . "} ALTER $field SET NOT NULL");
588     }
589     if (isset($new_keys)) {
590       // Make sure to drop the existing primary key before adding a new one.
591       // This is only needed when adding a field because this method, unlike
592       // changeField(), is supposed to handle primary keys automatically.
593       if (isset($new_keys['primary key']) && $this->constraintExists($table, 'pkey')) {
594         $this->dropPrimaryKey($table);
595       }
596       $this->_createKeys($table, $new_keys);
597     }
598     // Add column comment.
599     if (!empty($spec['description'])) {
600       $this->connection->query('COMMENT ON COLUMN {' . $table . '}.' . $field . ' IS ' . $this->prepareComment($spec['description']));
601     }
602     $this->resetTableInformation($table);
603   }
604
605   /**
606    * {@inheritdoc}
607    */
608   public function dropField($table, $field) {
609     if (!$this->fieldExists($table, $field)) {
610       return FALSE;
611     }
612
613     $this->connection->query('ALTER TABLE {' . $table . '} DROP COLUMN "' . $field . '"');
614     $this->resetTableInformation($table);
615     return TRUE;
616   }
617
618   /**
619    * {@inheritdoc}
620    */
621   public function fieldSetDefault($table, $field, $default) {
622     if (!$this->fieldExists($table, $field)) {
623       throw new SchemaObjectDoesNotExistException(t("Cannot set default value of field @table.@field: field doesn't exist.", ['@table' => $table, '@field' => $field]));
624     }
625
626     $default = $this->escapeDefaultValue($default);
627
628     $this->connection->query('ALTER TABLE {' . $table . '} ALTER COLUMN "' . $field . '" SET DEFAULT ' . $default);
629   }
630
631   /**
632    * {@inheritdoc}
633    */
634   public function fieldSetNoDefault($table, $field) {
635     if (!$this->fieldExists($table, $field)) {
636       throw new SchemaObjectDoesNotExistException(t("Cannot remove default value of field @table.@field: field doesn't exist.", ['@table' => $table, '@field' => $field]));
637     }
638
639     $this->connection->query('ALTER TABLE {' . $table . '} ALTER COLUMN "' . $field . '" DROP DEFAULT');
640   }
641
642   /**
643    * {@inheritdoc}
644    */
645   public function fieldExists($table, $column) {
646     $prefixInfo = $this->getPrefixInfo($table);
647
648     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();
649   }
650
651   /**
652    * {@inheritdoc}
653    */
654   public function indexExists($table, $name) {
655     // Details http://www.postgresql.org/docs/9.1/interactive/view-pg-indexes.html
656     $index_name = $this->ensureIdentifiersLength($table, $name, 'idx');
657     // Remove leading and trailing quotes because the index name is in a WHERE
658     // clause and not used as an identifier.
659     $index_name = str_replace('"', '', $index_name);
660     return (bool) $this->connection->query("SELECT 1 FROM pg_indexes WHERE indexname = '$index_name'")->fetchField();
661   }
662
663   /**
664    * Helper function: check if a constraint (PK, FK, UK) exists.
665    *
666    * @param string $table
667    *   The name of the table.
668    * @param string $name
669    *   The name of the constraint (typically 'pkey' or '[constraint]__key').
670    *
671    * @return bool
672    *   TRUE if the constraint exists, FALSE otherwise.
673    */
674   public function constraintExists($table, $name) {
675     // ::ensureIdentifiersLength() expects three parameters, although not
676     // explicitly stated in its signature, thus we split our constraint name in
677     // a proper name and a suffix.
678     if ($name == 'pkey') {
679       $suffix = $name;
680       $name = '';
681     }
682     else {
683       $pos = strrpos($name, '__');
684       $suffix = substr($name, $pos + 2);
685       $name = substr($name, 0, $pos);
686     }
687     $constraint_name = $this->ensureIdentifiersLength($table, $name, $suffix);
688     // Remove leading and trailing quotes because the index name is in a WHERE
689     // clause and not used as an identifier.
690     $constraint_name = str_replace('"', '', $constraint_name);
691     return (bool) $this->connection->query("SELECT 1 FROM pg_constraint WHERE conname = '$constraint_name'")->fetchField();
692   }
693
694   /**
695    * {@inheritdoc}
696    */
697   public function addPrimaryKey($table, $fields) {
698     if (!$this->tableExists($table)) {
699       throw new SchemaObjectDoesNotExistException(t("Cannot add primary key to table @table: table doesn't exist.", ['@table' => $table]));
700     }
701     if ($this->constraintExists($table, 'pkey')) {
702       throw new SchemaObjectExistsException(t("Cannot add primary key to table @table: primary key already exists.", ['@table' => $table]));
703     }
704
705     $this->connection->query('ALTER TABLE {' . $table . '} ADD CONSTRAINT ' . $this->ensureIdentifiersLength($table, '', 'pkey') . ' PRIMARY KEY (' . $this->createPrimaryKeySql($fields) . ')');
706     $this->resetTableInformation($table);
707   }
708
709   /**
710    * {@inheritdoc}
711    */
712   public function dropPrimaryKey($table) {
713     if (!$this->constraintExists($table, 'pkey')) {
714       return FALSE;
715     }
716
717     $this->connection->query('ALTER TABLE {' . $table . '} DROP CONSTRAINT ' . $this->ensureIdentifiersLength($table, '', 'pkey'));
718     $this->resetTableInformation($table);
719     return TRUE;
720   }
721
722   /**
723    * {@inheritdoc}
724    */
725   protected function findPrimaryKeyColumns($table) {
726     if (!$this->tableExists($table)) {
727       return FALSE;
728     }
729
730     // Fetch the 'indkey' column from 'pg_index' to figure out the order of the
731     // primary key.
732     // @todo Use 'array_position()' to be able to perform the ordering in SQL
733     //   directly when 9.5 is the minimum  PostgreSQL version.
734     $result = $this->connection->query("SELECT a.attname, i.indkey FROM pg_index i JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = ANY(i.indkey) WHERE i.indrelid = '{" . $table . "}'::regclass AND i.indisprimary")->fetchAllKeyed();
735     if (!$result) {
736       return [];
737     }
738
739     $order = explode(' ', reset($result));
740     $columns = array_combine($order, array_keys($result));
741     ksort($columns);
742     return array_values($columns);
743   }
744
745   /**
746    * {@inheritdoc}
747    */
748   public function addUniqueKey($table, $name, $fields) {
749     if (!$this->tableExists($table)) {
750       throw new SchemaObjectDoesNotExistException(t("Cannot add unique key @name to table @table: table doesn't exist.", ['@table' => $table, '@name' => $name]));
751     }
752     if ($this->constraintExists($table, $name . '__key')) {
753       throw new SchemaObjectExistsException(t("Cannot add unique key @name to table @table: unique key already exists.", ['@table' => $table, '@name' => $name]));
754     }
755
756     $this->connection->query('ALTER TABLE {' . $table . '} ADD CONSTRAINT ' . $this->ensureIdentifiersLength($table, $name, 'key') . ' UNIQUE (' . implode(',', $fields) . ')');
757     $this->resetTableInformation($table);
758   }
759
760   /**
761    * {@inheritdoc}
762    */
763   public function dropUniqueKey($table, $name) {
764     if (!$this->constraintExists($table, $name . '__key')) {
765       return FALSE;
766     }
767
768     $this->connection->query('ALTER TABLE {' . $table . '} DROP CONSTRAINT ' . $this->ensureIdentifiersLength($table, $name, 'key'));
769     $this->resetTableInformation($table);
770     return TRUE;
771   }
772
773   /**
774    * {@inheritdoc}
775    */
776   public function addIndex($table, $name, $fields, array $spec) {
777     if (!$this->tableExists($table)) {
778       throw new SchemaObjectDoesNotExistException(t("Cannot add index @name to table @table: table doesn't exist.", ['@table' => $table, '@name' => $name]));
779     }
780     if ($this->indexExists($table, $name)) {
781       throw new SchemaObjectExistsException(t("Cannot add index @name to table @table: index already exists.", ['@table' => $table, '@name' => $name]));
782     }
783
784     $this->connection->query($this->_createIndexSql($table, $name, $fields));
785     $this->resetTableInformation($table);
786   }
787
788   /**
789    * {@inheritdoc}
790    */
791   public function dropIndex($table, $name) {
792     if (!$this->indexExists($table, $name)) {
793       return FALSE;
794     }
795
796     $this->connection->query('DROP INDEX ' . $this->ensureIdentifiersLength($table, $name, 'idx'));
797     $this->resetTableInformation($table);
798     return TRUE;
799   }
800
801   /**
802    * {@inheritdoc}
803    */
804   public function changeField($table, $field, $field_new, $spec, $new_keys = []) {
805     if (!$this->fieldExists($table, $field)) {
806       throw new SchemaObjectDoesNotExistException(t("Cannot change the definition of field @table.@name: field doesn't exist.", ['@table' => $table, '@name' => $field]));
807     }
808     if (($field != $field_new) && $this->fieldExists($table, $field_new)) {
809       throw new SchemaObjectExistsException(t("Cannot rename field @table.@name to @name_new: target field already exists.", ['@table' => $table, '@name' => $field, '@name_new' => $field_new]));
810     }
811     if (isset($new_keys['primary key']) && in_array($field_new, $new_keys['primary key'], TRUE)) {
812       $this->ensureNotNullPrimaryKey($new_keys['primary key'], [$field_new => $spec]);
813     }
814
815     $spec = $this->processField($spec);
816
817     // Type 'serial' is known to PostgreSQL, but only during table creation,
818     // not when altering. Because of that, we create it here as an 'int'. After
819     // we create it we manually re-apply the sequence.
820     if (in_array($spec['pgsql_type'], ['serial', 'bigserial'])) {
821       $field_def = 'int';
822     }
823     else {
824       $field_def = $spec['pgsql_type'];
825     }
826
827     if (in_array($spec['pgsql_type'], ['varchar', 'character', 'text']) && isset($spec['length'])) {
828       $field_def .= '(' . $spec['length'] . ')';
829     }
830     elseif (isset($spec['precision']) && isset($spec['scale'])) {
831       $field_def .= '(' . $spec['precision'] . ', ' . $spec['scale'] . ')';
832     }
833
834     // Remove old check constraints.
835     $field_info = $this->queryFieldInformation($table, $field);
836
837     foreach ($field_info as $check) {
838       $this->connection->query('ALTER TABLE {' . $table . '} DROP CONSTRAINT "' . $check . '"');
839     }
840
841     // Remove old default.
842     $this->fieldSetNoDefault($table, $field);
843
844     // Convert field type.
845     // Usually, we do this via a simple typecast 'USING fieldname::type'. But
846     // the typecast does not work for conversions to bytea.
847     // @see http://www.postgresql.org/docs/current/static/datatype-binary.html
848     $table_information = $this->queryTableInformation($table);
849     $is_bytea = !empty($table_information->blob_fields[$field]);
850     if ($spec['pgsql_type'] != 'bytea') {
851       if ($is_bytea) {
852         $this->connection->query('ALTER TABLE {' . $table . '} ALTER "' . $field . '" TYPE ' . $field_def . ' USING convert_from("' . $field . '"' . ", 'UTF8')");
853       }
854       else {
855         $this->connection->query('ALTER TABLE {' . $table . '} ALTER "' . $field . '" TYPE ' . $field_def . ' USING "' . $field . '"::' . $field_def);
856       }
857     }
858     else {
859       // Do not attempt to convert a field that is bytea already.
860       if (!$is_bytea) {
861         // Convert to a bytea type by using the SQL replace() function to
862         // convert any single backslashes in the field content to double
863         // backslashes ('\' to '\\').
864         $this->connection->query('ALTER TABLE {' . $table . '} ALTER "' . $field . '" TYPE ' . $field_def . ' USING decode(replace("' . $field . '"' . ", E'\\\\', E'\\\\\\\\'), 'escape');");
865       }
866     }
867
868     if (isset($spec['not null'])) {
869       if ($spec['not null']) {
870         $nullaction = 'SET NOT NULL';
871       }
872       else {
873         $nullaction = 'DROP NOT NULL';
874       }
875       $this->connection->query('ALTER TABLE {' . $table . '} ALTER "' . $field . '" ' . $nullaction);
876     }
877
878     if (in_array($spec['pgsql_type'], ['serial', 'bigserial'])) {
879       // Type "serial" is known to PostgreSQL, but *only* during table creation,
880       // not when altering. Because of that, the sequence needs to be created
881       // and initialized by hand.
882       $seq = "{" . $table . "}_" . $field_new . "_seq";
883       $this->connection->query("CREATE SEQUENCE " . $seq);
884       // Set sequence to maximal field value to not conflict with existing
885       // entries.
886       $this->connection->query("SELECT setval('" . $seq . "', MAX(\"" . $field . '")) FROM {' . $table . "}");
887       $this->connection->query('ALTER TABLE {' . $table . '} ALTER ' . $field . ' SET DEFAULT nextval(' . $this->connection->quote($seq) . ')');
888     }
889
890     // Rename the column if necessary.
891     if ($field != $field_new) {
892       $this->connection->query('ALTER TABLE {' . $table . '} RENAME "' . $field . '" TO "' . $field_new . '"');
893     }
894
895     // Add unsigned check if necessary.
896     if (!empty($spec['unsigned'])) {
897       $this->connection->query('ALTER TABLE {' . $table . '} ADD CHECK ("' . $field_new . '" >= 0)');
898     }
899
900     // Add default if necessary.
901     if (isset($spec['default'])) {
902       $this->fieldSetDefault($table, $field_new, $spec['default']);
903     }
904
905     // Change description if necessary.
906     if (!empty($spec['description'])) {
907       $this->connection->query('COMMENT ON COLUMN {' . $table . '}."' . $field_new . '" IS ' . $this->prepareComment($spec['description']));
908     }
909
910     if (isset($new_keys)) {
911       $this->_createKeys($table, $new_keys);
912     }
913     $this->resetTableInformation($table);
914   }
915
916   protected function _createIndexSql($table, $name, $fields) {
917     $query = 'CREATE INDEX ' . $this->ensureIdentifiersLength($table, $name, 'idx') . ' ON {' . $table . '} (';
918     $query .= $this->_createKeySql($fields) . ')';
919     return $query;
920   }
921
922   protected function _createKeys($table, $new_keys) {
923     if (isset($new_keys['primary key'])) {
924       $this->addPrimaryKey($table, $new_keys['primary key']);
925     }
926     if (isset($new_keys['unique keys'])) {
927       foreach ($new_keys['unique keys'] as $name => $fields) {
928         $this->addUniqueKey($table, $name, $fields);
929       }
930     }
931     if (isset($new_keys['indexes'])) {
932       foreach ($new_keys['indexes'] as $name => $fields) {
933         // Even though $new_keys is not a full schema it still has 'indexes' and
934         // so is a partial schema. Technically addIndex() doesn't do anything
935         // with it so passing an empty array would work as well.
936         $this->addIndex($table, $name, $fields, $new_keys);
937       }
938     }
939   }
940
941   /**
942    * Retrieve a table or column comment.
943    */
944   public function getComment($table, $column = NULL) {
945     $info = $this->getPrefixInfo($table);
946     // Don't use {} around pg_class, pg_attribute tables.
947     if (isset($column)) {
948       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();
949     }
950     else {
951       return $this->connection->query('SELECT obj_description(oid, ?) FROM pg_class WHERE relname = ?', ['pg_class', $info['table']])->fetchField();
952     }
953   }
954
955   /**
956    * Calculates a base-64 encoded, PostgreSQL-safe sha-256 hash per PostgreSQL
957    * documentation: 4.1. Lexical Structure.
958    *
959    * @param $data
960    *   String to be hashed.
961    * @return string
962    *   A base-64 encoded sha-256 hash, with + and / replaced with _ and any =
963    *   padding characters removed.
964    */
965   protected function hashBase64($data) {
966     $hash = base64_encode(hash('sha256', $data, TRUE));
967     // Modify the hash so it's safe to use in PostgreSQL identifiers.
968     return strtr($hash, ['+' => '_', '/' => '_', '=' => '']);
969   }
970
971 }
972
973 /**
974  * @} End of "addtogroup schemaapi".
975  */