diff --git a/core/modules/mysql/src/Driver/Database/mysql/Schema.php b/core/modules/mysql/src/Driver/Database/mysql/Schema.php index 1d54466a67..a726a4551b 100644 --- a/core/modules/mysql/src/Driver/Database/mysql/Schema.php +++ b/core/modules/mysql/src/Driver/Database/mysql/Schema.php @@ -146,7 +146,7 @@ protected function createTableSql($name, $table) { * The field specification, as per the schema data structure format. */ protected function createFieldSql($name, $spec) { - $sql = "`" . $name . "` " . $spec['mysql_type']; + $sql = "[" . $name . "] " . $spec['mysql_type']; if (in_array($spec['mysql_type'], $this->mysqlStringTypes)) { if (isset($spec['length'])) { @@ -284,13 +284,13 @@ protected function createKeysSql($spec) { } if (!empty($spec['unique keys'])) { foreach ($spec['unique keys'] as $key => $fields) { - $keys[] = 'UNIQUE KEY `' . $key . '` (' . $this->createKeySql($fields) . ')'; + $keys[] = 'UNIQUE KEY [' . $key . '] (' . $this->createKeySql($fields) . ')'; } } if (!empty($spec['indexes'])) { $indexes = $this->getNormalizedIndexes($spec); foreach ($indexes as $index => $fields) { - $keys[] = 'INDEX `' . $index . '` (' . $this->createKeySql($fields) . ')'; + $keys[] = 'INDEX [' . $index . '] (' . $this->createKeySql($fields) . ')'; } } @@ -364,10 +364,10 @@ protected function createKeySql($fields) { $return = []; foreach ($fields as $field) { if (is_array($field)) { - $return[] = '`' . $field[0] . '`(' . $field[1] . ')'; + $return[] = '[' . $field[0] . '] (' . $field[1] . ')'; } else { - $return[] = '`' . $field . '`'; + $return[] = '[' . $field . ']'; } } return implode(', ', $return); @@ -385,7 +385,7 @@ public function renameTable($table, $new_name) { } $info = $this->getPrefixInfo($new_name); - $this->connection->query('ALTER TABLE {' . $table . '} RENAME TO `' . $info['table'] . '`'); + $this->connection->query('ALTER TABLE {' . $table . '} RENAME TO [' . $info['table'] . ']'); } /** @@ -479,7 +479,7 @@ public function dropField($table, $field) { $this->dropPrimaryKey($table); } - $this->connection->query('ALTER TABLE {' . $table . '} DROP `' . $field . '`'); + $this->connection->query('ALTER TABLE {' . $table . '} DROP [' . $field . ']'); return TRUE; } @@ -541,7 +541,7 @@ public function addUniqueKey($table, $name, $fields) { throw new SchemaObjectExistsException("Cannot add unique key '$name' to table '$table': unique key already exists."); } - $this->connection->query('ALTER TABLE {' . $table . '} ADD UNIQUE KEY `' . $name . '` (' . $this->createKeySql($fields) . ')'); + $this->connection->query('ALTER TABLE {' . $table . '} ADD UNIQUE KEY [' . $name . '] (' . $this->createKeySql($fields) . ')'); } /** @@ -552,7 +552,7 @@ public function dropUniqueKey($table, $name) { return FALSE; } - $this->connection->query('ALTER TABLE {' . $table . '} DROP KEY `' . $name . '`'); + $this->connection->query('ALTER TABLE {' . $table . '} DROP KEY [' . $name . ']'); return TRUE; } @@ -570,7 +570,7 @@ public function addIndex($table, $name, $fields, array $spec) { $spec['indexes'][$name] = $fields; $indexes = $this->getNormalizedIndexes($spec); - $this->connection->query('ALTER TABLE {' . $table . '} ADD INDEX `' . $name . '` (' . $this->createKeySql($indexes[$name]) . ')'); + $this->connection->query('ALTER TABLE {' . $table . '} ADD INDEX [' . $name . '] (' . $this->createKeySql($indexes[$name]) . ')'); } /** @@ -581,7 +581,7 @@ public function dropIndex($table, $name) { return FALSE; } - $this->connection->query('ALTER TABLE {' . $table . '} DROP INDEX `' . $name . '`'); + $this->connection->query('ALTER TABLE {' . $table . '} DROP INDEX [' . $name . ']'); return TRUE; } @@ -629,7 +629,7 @@ public function changeField($table, $field, $field_new, $spec, $keys_new = []) { $this->ensureNotNullPrimaryKey($keys_new['primary key'], [$field_new => $spec]); } - $sql = 'ALTER TABLE {' . $table . '} CHANGE `' . $field . '` ' . $this->createFieldSql($field_new, $this->processField($spec)); + $sql = 'ALTER TABLE {' . $table . '} CHANGE [' . $field . '] ' . $this->createFieldSql($field_new, $this->processField($spec)); if ($keys_sql = $this->createKeysSql($keys_new)) { $sql .= ', ADD ' . implode(', ADD ', $keys_sql); } diff --git a/core/modules/pgsql/src/Driver/Database/pgsql/Schema.php b/core/modules/pgsql/src/Driver/Database/pgsql/Schema.php index 5cb6c569e1..470c5813e8 100644 --- a/core/modules/pgsql/src/Driver/Database/pgsql/Schema.php +++ b/core/modules/pgsql/src/Driver/Database/pgsql/Schema.php @@ -802,6 +802,7 @@ public function addUniqueKey($table, $name, $fields) { throw new SchemaObjectExistsException("Cannot add unique key '$name' to table '$table': unique key already exists."); } + $fields = array_map([$this->connection, 'escapeField'], $fields); $this->connection->query('ALTER TABLE {' . $table . '} ADD CONSTRAINT ' . $this->ensureIdentifiersLength($table, $name, 'key') . ' UNIQUE (' . implode(',', $fields) . ')'); $this->resetTableInformation($table); } @@ -918,11 +919,11 @@ public function changeField($table, $field, $field_new, $spec, $new_keys = []) { $field_info = $this->queryFieldInformation($table, $field); foreach ($field_info as $check) { - $this->connection->query('ALTER TABLE {' . $table . '} DROP CONSTRAINT "' . $check . '"'); + $this->connection->query('ALTER TABLE {' . $table . '} DROP CONSTRAINT [' . $check . ']'); } // Remove old default. - $this->connection->query('ALTER TABLE {' . $table . '} ALTER COLUMN "' . $field . '" DROP DEFAULT'); + $this->connection->query('ALTER TABLE {' . $table . '} ALTER COLUMN [' . $field . '] DROP DEFAULT'); // Convert field type. // Usually, we do this via a simple typecast 'USING fieldname::type'. But @@ -932,10 +933,10 @@ public function changeField($table, $field, $field_new, $spec, $new_keys = []) { $is_bytea = !empty($table_information->blob_fields[$field]); if ($spec['pgsql_type'] != 'bytea') { if ($is_bytea) { - $this->connection->query('ALTER TABLE {' . $table . '} ALTER "' . $field . '" TYPE ' . $field_def . ' USING convert_from("' . $field . '"' . ", 'UTF8')"); + $this->connection->query('ALTER TABLE {' . $table . '} ALTER [' . $field . '] TYPE ' . $field_def . ' USING convert_from([' . $field . ']' . ", 'UTF8')"); } else { - $this->connection->query('ALTER TABLE {' . $table . '} ALTER "' . $field . '" TYPE ' . $field_def . ' USING "' . $field . '"::' . $field_def); + $this->connection->query('ALTER TABLE {' . $table . '} ALTER [' . $field . '] TYPE ' . $field_def . ' USING [' . $field . ']::' . $field_def); } } else { @@ -944,7 +945,7 @@ public function changeField($table, $field, $field_new, $spec, $new_keys = []) { // Convert to a bytea type by using the SQL replace() function to // convert any single backslashes in the field content to double // backslashes ('\' to '\\'). - $this->connection->query('ALTER TABLE {' . $table . '} ALTER "' . $field . '" TYPE ' . $field_def . ' USING decode(replace("' . $field . '"' . ", E'\\\\', E'\\\\\\\\'), 'escape');"); + $this->connection->query('ALTER TABLE {' . $table . '} ALTER [' . $field . '] TYPE ' . $field_def . ' USING decode(replace("' . $field . '"' . ", E'\\\\', E'\\\\\\\\'), 'escape');"); } } @@ -955,7 +956,7 @@ public function changeField($table, $field, $field_new, $spec, $new_keys = []) { else { $null_action = 'DROP NOT NULL'; } - $this->connection->query('ALTER TABLE {' . $table . '} ALTER "' . $field . '" ' . $null_action); + $this->connection->query('ALTER TABLE {' . $table . '} ALTER [' . $field . '] ' . $null_action); } if (in_array($spec['pgsql_type'], ['serial', 'bigserial'])) { @@ -966,28 +967,28 @@ public function changeField($table, $field, $field_new, $spec, $new_keys = []) { $this->connection->query("CREATE SEQUENCE " . $seq); // Set sequence to maximal field value to not conflict with existing // entries. - $this->connection->query("SELECT setval('" . $seq . "', MAX(\"" . $field . '")) FROM {' . $table . "}"); - $this->connection->query('ALTER TABLE {' . $table . '} ALTER ' . $field . ' SET DEFAULT nextval(' . $this->connection->quote($seq) . ')'); + $this->connection->query("SELECT setval('" . $seq . "', MAX([" . $field . "])) FROM {" . $table . "}"); + $this->connection->query('ALTER TABLE {' . $table . '} ALTER [' . $field . '] SET DEFAULT nextval(' . $this->connection->quote($seq) . ')'); } // Rename the column if necessary. if ($field != $field_new) { - $this->connection->query('ALTER TABLE {' . $table . '} RENAME "' . $field . '" TO "' . $field_new . '"'); + $this->connection->query('ALTER TABLE {' . $table . '} RENAME [' . $field . '] TO [' . $field_new . ']'); } // Add unsigned check if necessary. if (!empty($spec['unsigned'])) { - $this->connection->query('ALTER TABLE {' . $table . '} ADD CHECK ("' . $field_new . '" >= 0)'); + $this->connection->query('ALTER TABLE {' . $table . '} ADD CHECK ([' . $field_new . '] >= 0)'); } // Add default if necessary. if (isset($spec['default'])) { - $this->connection->query('ALTER TABLE {' . $table . '} ALTER COLUMN "' . $field_new . '" SET DEFAULT ' . $this->escapeDefaultValue($spec['default'])); + $this->connection->query('ALTER TABLE {' . $table . '} ALTER COLUMN [' . $field_new . '] SET DEFAULT ' . $this->escapeDefaultValue($spec['default'])); } // Change description if necessary. if (!empty($spec['description'])) { - $this->connection->query('COMMENT ON COLUMN {' . $table . '}."' . $field_new . '" IS ' . $this->prepareComment($spec['description'])); + $this->connection->query('COMMENT ON COLUMN {' . $table . '}.[' . $field_new . '] IS ' . $this->prepareComment($spec['description'])); } if (isset($new_keys)) { diff --git a/core/modules/sqlite/src/Driver/Database/sqlite/Schema.php b/core/modules/sqlite/src/Driver/Database/sqlite/Schema.php index 02e28976af..f126556ba0 100644 --- a/core/modules/sqlite/src/Driver/Database/sqlite/Schema.php +++ b/core/modules/sqlite/src/Driver/Database/sqlite/Schema.php @@ -32,7 +32,7 @@ public function tableExists($table) { $info = $this->getPrefixInfo($table); // Don't use {} around sqlite_master table. - return (bool) $this->connection->query('SELECT 1 FROM ' . $info['schema'] . '.sqlite_master WHERE type = :type AND name = :name', [':type' => 'table', ':name' => $info['table']])->fetchField(); + return (bool) $this->connection->query('SELECT 1 FROM [' . $info['schema'] . '].sqlite_master WHERE type = :type AND name = :name', [':type' => 'table', ':name' => $info['table']])->fetchField(); } /** @@ -72,12 +72,12 @@ protected function createIndexSql($tablename, $schema) { $info = $this->getPrefixInfo($tablename); if (!empty($schema['unique keys'])) { foreach ($schema['unique keys'] as $key => $fields) { - $sql[] = 'CREATE UNIQUE INDEX ' . $info['schema'] . '.' . $info['table'] . '_' . $key . ' ON ' . $info['table'] . ' (' . $this->createKeySql($fields) . ")\n"; + $sql[] = 'CREATE UNIQUE INDEX [' . $info['schema'] . '].[' . $info['table'] . '_' . $key . '] ON [' . $info['table'] . '] (' . $this->createKeySql($fields) . ")\n"; } } if (!empty($schema['indexes'])) { foreach ($schema['indexes'] as $key => $fields) { - $sql[] = 'CREATE INDEX ' . $info['schema'] . '.' . $info['table'] . '_' . $key . ' ON ' . $info['table'] . ' (' . $this->createKeySql($fields) . ")\n"; + $sql[] = 'CREATE INDEX [' . $info['schema'] . '].[' . $info['table'] . '_' . $key . '] ON [' . $info['table'] . '] (' . $this->createKeySql($fields) . ")\n"; } } return $sql; @@ -114,10 +114,10 @@ protected function createKeySql($fields) { $return = []; foreach ($fields as $field) { if (is_array($field)) { - $return[] = $field[0]; + $return[] = '[' . $field[0] . ']'; } else { - $return[] = $field; + $return[] = '[' . $field . ']'; } } return implode(', ', $return); @@ -280,7 +280,7 @@ public function renameTable($table, $new_name) { // the table with curly braces in case the db_prefix contains a reference // to a database outside of our existing database. $info = $this->getPrefixInfo($new_name); - $this->connection->query('ALTER TABLE {' . $table . '} RENAME TO ' . $info['table']); + $this->connection->query('ALTER TABLE {' . $table . '} RENAME TO [' . $info['table'] . ']'); // Drop the indexes, there is no RENAME INDEX command in SQLite. if (!empty($schema['unique keys'])) { @@ -491,7 +491,7 @@ protected function introspectSchema($table) { ]; $info = $this->getPrefixInfo($table); - $result = $this->connection->query('PRAGMA ' . $info['schema'] . '.table_info(' . $info['table'] . ')'); + $result = $this->connection->query('PRAGMA [' . $info['schema'] . '].table_info([' . $info['table'] . '])'); foreach ($result as $row) { if (preg_match('/^([^(]+)\((.*)\)$/', $row->type, $matches)) { $type = $matches[1]; @@ -547,7 +547,7 @@ protected function introspectSchema($table) { $schema['primary key'] = array_values($schema['primary key']); $indexes = []; - $result = $this->connection->query('PRAGMA ' . $info['schema'] . '.index_list(' . $info['table'] . ')'); + $result = $this->connection->query('PRAGMA [' . $info['schema'] . '].index_list([' . $info['table'] . '])'); foreach ($result as $row) { if (strpos($row->name, 'sqlite_autoindex_') !== 0) { $indexes[] = [ @@ -560,7 +560,7 @@ protected function introspectSchema($table) { $name = $index['name']; // Get index name without prefix. $index_name = substr($name, strlen($info['table']) + 1); - $result = $this->connection->query('PRAGMA ' . $info['schema'] . '.index_info(' . $name . ')'); + $result = $this->connection->query('PRAGMA [' . $info['schema'] . '].index_info([' . $name . '])'); foreach ($result as $row) { $schema[$index['schema_key']][$index_name][] = $row->name; } @@ -701,7 +701,7 @@ public function addIndex($table, $name, $fields, array $spec) { public function indexExists($table, $name) { $info = $this->getPrefixInfo($table); - return $this->connection->query('PRAGMA ' . $info['schema'] . '.index_info(' . $info['table'] . '_' . $name . ')')->fetchField() != ''; + return $this->connection->query('PRAGMA [' . $info['schema'] . '].index_info([' . $info['table'] . '_' . $name . '])')->fetchField() != ''; } /** @@ -714,7 +714,7 @@ public function dropIndex($table, $name) { $info = $this->getPrefixInfo($table); - $this->connection->query('DROP INDEX ' . $info['schema'] . '.' . $info['table'] . '_' . $name); + $this->connection->query('DROP INDEX [' . $info['schema'] . '].[' . $info['table'] . '_' . $name . ']'); return TRUE; } @@ -746,7 +746,7 @@ public function dropUniqueKey($table, $name) { $info = $this->getPrefixInfo($table); - $this->connection->query('DROP INDEX ' . $info['schema'] . '.' . $info['table'] . '_' . $name); + $this->connection->query('DROP INDEX [' . $info['schema'] . '].[' . $info['table'] . '_' . $name . ']'); return TRUE; } @@ -825,7 +825,7 @@ public function findTables($table_expression) { // Can't use query placeholders for the schema because the query would // have to be :prefixsqlite_master, which does not work. We also need to // ignore the internal SQLite tables. - $result = $this->connection->query("SELECT name FROM " . $schema . ".sqlite_master WHERE type = :type AND name LIKE :table_name AND name NOT LIKE :pattern", [ + $result = $this->connection->query("SELECT name FROM [" . $schema . "].sqlite_master WHERE type = :type AND name LIKE :table_name AND name NOT LIKE :pattern", [ ':type' => 'table', ':table_name' => $table_expression, ':pattern' => 'sqlite_%', diff --git a/core/tests/Drupal/KernelTests/Core/Database/SchemaTest.php b/core/tests/Drupal/KernelTests/Core/Database/SchemaTest.php index 72b40e305c..b34da7cdf7 100644 --- a/core/tests/Drupal/KernelTests/Core/Database/SchemaTest.php +++ b/core/tests/Drupal/KernelTests/Core/Database/SchemaTest.php @@ -1323,4 +1323,113 @@ public function testDefaultAfterAlter() { $this->assertSame('default value', $result->column7); } + /** + * Tests handling with reserved keywords for naming tables, fields and more. + */ + public function testReservedKeywordsForNaming() { + $table_specification = [ + 'description' => 'A test table with an ANSI reserved keywords for naming.', + 'fields' => [ + 'primary' => [ + 'description' => 'Simple unique ID.', + 'type' => 'int', + 'not null' => TRUE, + ], + 'update' => [ + 'description' => 'A column with reserved name.', + 'type' => 'varchar', + 'length' => 255, + ], + ], + 'primary key' => ['primary'], + 'unique keys' => [ + 'having' => ['update'], + ], + 'indexes' => [ + 'in' => ['primary', 'update'], + ], + ]; + + // Creating a table. + $table_name = 'select'; + $this->schema->createTable($table_name, $table_specification); + $this->assertTrue($this->schema->tableExists($table_name)); + + // Finding all tables. + $tables = $this->schema->findTables('%'); + sort($tables); + $this->assertEquals(['config', 'select'], $tables); + + // Renaming a table. + $table_name_new = 'from'; + $this->schema->renameTable($table_name, $table_name_new); + $this->assertFalse($this->schema->tableExists($table_name)); + $this->assertTrue($this->schema->tableExists($table_name_new)); + + // Adding a field. + $field_name = 'delete'; + $this->schema->addField($table_name_new, $field_name, ['type' => 'int', 'not null' => TRUE]); + $this->assertTrue($this->schema->fieldExists($table_name_new, $field_name)); + + // Dropping a primary key. + $this->schema->dropPrimaryKey($table_name_new); + + // Adding a primary key. + $this->schema->addPrimaryKey($table_name_new, [$field_name]); + + // Check the primary key columns. + $find_primary_key_columns = new \ReflectionMethod(get_class($this->schema), 'findPrimaryKeyColumns'); + $find_primary_key_columns->setAccessible(TRUE); + $this->assertEquals([$field_name], $find_primary_key_columns->invoke($this->schema, $table_name_new)); + + // Dropping a primary key. + $this->schema->dropPrimaryKey($table_name_new); + + // Changing a field. + $field_name_new = 'where'; + $this->schema->changeField($table_name_new, $field_name, $field_name_new, ['type' => 'int', 'not null' => FALSE]); + $this->assertFalse($this->schema->fieldExists($table_name_new, $field_name)); + $this->assertTrue($this->schema->fieldExists($table_name_new, $field_name_new)); + + // Adding an unique key + $unique_key_name = $unique_key_introspect_name = 'unique'; + $this->schema->addUniqueKey($table_name_new, $unique_key_name, [$field_name_new]); + + // Check the unique key columns. + $introspect_index_schema = new \ReflectionMethod(get_class($this->schema), 'introspectIndexSchema'); + $introspect_index_schema->setAccessible(TRUE); + if ($this->connection->databaseType() == 'pgsql') { + $ensure_identifiers_length = new \ReflectionMethod(get_class($this->schema), 'ensureIdentifiersLength'); + $ensure_identifiers_length->setAccessible(TRUE); + $unique_key_introspect_name = $ensure_identifiers_length->invoke($this->schema, $table_name_new, $unique_key_name, 'key'); + } + $this->assertEquals([$field_name_new], $introspect_index_schema->invoke($this->schema, $table_name_new)['unique keys'][$unique_key_introspect_name]); + + // Dropping an unique key + $this->schema->dropUniqueKey($table_name_new, $unique_key_name); + + // Dropping a field. + $this->schema->dropField($table_name_new, $field_name_new); + $this->assertFalse($this->schema->fieldExists($table_name_new, $field_name_new)); + + // Adding an index. + $index_name = $index_introspect_name = 'index'; + $this->schema->addIndex($table_name_new, $index_name, ['update'], $table_specification); + $this->assertTrue($this->schema->indexExists($table_name_new, $index_name)); + + // Check the index columns. + if ($this->connection->databaseType() == 'pgsql') { + $index_introspect_name = $ensure_identifiers_length->invoke($this->schema, $table_name_new, $index_name, 'idx'); + } + $this->assertEquals(['update'], $introspect_index_schema->invoke($this->schema, $table_name_new)['indexes'][$index_introspect_name]); + + // Dropping an index. + $this->schema->dropIndex($table_name_new, $index_name); + $this->assertFalse($this->schema->indexExists($table_name_new, $index_name)); + + // Dropping a table. + $this->schema->dropTable($table_name_new); + $this->assertFalse($this->schema->tableExists($table_name_new)); + } + }