Newer
Older
Dries Buytaert
committed
<?php
/**
* @file
* Definition of Drupal\Core\Database\Driver\mysql\Schema
*/
namespace Drupal\Core\Database\Driver\mysql;
Dries Buytaert
committed
use Drupal\Component\Utility\String;
use Drupal\Core\Database\Database;
use Drupal\Core\Database\Query\Condition;
use Drupal\Core\Database\SchemaObjectExistsException;
use Drupal\Core\Database\SchemaObjectDoesNotExistException;
use Drupal\Core\Database\Schema as DatabaseSchema;
Alex Pott
committed
use Drupal\Component\Utility\Unicode;
Dries Buytaert
committed
/**
* @addtogroup schemaapi
Dries Buytaert
committed
* @{
*/
class Schema extends DatabaseSchema {
Dries Buytaert
committed
/**
* Maximum length of a table comment in MySQL.
*/
const COMMENT_MAX_TABLE = 60;
/**
* Maximum length of a column comment in MySQL.
*/
const COMMENT_MAX_COLUMN = 255;
Dries Buytaert
committed
* Get information about the table and database name from the prefix.
*
* @return
* A keyed array with information about the database, table name and prefix.
*/
Angie Byron
committed
protected function getPrefixInfo($table = 'default', $add_prefix = TRUE) {
$info = array('prefix' => $this->connection->tablePrefix($table));
Angie Byron
committed
if ($add_prefix) {
$table = $info['prefix'] . $table;
}
if (($pos = strpos($table, '.')) !== FALSE) {
$info['database'] = substr($table, 0, $pos);
$info['table'] = substr($table, ++$pos);
}
else {
$db_info = Database::getConnectionInfo();
$info['database'] = $db_info[$this->connection->getTarget()]['database'];
Angie Byron
committed
$info['table'] = $table;
}
return $info;
}
/**
* Build a condition to match a table name against a standard information_schema.
*
* MySQL uses databases like schemas rather than catalogs so when we build
* a condition to query the information_schema.tables, we set the default
* database as the schema unless specified otherwise, and exclude table_catalog
* from the condition criteria.
*/
Angie Byron
committed
protected function buildTableNameCondition($table_name, $operator = '=', $add_prefix = TRUE) {
$table_info = $this->getPrefixInfo($table_name, $add_prefix);
Dries Buytaert
committed
$condition = new Condition('AND');
$condition->condition('table_schema', $table_info['database']);
$condition->condition('table_name', $table_info['table'], $operator);
return $condition;
}
Dries Buytaert
committed
/**
* Generate SQL to create a new table from a Drupal schema definition.
*
* @param $name
* The name of the table to create.
* @param $table
* A Schema API table definition array.
* @return
* An array of SQL statements to create the table.
*/
protected function createTableSql($name, $table) {
Dries Buytaert
committed
$info = $this->connection->getConnectionOptions();
// Provide defaults if needed.
Angie Byron
committed
$table += array(
'mysql_engine' => 'InnoDB',
Dries Buytaert
committed
'mysql_character_set' => 'utf8',
Angie Byron
committed
);
Dries Buytaert
committed
$sql = "CREATE TABLE {" . $name . "} (\n";
Dries Buytaert
committed
// Add the SQL statement for each field.
foreach ($table['fields'] as $field_name => $field) {
$sql .= $this->createFieldSql($field_name, $this->processField($field)) . ", \n";
}
Dries Buytaert
committed
// Process keys & indexes.
$keys = $this->createKeysSql($table);
if (count($keys)) {
$sql .= implode(", \n", $keys) . ", \n";
}
Dries Buytaert
committed
// Remove the last comma and space.
$sql = substr($sql, 0, -3) . "\n) ";
Angie Byron
committed
$sql .= 'ENGINE = ' . $table['mysql_engine'] . ' DEFAULT CHARACTER SET ' . $table['mysql_character_set'];
Dries Buytaert
committed
// By default, MySQL uses the default collation for new tables, which is
// 'utf8_general_ci' for utf8. If an alternate collation has been set, it
// needs to be explicitly specified.
// @see DatabaseConnection_mysql
if (!empty($info['collation'])) {
$sql .= ' COLLATE ' . $info['collation'];
}
// Add table comment.
if (!empty($table['description'])) {
$sql .= ' COMMENT ' . $this->prepareComment($table['description'], self::COMMENT_MAX_TABLE);
}
Dries Buytaert
committed
return array($sql);
}
/**
* Create an SQL string for a field to be used in table creation or alteration.
*
* Before passing a field out of a schema definition into this function it has
* to be processed by _db_process_field().
*
* @param $name
* Name of the field.
* @param $spec
* The field specification, as per the schema data structure format.
*/
protected function createFieldSql($name, $spec) {
$sql = "`" . $name . "` " . $spec['mysql_type'];
if (in_array($spec['mysql_type'], array('VARCHAR', 'CHAR', 'TINYTEXT', 'MEDIUMTEXT', 'LONGTEXT', 'TEXT'))) {
if (isset($spec['length'])) {
$sql .= '(' . $spec['length'] . ')';
}
if (!empty($spec['binary'])) {
$sql .= ' BINARY';
}
Dries Buytaert
committed
}
elseif (isset($spec['precision']) && isset($spec['scale'])) {
$sql .= '(' . $spec['precision'] . ', ' . $spec['scale'] . ')';
}
Dries Buytaert
committed
if (!empty($spec['unsigned'])) {
$sql .= ' unsigned';
}
Angie Byron
committed
if (isset($spec['not null'])) {
if ($spec['not null']) {
$sql .= ' NOT NULL';
}
else {
$sql .= ' NULL';
}
Dries Buytaert
committed
}
Dries Buytaert
committed
if (!empty($spec['auto_increment'])) {
$sql .= ' auto_increment';
}
// $spec['default'] can be NULL, so we explicitly check for the key here.
Dries Buytaert
committed
if (array_key_exists('default', $spec)) {
$sql .= ' DEFAULT ' . $this->escapeDefaultValue($spec['default']);
Dries Buytaert
committed
}
Dries Buytaert
committed
if (empty($spec['not null']) && !isset($spec['default'])) {
$sql .= ' DEFAULT NULL';
}
// Add column comment.
if (!empty($spec['description'])) {
$sql .= ' COMMENT ' . $this->prepareComment($spec['description'], self::COMMENT_MAX_COLUMN);
}
Dries Buytaert
committed
return $sql;
}
Dries Buytaert
committed
/**
* Set database-engine specific properties for a field.
*
* @param $field
* A field description array, as specified in the schema documentation.
*/
protected function processField($field) {
Dries Buytaert
committed
if (!isset($field['size'])) {
$field['size'] = 'normal';
}
Dries Buytaert
committed
// Set the correct database-engine specific datatype.
Angie Byron
committed
// In case one is already provided, force it to uppercase.
if (isset($field['mysql_type'])) {
$field['mysql_type'] = Unicode::strtoupper($field['mysql_type']);
Angie Byron
committed
}
else {
$map = $this->getFieldTypeMap();
Dries Buytaert
committed
$field['mysql_type'] = $map[$field['type'] . ':' . $field['size']];
}
Angie Byron
committed
if (isset($field['type']) && $field['type'] == 'serial') {
Dries Buytaert
committed
$field['auto_increment'] = TRUE;
}
Dries Buytaert
committed
return $field;
}
public function getFieldTypeMap() {
Dries Buytaert
committed
// Put :normal last so it gets preserved by array_flip. This makes
Dries Buytaert
committed
// it much easier for modules (such as schema.module) to map
// database types back into schema types.
// $map does not use drupal_static as its value never changes.
Dries Buytaert
committed
static $map = array(
'varchar:normal' => 'VARCHAR',
'char:normal' => 'CHAR',
Dries Buytaert
committed
'text:tiny' => 'TINYTEXT',
'text:small' => 'TINYTEXT',
'text:medium' => 'MEDIUMTEXT',
'text:big' => 'LONGTEXT',
'text:normal' => 'TEXT',
Dries Buytaert
committed
'serial:tiny' => 'TINYINT',
'serial:small' => 'SMALLINT',
'serial:medium' => 'MEDIUMINT',
'serial:big' => 'BIGINT',
'serial:normal' => 'INT',
Dries Buytaert
committed
'int:tiny' => 'TINYINT',
'int:small' => 'SMALLINT',
'int:medium' => 'MEDIUMINT',
'int:big' => 'BIGINT',
'int:normal' => 'INT',
Dries Buytaert
committed
'float:tiny' => 'FLOAT',
'float:small' => 'FLOAT',
'float:medium' => 'FLOAT',
'float:big' => 'DOUBLE',
'float:normal' => 'FLOAT',
Dries Buytaert
committed
'numeric:normal' => 'DECIMAL',
Dries Buytaert
committed
'blob:big' => 'LONGBLOB',
'blob:normal' => 'BLOB',
);
return $map;
}
Dries Buytaert
committed
protected function createKeysSql($spec) {
$keys = array();
if (!empty($spec['primary key'])) {
$keys[] = 'PRIMARY KEY (' . $this->createKeySql($spec['primary key']) . ')';
Dries Buytaert
committed
}
if (!empty($spec['unique keys'])) {
foreach ($spec['unique keys'] as $key => $fields) {
$keys[] = 'UNIQUE KEY `' . $key . '` (' . $this->createKeySql($fields) . ')';
Dries Buytaert
committed
}
}
if (!empty($spec['indexes'])) {
foreach ($spec['indexes'] as $index => $fields) {
$keys[] = 'INDEX `' . $index . '` (' . $this->createKeySql($fields) . ')';
Dries Buytaert
committed
}
}
return $keys;
}
Dries Buytaert
committed
protected function createKeySql($fields) {
Dries Buytaert
committed
$return = array();
Dries Buytaert
committed
foreach ($fields as $field) {
if (is_array($field)) {
Dries Buytaert
committed
$return[] = '`' . $field[0] . '`(' . $field[1] . ')';
Dries Buytaert
committed
}
else {
Dries Buytaert
committed
$return[] = '`' . $field . '`';
Dries Buytaert
committed
}
}
Dries Buytaert
committed
return implode(', ', $return);
Dries Buytaert
committed
}
Dries Buytaert
committed
public function renameTable($table, $new_name) {
Dries Buytaert
committed
if (!$this->tableExists($table)) {
Angie Byron
committed
throw new SchemaObjectDoesNotExistException(t("Cannot rename @table to @table_new: table @table doesn't exist.", array('@table' => $table, '@table_new' => $new_name)));
Dries Buytaert
committed
}
if ($this->tableExists($new_name)) {
Angie Byron
committed
throw new SchemaObjectExistsException(t("Cannot rename @table to @table_new: table @table_new already exists.", array('@table' => $table, '@table_new' => $new_name)));
Dries Buytaert
committed
}
$info = $this->getPrefixInfo($new_name);
return $this->connection->query('ALTER TABLE {' . $table . '} RENAME TO `' . $info['table'] . '`');
Dries Buytaert
committed
}
Dries Buytaert
committed
public function dropTable($table) {
Dries Buytaert
committed
if (!$this->tableExists($table)) {
return FALSE;
}
Dries Buytaert
committed
$this->connection->query('DROP TABLE {' . $table . '}');
Dries Buytaert
committed
return TRUE;
Dries Buytaert
committed
}
/**
* {@inheritdoc}
*/
public function copyTable($source, $destination) {
if (!$this->tableExists($source)) {
throw new SchemaObjectDoesNotExistException(String::format("Cannot copy @source to @destination: table @source doesn't exist.", array('@source' => $source, '@destination' => $destination)));
}
if ($this->tableExists($destination)) {
throw new SchemaObjectExistsException(String::format("Cannot copy @source to @destination: table @destination already exists.", array('@source' => $source, '@destination' => $destination)));
}
$info = $this->getPrefixInfo($destination);
return $this->connection->query('CREATE TABLE `' . $info['table'] . '` LIKE {' . $source . '}');
}
Dries Buytaert
committed
public function addField($table, $field, $spec, $keys_new = array()) {
Dries Buytaert
committed
if (!$this->tableExists($table)) {
Angie Byron
committed
throw new SchemaObjectDoesNotExistException(t("Cannot add field @table.@field: table doesn't exist.", array('@field' => $field, '@table' => $table)));
Dries Buytaert
committed
}
Dries Buytaert
committed
if ($this->fieldExists($table, $field)) {
Angie Byron
committed
throw new SchemaObjectExistsException(t("Cannot add field @table.@field: field already exists.", array('@field' => $field, '@table' => $table)));
Dries Buytaert
committed
}
Dries Buytaert
committed
$fixnull = FALSE;
if (!empty($spec['not null']) && !isset($spec['default'])) {
$fixnull = TRUE;
$spec['not null'] = FALSE;
}
$query = 'ALTER TABLE {' . $table . '} ADD ';
$query .= $this->createFieldSql($field, $this->processField($spec));
Dries Buytaert
committed
if ($keys_sql = $this->createKeysSql($keys_new)) {
$query .= ', ADD ' . implode(', ADD ', $keys_sql);
Dries Buytaert
committed
}
Dries Buytaert
committed
$this->connection->query($query);
Dries Buytaert
committed
if (isset($spec['initial'])) {
Dries Buytaert
committed
$this->connection->update($table)
Angie Byron
committed
->fields(array($field => $spec['initial']))
Dries Buytaert
committed
->execute();
Dries Buytaert
committed
}
if ($fixnull) {
$spec['not null'] = TRUE;
Dries Buytaert
committed
$this->changeField($table, $field, $field, $spec);
Dries Buytaert
committed
}
}
Dries Buytaert
committed
public function dropField($table, $field) {
Dries Buytaert
committed
if (!$this->fieldExists($table, $field)) {
Dries Buytaert
committed
return FALSE;
}
Dries Buytaert
committed
$this->connection->query('ALTER TABLE {' . $table . '} DROP `' . $field . '`');
Dries Buytaert
committed
return TRUE;
Dries Buytaert
committed
}
Dries Buytaert
committed
public function fieldSetDefault($table, $field, $default) {
Dries Buytaert
committed
if (!$this->fieldExists($table, $field)) {
Angie Byron
committed
throw new SchemaObjectDoesNotExistException(t("Cannot set default value of field @table.@field: field doesn't exist.", array('@table' => $table, '@field' => $field)));
Dries Buytaert
committed
}
$this->connection->query('ALTER TABLE {' . $table . '} ALTER COLUMN `' . $field . '` SET DEFAULT ' . $this->escapeDefaultValue($default));
Dries Buytaert
committed
}
Dries Buytaert
committed
public function fieldSetNoDefault($table, $field) {
Dries Buytaert
committed
if (!$this->fieldExists($table, $field)) {
Angie Byron
committed
throw new SchemaObjectDoesNotExistException(t("Cannot remove default value of field @table.@field: field doesn't exist.", array('@table' => $table, '@field' => $field)));
Dries Buytaert
committed
}
Dries Buytaert
committed
$this->connection->query('ALTER TABLE {' . $table . '} ALTER COLUMN `' . $field . '` DROP DEFAULT');
}
public function indexExists($table, $name) {
Dries Buytaert
committed
// Returns one row for each column in the index. Result is string or FALSE.
// Details at http://dev.mysql.com/doc/refman/5.0/en/show-index.html
Alex Pott
committed
$row = $this->connection->query('SHOW INDEX FROM {' . $table . '} WHERE key_name = ' . $this->connection->quote($name))->fetchAssoc();
return isset($row['Key_name']);
Dries Buytaert
committed
}
Dries Buytaert
committed
public function addPrimaryKey($table, $fields) {
Dries Buytaert
committed
if (!$this->tableExists($table)) {
Angie Byron
committed
throw new SchemaObjectDoesNotExistException(t("Cannot add primary key to table @table: table doesn't exist.", array('@table' => $table)));
Dries Buytaert
committed
}
if ($this->indexExists($table, 'PRIMARY')) {
Angie Byron
committed
throw new SchemaObjectExistsException(t("Cannot add primary key to table @table: primary key already exists.", array('@table' => $table)));
Dries Buytaert
committed
}
Dries Buytaert
committed
$this->connection->query('ALTER TABLE {' . $table . '} ADD PRIMARY KEY (' . $this->createKeySql($fields) . ')');
Dries Buytaert
committed
}
Dries Buytaert
committed
public function dropPrimaryKey($table) {
Dries Buytaert
committed
if (!$this->indexExists($table, 'PRIMARY')) {
return FALSE;
}
Dries Buytaert
committed
$this->connection->query('ALTER TABLE {' . $table . '} DROP PRIMARY KEY');
Dries Buytaert
committed
return TRUE;
Dries Buytaert
committed
}
Dries Buytaert
committed
public function addUniqueKey($table, $name, $fields) {
Dries Buytaert
committed
if (!$this->tableExists($table)) {
Angie Byron
committed
throw new SchemaObjectDoesNotExistException(t("Cannot add unique key @name to table @table: table doesn't exist.", array('@table' => $table, '@name' => $name)));
Dries Buytaert
committed
}
if ($this->indexExists($table, $name)) {
Angie Byron
committed
throw new SchemaObjectExistsException(t("Cannot add unique key @name to table @table: unique key already exists.", array('@table' => $table, '@name' => $name)));
Dries Buytaert
committed
}
Dries Buytaert
committed
$this->connection->query('ALTER TABLE {' . $table . '} ADD UNIQUE KEY `' . $name . '` (' . $this->createKeySql($fields) . ')');
Dries Buytaert
committed
}
Dries Buytaert
committed
public function dropUniqueKey($table, $name) {
Dries Buytaert
committed
if (!$this->indexExists($table, $name)) {
return FALSE;
}
Dries Buytaert
committed
$this->connection->query('ALTER TABLE {' . $table . '} DROP KEY `' . $name . '`');
Dries Buytaert
committed
return TRUE;
Dries Buytaert
committed
}
Dries Buytaert
committed
public function addIndex($table, $name, $fields) {
Dries Buytaert
committed
if (!$this->tableExists($table)) {
Angie Byron
committed
throw new SchemaObjectDoesNotExistException(t("Cannot add index @name to table @table: table doesn't exist.", array('@table' => $table, '@name' => $name)));
Dries Buytaert
committed
}
if ($this->indexExists($table, $name)) {
Angie Byron
committed
throw new SchemaObjectExistsException(t("Cannot add index @name to table @table: index already exists.", array('@table' => $table, '@name' => $name)));
Dries Buytaert
committed
}
Dries Buytaert
committed
$this->connection->query('ALTER TABLE {' . $table . '} ADD INDEX `' . $name . '` (' . $this->createKeySql($fields) . ')');
Dries Buytaert
committed
}
Dries Buytaert
committed
public function dropIndex($table, $name) {
Dries Buytaert
committed
if (!$this->indexExists($table, $name)) {
return FALSE;
}
Dries Buytaert
committed
$this->connection->query('ALTER TABLE {' . $table . '} DROP INDEX `' . $name . '`');
Dries Buytaert
committed
return TRUE;
Dries Buytaert
committed
}
Dries Buytaert
committed
public function changeField($table, $field, $field_new, $spec, $keys_new = array()) {
Dries Buytaert
committed
if (!$this->fieldExists($table, $field)) {
Angie Byron
committed
throw new SchemaObjectDoesNotExistException(t("Cannot change the definition of field @table.@name: field doesn't exist.", array('@table' => $table, '@name' => $field)));
Dries Buytaert
committed
}
Dries Buytaert
committed
if (($field != $field_new) && $this->fieldExists($table, $field_new)) {
Angie Byron
committed
throw new SchemaObjectExistsException(t("Cannot rename field @table.@name to @name_new: target field already exists.", array('@table' => $table, '@name' => $field, '@name_new' => $field_new)));
Dries Buytaert
committed
}
$sql = 'ALTER TABLE {' . $table . '} CHANGE `' . $field . '` ' . $this->createFieldSql($field_new, $this->processField($spec));
Dries Buytaert
committed
if ($keys_sql = $this->createKeysSql($keys_new)) {
$sql .= ', ADD ' . implode(', ADD ', $keys_sql);
Dries Buytaert
committed
}
Dries Buytaert
committed
$this->connection->query($sql);
Dries Buytaert
committed
}
public function prepareComment($comment, $length = NULL) {
// Truncate comment to maximum comment length.
if (isset($length)) {
// Add table prefixes before truncating.
Alex Pott
committed
$comment = Unicode::truncate($this->connection->prefixTables($comment), $length, TRUE, TRUE);
}
return $this->connection->quote($comment);
}
/**
* Retrieve a table or column comment.
*/
public function getComment($table, $column = NULL) {
$condition = $this->buildTableNameCondition($table);
if (isset($column)) {
$condition->condition('column_name', $column);
$condition->compile($this->connection, $this);
// Don't use {} around information_schema.columns table.
Dries Buytaert
committed
return $this->connection->query("SELECT column_comment FROM information_schema.columns WHERE " . (string) $condition, $condition->arguments())->fetchField();
$condition->compile($this->connection, $this);
// Don't use {} around information_schema.tables table.
Dries Buytaert
committed
$comment = $this->connection->query("SELECT table_comment FROM information_schema.tables WHERE " . (string) $condition, $condition->arguments())->fetchField();
// Work-around for MySQL 5.0 bug http://bugs.mysql.com/bug.php?id=11379
return preg_replace('/; InnoDB free:.*$/', '', $comment);
Dries Buytaert
committed
public function tableExists($table) {
// The information_schema table is very slow to query under MySQL 5.0.
// Instead, we try to select from the table in question. If it fails,
// the most likely reason is that it does not exist. That is dramatically
// faster than using information_schema.
// @link http://bugs.mysql.com/bug.php?id=19588
// @todo This override should be removed once we require a version of MySQL
// that has that bug fixed.
Dries Buytaert
committed
try {
$this->connection->queryRange("SELECT 1 FROM {" . $table . "}", 0, 1);
return TRUE;
}
Dries Buytaert
committed
return FALSE;
}
}
public function fieldExists($table, $column) {
// The information_schema table is very slow to query under MySQL 5.0.
// Instead, we try to select from the table and field in question. If it
// fails, the most likely reason is that it does not exist. That is
// dramatically faster than using information_schema.
// @link http://bugs.mysql.com/bug.php?id=19588
// @todo This override should be removed once we require a version of MySQL
// that has that bug fixed.
Dries Buytaert
committed
try {
$this->connection->queryRange("SELECT $column FROM {" . $table . "}", 0, 1);
return TRUE;
}
Dries Buytaert
committed
return FALSE;
}
}
Dries Buytaert
committed
}
/**
* @} End of "addtogroup schemaapi".