3 namespace Drupal\Core\Database\Driver\pgsql;
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;
11 * @addtogroup schemaapi
16 * PostgreSQL implementation of \Drupal\Core\Database\Schema.
18 class Schema extends DatabaseSchema {
21 * A cache of information about blob columns and sequences of tables.
23 * This is collected by Schema::queryTableInformation(), by introspecting the
26 * @see \Drupal\Core\Database\Driver\pgsql\Schema::queryTableInformation()
29 protected $tableInformation = [];
32 * The maximum allowed length for index, primary key and constraint names.
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.
39 protected $maxIdentifierLength;
42 * PostgreSQL's temporary namespace name.
46 protected $tempNamespaceName;
49 * Make sure to limit identifiers according to PostgreSQL compiled in length.
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
56 * - key for constraints
57 * - pkey for primary keys
60 * The arguments to build the identifier string
62 * The index/constraint/pkey identifier
64 protected function ensureIdentifiersLength($identifier) {
65 $args = func_get_args();
66 $info = $this->getPrefixInfo($identifier);
67 $args[0] = $info['table'];
68 $identifierName = implode('__', $args);
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();
74 if (strlen($identifierName) > $this->maxIdentifierLength) {
75 $saveIdentifier = '"drupal_' . $this->hashBase64($identifierName) . '_' . $args[2] . '"';
78 $saveIdentifier = $identifierName;
80 return $saveIdentifier;
84 * Fetch the list of blobs and sequences used on a table.
86 * We introspect the database to collect the information required by insert
90 * The non-prefixed name of the table.
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.
96 public function queryTableInformation($table) {
97 // Generate a key to reference this table's information on.
98 $key = $this->connection->prefixTables('{' . $table . '}');
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;
107 $key = $this->getTempNamespaceName() . '.' . $key;
110 if (!isset($this->tableInformation[$key])) {
111 $table_information = (object) [
115 $this->connection->addSavepoint();
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.
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
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%')
134 $result = $this->connection->query($sql, [
138 catch (\Exception $e) {
139 $this->connection->rollbackSavepoint();
142 $this->connection->releaseSavepoint();
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;
151 foreach ($result as $column) {
152 if ($column->data_type == 'bytea') {
153 $table_information->blob_fields[$column->column_name] = TRUE;
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;
163 $this->tableInformation[$key] = $table_information;
165 return $this->tableInformation[$key];
169 * Gets PostgreSQL's temporary namespace name.
172 * PostgreSQL's temporary namespace name.
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();
178 return $this->tempNamespaceName;
182 * Resets information about table blobs, sequences and serial fields.
185 * The non-prefixed name of the table.
187 protected function resetTableInformation($table) {
188 $key = $this->connection->prefixTables('{' . $table . '}');
189 if (strpos($key, '.') === FALSE) {
190 $key = 'public.' . $key;
192 unset($this->tableInformation[$key]);
196 * Fetch the list of CHECK constraints used on a field.
198 * We introspect the database to collect the information required by field
202 * The non-prefixed name of the table.
204 * The name of the field.
206 * An array of all the checks for the field.
208 public function queryFieldInformation($table, $field) {
209 $prefixInfo = $this->getPrefixInfo($table, TRUE);
211 // Split the key into schema and table for querying.
212 $schema = $prefixInfo['schema'];
213 $table_name = $prefixInfo['table'];
215 $this->connection->addSavepoint();
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,
224 catch (\Exception $e) {
225 $this->connection->rollbackSavepoint();
229 $this->connection->releaseSavepoint();
231 $field_information = $checks->fetchCol();
233 return $field_information;
237 * Generate SQL to create a new table from a Drupal schema definition.
240 * The name of the table to create.
242 * A Schema API table definition array.
244 * An array of SQL statements to create the table.
246 protected function createTableSql($name, $table) {
248 foreach ($table['fields'] as $field_name => $field) {
249 $sql_fields[] = $this->createFieldSql($field_name, $this->processField($field));
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']) . ')';
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) . ')';
262 $sql = "CREATE TABLE {" . $name . "} (\n\t";
263 $sql .= implode(",\n\t", $sql_fields);
264 if (count($sql_keys) > 0) {
267 $sql .= implode(",\n\t", $sql_keys);
269 $statements[] = $sql;
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);
277 // Add table comment.
278 if (!empty($table['description'])) {
279 $statements[] = 'COMMENT ON TABLE {' . $name . '} IS ' . $this->prepareComment($table['description']);
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']);
293 * Create an SQL string for a field to be used in table creation or
296 * Before passing a field out of a schema definition into this
297 * function it has to be processed by _db_process_field().
302 * The field specification, as per the schema data structure format.
304 protected function createFieldSql($name, $spec) {
305 // The PostgreSQL server converts names into lowercase, unless quoted.
306 $sql = '"' . $name . '" ' . $spec['pgsql_type'];
308 if (isset($spec['type']) && $spec['type'] == 'serial') {
309 unset($spec['not null']);
312 if (in_array($spec['pgsql_type'], ['varchar', 'character']) && isset($spec['length'])) {
313 $sql .= '(' . $spec['length'] . ')';
315 elseif (isset($spec['precision']) && isset($spec['scale'])) {
316 $sql .= '(' . $spec['precision'] . ', ' . $spec['scale'] . ')';
319 if (!empty($spec['unsigned'])) {
320 $sql .= " CHECK ($name >= 0)";
323 if (isset($spec['not null'])) {
324 if ($spec['not null']) {
331 if (array_key_exists('default', $spec)) {
332 $default = $this->escapeDefaultValue($spec['default']);
333 $sql .= " default $default";
340 * Set database-engine specific properties for a field.
343 * A field description array, as specified in the schema documentation.
345 protected function processField($field) {
346 if (!isset($field['size'])) {
347 $field['size'] = 'normal';
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']);
356 $map = $this->getFieldTypeMap();
357 $field['pgsql_type'] = $map[$field['type'] . ':' . $field['size']];
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.
368 $map = $this->getFieldTypeMap();
370 switch ($field['pgsql_type']) {
372 $field['pgsql_type'] = $map['int:medium'];
375 $field['pgsql_type'] = $map['int:big'];
379 if (isset($field['type']) && $field['type'] == 'serial') {
380 unset($field['not null']);
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.
394 'varchar_ascii:normal' => 'varchar',
396 'varchar:normal' => 'varchar',
397 'char:normal' => 'character',
399 'text:tiny' => 'text',
400 'text:small' => 'text',
401 'text:medium' => 'text',
402 'text:big' => 'text',
403 'text:normal' => 'text',
405 'int:tiny' => 'smallint',
406 'int:small' => 'smallint',
407 'int:medium' => 'int',
408 'int:big' => 'bigint',
409 'int:normal' => 'int',
411 'float:tiny' => 'real',
412 'float:small' => 'real',
413 'float:medium' => 'real',
414 'float:big' => 'double precision',
415 'float:normal' => 'real',
417 'numeric:normal' => 'numeric',
419 'blob:big' => 'bytea',
420 'blob:normal' => 'bytea',
422 'serial:tiny' => 'serial',
423 'serial:small' => 'serial',
424 'serial:medium' => 'serial',
425 'serial:big' => 'bigserial',
426 'serial:normal' => 'serial',
431 protected function _createKeySql($fields) {
433 foreach ($fields as $field) {
434 if (is_array($field)) {
435 $return[] = 'substr(' . $field[0] . ', 1, ' . $field[1] . ')';
438 $return[] = '"' . $field . '"';
441 return implode(', ', $return);
445 * Create the SQL expression for primary keys.
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.
451 protected function createPrimaryKeySql($fields) {
453 foreach ($fields as $field) {
454 if (is_array($field)) {
455 $return[] = '"' . $field[0] . '"';
458 $return[] = '"' . $field . '"';
461 return implode(', ', $return);
467 public function tableExists($table) {
468 $prefixInfo = $this->getPrefixInfo($table, TRUE);
470 return (bool) $this->connection->query("SELECT 1 FROM pg_tables WHERE schemaname = :schema AND tablename = :table", [':schema' => $prefixInfo['schema'], ':table' => $prefixInfo['table']])->fetchField();
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]));
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]));
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];
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]);
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);
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];
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];
510 $this->connection->query('ALTER INDEX "' . $index->indexname . '" RENAME TO ' . $this->ensureIdentifiersLength($new_name, $index_name, $index_type) . '');
513 // Ensure the new table name does not include schema syntax.
514 $prefixInfo = $this->getPrefixInfo($new_name);
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);
525 // Now rename the table.
526 $this->connection->query('ALTER TABLE {' . $table . '} RENAME TO ' . $prefixInfo['table']);
527 $this->resetTableInformation($table);
533 public function dropTable($table) {
534 if (!$this->tableExists($table)) {
538 $this->connection->query('DROP TABLE {' . $table . '}');
539 $this->resetTableInformation($table);
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]));
550 if ($this->fieldExists($table, $field)) {
551 throw new SchemaObjectExistsException(t("Cannot add field @table.@field: field already exists.", ['@field' => $field, '@table' => $table]));
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);
558 if (!empty($spec['not null']) && !isset($spec['default']) && !$is_primary_key) {
560 $spec['not null'] = FALSE;
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']])
570 if (isset($spec['initial_from_field'])) {
571 $this->connection->update($table)
572 ->expression($field, $spec['initial_from_field'])
576 $this->connection->query("ALTER TABLE {" . $table . "} ALTER $field SET NOT NULL");
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);
585 $this->_createKeys($table, $new_keys);
587 // Add column comment.
588 if (!empty($spec['description'])) {
589 $this->connection->query('COMMENT ON COLUMN {' . $table . '}.' . $field . ' IS ' . $this->prepareComment($spec['description']));
591 $this->resetTableInformation($table);
597 public function dropField($table, $field) {
598 if (!$this->fieldExists($table, $field)) {
602 $this->connection->query('ALTER TABLE {' . $table . '} DROP COLUMN "' . $field . '"');
603 $this->resetTableInformation($table);
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]));
615 $default = $this->escapeDefaultValue($default);
617 $this->connection->query('ALTER TABLE {' . $table . '} ALTER COLUMN "' . $field . '" SET DEFAULT ' . $default);
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]));
628 $this->connection->query('ALTER TABLE {' . $table . '} ALTER COLUMN "' . $field . '" DROP DEFAULT');
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();
644 * Helper function: check if a constraint (PK, FK, UK) exists.
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').
652 * TRUE if the constraint exists, FALSE otherwise.
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') {
663 $pos = strrpos($name, '__');
664 $suffix = substr($name, $pos + 2);
665 $name = substr($name, 0, $pos);
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();
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]));
681 if ($this->constraintExists($table, 'pkey')) {
682 throw new SchemaObjectExistsException(t("Cannot add primary key to table @table: primary key already exists.", ['@table' => $table]));
685 $this->connection->query('ALTER TABLE {' . $table . '} ADD CONSTRAINT ' . $this->ensureIdentifiersLength($table, '', 'pkey') . ' PRIMARY KEY (' . $this->createPrimaryKeySql($fields) . ')');
686 $this->resetTableInformation($table);
692 public function dropPrimaryKey($table) {
693 if (!$this->constraintExists($table, 'pkey')) {
697 $this->connection->query('ALTER TABLE {' . $table . '} DROP CONSTRAINT ' . $this->ensureIdentifiersLength($table, '', 'pkey'));
698 $this->resetTableInformation($table);
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]));
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]));
713 $this->connection->query('ALTER TABLE {' . $table . '} ADD CONSTRAINT ' . $this->ensureIdentifiersLength($table, $name, 'key') . ' UNIQUE (' . implode(',', $fields) . ')');
714 $this->resetTableInformation($table);
720 public function dropUniqueKey($table, $name) {
721 if (!$this->constraintExists($table, $name . '__key')) {
725 $this->connection->query('ALTER TABLE {' . $table . '} DROP CONSTRAINT ' . $this->ensureIdentifiersLength($table, $name, 'key'));
726 $this->resetTableInformation($table);
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]));
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]));
741 $this->connection->query($this->_createIndexSql($table, $name, $fields));
742 $this->resetTableInformation($table);
748 public function dropIndex($table, $name) {
749 if (!$this->indexExists($table, $name)) {
753 $this->connection->query('DROP INDEX ' . $this->ensureIdentifiersLength($table, $name, 'idx'));
754 $this->resetTableInformation($table);
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]));
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]));
769 $spec = $this->processField($spec);
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'])) {
778 $field_def = $spec['pgsql_type'];
781 if (in_array($spec['pgsql_type'], ['varchar', 'character', 'text']) && isset($spec['length'])) {
782 $field_def .= '(' . $spec['length'] . ')';
784 elseif (isset($spec['precision']) && isset($spec['scale'])) {
785 $field_def .= '(' . $spec['precision'] . ', ' . $spec['scale'] . ')';
788 // Remove old check constraints.
789 $field_info = $this->queryFieldInformation($table, $field);
791 foreach ($field_info as $check) {
792 $this->connection->query('ALTER TABLE {' . $table . '} DROP CONSTRAINT "' . $check . '"');
795 // Remove old default.
796 $this->fieldSetNoDefault($table, $field);
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') {
806 $this->connection->query('ALTER TABLE {' . $table . '} ALTER "' . $field . '" TYPE ' . $field_def . ' USING convert_from("' . $field . '"' . ", 'UTF8')");
809 $this->connection->query('ALTER TABLE {' . $table . '} ALTER "' . $field . '" TYPE ' . $field_def . ' USING "' . $field . '"::' . $field_def);
813 // Do not attempt to convert a field that is bytea already.
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');");
822 if (isset($spec['not null'])) {
823 if ($spec['not null']) {
824 $nullaction = 'SET NOT NULL';
827 $nullaction = 'DROP NOT NULL';
829 $this->connection->query('ALTER TABLE {' . $table . '} ALTER "' . $field . '" ' . $nullaction);
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
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) . ')');
844 // Rename the column if necessary.
845 if ($field != $field_new) {
846 $this->connection->query('ALTER TABLE {' . $table . '} RENAME "' . $field . '" TO "' . $field_new . '"');
849 // Add unsigned check if necessary.
850 if (!empty($spec['unsigned'])) {
851 $this->connection->query('ALTER TABLE {' . $table . '} ADD CHECK ("' . $field_new . '" >= 0)');
854 // Add default if necessary.
855 if (isset($spec['default'])) {
856 $this->fieldSetDefault($table, $field_new, $spec['default']);
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']));
864 if (isset($new_keys)) {
865 $this->_createKeys($table, $new_keys);
867 $this->resetTableInformation($table);
870 protected function _createIndexSql($table, $name, $fields) {
871 $query = 'CREATE INDEX ' . $this->ensureIdentifiersLength($table, $name, 'idx') . ' ON {' . $table . '} (';
872 $query .= $this->_createKeySql($fields) . ')';
876 protected function _createKeys($table, $new_keys) {
877 if (isset($new_keys['primary key'])) {
878 $this->addPrimaryKey($table, $new_keys['primary key']);
880 if (isset($new_keys['unique keys'])) {
881 foreach ($new_keys['unique keys'] as $name => $fields) {
882 $this->addUniqueKey($table, $name, $fields);
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);
896 * Retrieve a table or column comment.
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();
905 return $this->connection->query('SELECT obj_description(oid, ?) FROM pg_class WHERE relname = ?', ['pg_class', $info['table']])->fetchField();
910 * Calculates a base-64 encoded, PostgreSQL-safe sha-256 hash per PostgreSQL
911 * documentation: 4.1. Lexical Structure.
914 * String to be hashed.
916 * A base-64 encoded sha-256 hash, with + and / replaced with _ and any =
917 * padding characters removed.
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, ['+' => '_', '/' => '_', '=' => '']);
928 * @} End of "addtogroup schemaapi".