View source
<?php
namespace Drupal\Core\Database\Driver\mysql;
use Drupal\Core\Database\SchemaException;
use Drupal\Core\Database\SchemaObjectExistsException;
use Drupal\Core\Database\SchemaObjectDoesNotExistException;
use Drupal\Core\Database\Schema as DatabaseSchema;
use Drupal\Component\Utility\Unicode;
class Schema extends DatabaseSchema {
const COMMENT_MAX_TABLE = 60;
const COMMENT_MAX_COLUMN = 255;
protected $mysqlStringTypes = [
'VARCHAR',
'CHAR',
'TINYTEXT',
'MEDIUMTEXT',
'LONGTEXT',
'TEXT',
];
protected function getPrefixInfo($table = 'default', $add_prefix = TRUE) {
$info = [
'prefix' => $this->connection
->tablePrefix($table),
];
if ($add_prefix) {
$table = $info['prefix'] . $table;
}
if (($pos = strpos($table, '.')) !== FALSE) {
$info['database'] = substr($table, 0, $pos);
$info['table'] = substr($table, ++$pos);
}
else {
$info['database'] = $this->connection
->getConnectionOptions()['database'];
$info['table'] = $table;
}
return $info;
}
protected function buildTableNameCondition($table_name, $operator = '=', $add_prefix = TRUE) {
$table_info = $this
->getPrefixInfo($table_name, $add_prefix);
$condition = $this->connection
->condition('AND');
$condition
->condition('table_schema', $table_info['database']);
$condition
->condition('table_name', $table_info['table'], $operator);
return $condition;
}
protected function createTableSql($name, $table) {
$info = $this->connection
->getConnectionOptions();
$table += [
'mysql_engine' => 'InnoDB',
'mysql_character_set' => 'utf8mb4',
];
$sql = "CREATE TABLE {" . $name . "} (\n";
foreach ($table['fields'] as $field_name => $field) {
$sql .= $this
->createFieldSql($field_name, $this
->processField($field)) . ", \n";
}
if (!empty($table['primary key']) && is_array($table['primary key'])) {
$this
->ensureNotNullPrimaryKey($table['primary key'], $table['fields']);
}
$keys = $this
->createKeysSql($table);
if (count($keys)) {
$sql .= implode(", \n", $keys) . ", \n";
}
$sql = substr($sql, 0, -3) . "\n) ";
$sql .= 'ENGINE = ' . $table['mysql_engine'] . ' DEFAULT CHARACTER SET ' . $table['mysql_character_set'];
if (!empty($info['collation'])) {
$sql .= ' COLLATE ' . $info['collation'];
}
if (!empty($table['description'])) {
$sql .= ' COMMENT ' . $this
->prepareComment($table['description'], self::COMMENT_MAX_TABLE);
}
return [
$sql,
];
}
protected function createFieldSql($name, $spec) {
$sql = "`" . $name . "` " . $spec['mysql_type'];
if (in_array($spec['mysql_type'], $this->mysqlStringTypes)) {
if (isset($spec['length'])) {
$sql .= '(' . $spec['length'] . ')';
}
if (isset($spec['type']) && $spec['type'] == 'varchar_ascii') {
$sql .= ' CHARACTER SET ascii';
}
if (!empty($spec['binary'])) {
$sql .= ' BINARY';
}
elseif (isset($spec['type']) && $spec['type'] == 'varchar_ascii') {
$sql .= ' COLLATE ascii_general_ci';
}
}
elseif (isset($spec['precision']) && isset($spec['scale'])) {
$sql .= '(' . $spec['precision'] . ', ' . $spec['scale'] . ')';
}
if (!empty($spec['unsigned'])) {
$sql .= ' unsigned';
}
if (isset($spec['not null'])) {
if ($spec['not null']) {
$sql .= ' NOT NULL';
}
else {
$sql .= ' NULL';
}
}
if (!empty($spec['auto_increment'])) {
$sql .= ' auto_increment';
}
if (array_key_exists('default', $spec)) {
$sql .= ' DEFAULT ' . $this
->escapeDefaultValue($spec['default']);
}
if (empty($spec['not null']) && !isset($spec['default'])) {
$sql .= ' DEFAULT NULL';
}
if (!empty($spec['description'])) {
$sql .= ' COMMENT ' . $this
->prepareComment($spec['description'], self::COMMENT_MAX_COLUMN);
}
return $sql;
}
protected function processField($field) {
if (!isset($field['size'])) {
$field['size'] = 'normal';
}
if (isset($field['mysql_type'])) {
$field['mysql_type'] = mb_strtoupper($field['mysql_type']);
}
else {
$map = $this
->getFieldTypeMap();
$field['mysql_type'] = $map[$field['type'] . ':' . $field['size']];
}
if (isset($field['type']) && $field['type'] == 'serial') {
$field['auto_increment'] = TRUE;
}
return $field;
}
public function getFieldTypeMap() {
static $map = [
'varchar_ascii:normal' => 'VARCHAR',
'varchar:normal' => 'VARCHAR',
'char:normal' => 'CHAR',
'text:tiny' => 'TINYTEXT',
'text:small' => 'TINYTEXT',
'text:medium' => 'MEDIUMTEXT',
'text:big' => 'LONGTEXT',
'text:normal' => 'TEXT',
'serial:tiny' => 'TINYINT',
'serial:small' => 'SMALLINT',
'serial:medium' => 'MEDIUMINT',
'serial:big' => 'BIGINT',
'serial:normal' => 'INT',
'int:tiny' => 'TINYINT',
'int:small' => 'SMALLINT',
'int:medium' => 'MEDIUMINT',
'int:big' => 'BIGINT',
'int:normal' => 'INT',
'float:tiny' => 'FLOAT',
'float:small' => 'FLOAT',
'float:medium' => 'FLOAT',
'float:big' => 'DOUBLE',
'float:normal' => 'FLOAT',
'numeric:normal' => 'DECIMAL',
'blob:big' => 'LONGBLOB',
'blob:normal' => 'BLOB',
];
return $map;
}
protected function createKeysSql($spec) {
$keys = [];
if (!empty($spec['primary key'])) {
$keys[] = 'PRIMARY KEY (' . $this
->createKeySql($spec['primary key']) . ')';
}
if (!empty($spec['unique keys'])) {
foreach ($spec['unique keys'] as $key => $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) . ')';
}
}
return $keys;
}
protected function getNormalizedIndexes(array $spec) {
$indexes = isset($spec['indexes']) ? $spec['indexes'] : [];
foreach ($indexes as $index_name => $index_fields) {
foreach ($index_fields as $index_key => $index_field) {
$field_name = is_array($index_field) ? $index_field[0] : $index_field;
if (isset($spec['fields'][$field_name])) {
$mysql_field = $this
->processField($spec['fields'][$field_name]);
if (in_array($mysql_field['mysql_type'], $this->mysqlStringTypes)) {
if ((!isset($mysql_field['type']) || $mysql_field['type'] != 'varchar_ascii') && (!isset($mysql_field['length']) || $mysql_field['length'] > 191)) {
$this
->shortenIndex($indexes[$index_name][$index_key]);
}
}
}
else {
throw new SchemaException("MySQL needs the '{$field_name}' field specification in order to normalize the '{$index_name}' index");
}
}
}
return $indexes;
}
protected function shortenIndex(&$index) {
if (is_array($index)) {
if ($index[1] > 191) {
$index[1] = 191;
}
}
else {
$index = [
$index,
191,
];
}
}
protected function createKeySql($fields) {
$return = [];
foreach ($fields as $field) {
if (is_array($field)) {
$return[] = '`' . $field[0] . '`(' . $field[1] . ')';
}
else {
$return[] = '`' . $field . '`';
}
}
return implode(', ', $return);
}
public function renameTable($table, $new_name) {
if (!$this
->tableExists($table)) {
throw new SchemaObjectDoesNotExistException("Cannot rename '{$table}' to '{$new_name}': table '{$table}' doesn't exist.");
}
if ($this
->tableExists($new_name)) {
throw new SchemaObjectExistsException("Cannot rename '{$table}' to '{$new_name}': table '{$new_name}' already exists.");
}
$info = $this
->getPrefixInfo($new_name);
$this->connection
->query('ALTER TABLE {' . $table . '} RENAME TO `' . $info['table'] . '`');
}
public function dropTable($table) {
if (!$this
->tableExists($table)) {
return FALSE;
}
$this->connection
->query('DROP TABLE {' . $table . '}');
return TRUE;
}
public function addField($table, $field, $spec, $keys_new = []) {
if (!$this
->tableExists($table)) {
throw new SchemaObjectDoesNotExistException("Cannot add field '{$table}.{$field}': table doesn't exist.");
}
if ($this
->fieldExists($table, $field)) {
throw new SchemaObjectExistsException("Cannot add field '{$table}.{$field}': field already exists.");
}
$is_primary_key = isset($keys_new['primary key']) && in_array($field, $keys_new['primary key'], TRUE);
if ($is_primary_key) {
$this
->ensureNotNullPrimaryKey($keys_new['primary key'], [
$field => $spec,
]);
}
$fixnull = FALSE;
if (!empty($spec['not null']) && !isset($spec['default']) && !$is_primary_key) {
$fixnull = TRUE;
$spec['not null'] = FALSE;
}
$query = 'ALTER TABLE {' . $table . '} ADD ';
$query .= $this
->createFieldSql($field, $this
->processField($spec));
if ($keys_sql = $this
->createKeysSql($keys_new)) {
if (isset($keys_new['primary key']) && $this
->indexExists($table, 'PRIMARY')) {
$query .= ', DROP PRIMARY KEY';
}
$query .= ', ADD ' . implode(', ADD ', $keys_sql);
}
$this->connection
->query($query);
if (isset($spec['initial_from_field'])) {
if (isset($spec['initial'])) {
$expression = 'COALESCE(' . $spec['initial_from_field'] . ', :default_initial_value)';
$arguments = [
':default_initial_value' => $spec['initial'],
];
}
else {
$expression = $spec['initial_from_field'];
$arguments = [];
}
$this->connection
->update($table)
->expression($field, $expression, $arguments)
->execute();
}
elseif (isset($spec['initial'])) {
$this->connection
->update($table)
->fields([
$field => $spec['initial'],
])
->execute();
}
if ($fixnull) {
$spec['not null'] = TRUE;
$this
->changeField($table, $field, $field, $spec);
}
}
public function dropField($table, $field) {
if (!$this
->fieldExists($table, $field)) {
return FALSE;
}
$primary_key = $this
->findPrimaryKeyColumns($table);
if (count($primary_key) > 1 && in_array($field, $primary_key, TRUE)) {
$this
->dropPrimaryKey($table);
}
$this->connection
->query('ALTER TABLE {' . $table . '} DROP `' . $field . '`');
return TRUE;
}
public function indexExists($table, $name) {
$row = $this->connection
->query('SHOW INDEX FROM {' . $table . '} WHERE key_name = ' . $this->connection
->quote($name))
->fetchAssoc();
return isset($row['Key_name']);
}
public function addPrimaryKey($table, $fields) {
if (!$this
->tableExists($table)) {
throw new SchemaObjectDoesNotExistException("Cannot add primary key to table '{$table}': table doesn't exist.");
}
if ($this
->indexExists($table, 'PRIMARY')) {
throw new SchemaObjectExistsException("Cannot add primary key to table '{$table}': primary key already exists.");
}
$this->connection
->query('ALTER TABLE {' . $table . '} ADD PRIMARY KEY (' . $this
->createKeySql($fields) . ')');
}
public function dropPrimaryKey($table) {
if (!$this
->indexExists($table, 'PRIMARY')) {
return FALSE;
}
$this->connection
->query('ALTER TABLE {' . $table . '} DROP PRIMARY KEY');
return TRUE;
}
protected function findPrimaryKeyColumns($table) {
if (!$this
->tableExists($table)) {
return FALSE;
}
$result = $this->connection
->query("SHOW KEYS FROM {" . $table . "} WHERE Key_name = 'PRIMARY'")
->fetchAllAssoc('Column_name');
return array_keys($result);
}
public function addUniqueKey($table, $name, $fields) {
if (!$this
->tableExists($table)) {
throw new SchemaObjectDoesNotExistException("Cannot add unique key '{$name}' to table '{$table}': table doesn't exist.");
}
if ($this
->indexExists($table, $name)) {
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) . ')');
}
public function dropUniqueKey($table, $name) {
if (!$this
->indexExists($table, $name)) {
return FALSE;
}
$this->connection
->query('ALTER TABLE {' . $table . '} DROP KEY `' . $name . '`');
return TRUE;
}
public function addIndex($table, $name, $fields, array $spec) {
if (!$this
->tableExists($table)) {
throw new SchemaObjectDoesNotExistException("Cannot add index '{$name}' to table '{$table}': table doesn't exist.");
}
if ($this
->indexExists($table, $name)) {
throw new SchemaObjectExistsException("Cannot add index '{$name}' to table '{$table}': index already exists.");
}
$spec['indexes'][$name] = $fields;
$indexes = $this
->getNormalizedIndexes($spec);
$this->connection
->query('ALTER TABLE {' . $table . '} ADD INDEX `' . $name . '` (' . $this
->createKeySql($indexes[$name]) . ')');
}
public function dropIndex($table, $name) {
if (!$this
->indexExists($table, $name)) {
return FALSE;
}
$this->connection
->query('ALTER TABLE {' . $table . '} DROP INDEX `' . $name . '`');
return TRUE;
}
protected function introspectIndexSchema($table) {
if (!$this
->tableExists($table)) {
throw new SchemaObjectDoesNotExistException("The table {$table} doesn't exist.");
}
$index_schema = [
'primary key' => [],
'unique keys' => [],
'indexes' => [],
];
$result = $this->connection
->query('SHOW INDEX FROM {' . $table . '}')
->fetchAll();
foreach ($result as $row) {
if ($row->Key_name === 'PRIMARY') {
$index_schema['primary key'][] = $row->Column_name;
}
elseif ($row->Non_unique == 0) {
$index_schema['unique keys'][$row->Key_name][] = $row->Column_name;
}
else {
$index_schema['indexes'][$row->Key_name][] = $row->Column_name;
}
}
return $index_schema;
}
public function changeField($table, $field, $field_new, $spec, $keys_new = []) {
if (!$this
->fieldExists($table, $field)) {
throw new SchemaObjectDoesNotExistException("Cannot change the definition of field '{$table}.{$field}': field doesn't exist.");
}
if ($field != $field_new && $this
->fieldExists($table, $field_new)) {
throw new SchemaObjectExistsException("Cannot rename field '{$table}.{$field}' to '{$field_new}': target field already exists.");
}
if (isset($keys_new['primary key']) && in_array($field_new, $keys_new['primary key'], TRUE)) {
$this
->ensureNotNullPrimaryKey($keys_new['primary key'], [
$field_new => $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);
}
$this->connection
->query($sql);
}
public function prepareComment($comment, $length = NULL) {
if (isset($length)) {
$comment = Unicode::truncate($this->connection
->prefixTables($comment), $length, TRUE, TRUE);
}
$comment = strtr($comment, [
';' => '.',
]);
return $this->connection
->quote($comment);
}
public function getComment($table, $column = NULL) {
$condition = $this
->buildTableNameCondition($table);
if (isset($column)) {
$condition
->condition('column_name', $column);
$condition
->compile($this->connection, $this);
return $this->connection
->query("SELECT column_comment AS column_comment FROM information_schema.columns WHERE " . (string) $condition, $condition
->arguments())
->fetchField();
}
$condition
->compile($this->connection, $this);
$comment = $this->connection
->query("SELECT table_comment AS table_comment FROM information_schema.tables WHERE " . (string) $condition, $condition
->arguments())
->fetchField();
return preg_replace('/; InnoDB free:.*$/', '', $comment);
}
public function tableExists($table) {
try {
$this->connection
->queryRange("SELECT 1 FROM {" . $table . "}", 0, 1);
return TRUE;
} catch (\Exception $e) {
return FALSE;
}
}
public function fieldExists($table, $column) {
try {
$this->connection
->queryRange("SELECT {$column} FROM {" . $table . "}", 0, 1);
return TRUE;
} catch (\Exception $e) {
return FALSE;
}
}
}