Skip navigation
Help

schema.inc

  1. drupal
    1. 7 drupal/includes/database/schema.inc
    2. 7 drupal/includes/database/mysql/schema.inc
    3. 7 drupal/includes/database/sqlite/schema.inc
    4. 7 drupal/includes/database/pgsql/schema.inc

Database schema code for MySQL database servers.

Classes

NameDescription
DatabaseSchema_mysql

File

drupal/includes/database/mysql/schema.inc
View source
  1. <?php
  2. /**
  3. * @file
  4. * Database schema code for MySQL database servers.
  5. */
  6. /**
  7. * @ingroup schemaapi
  8. * @{
  9. */
  10. class DatabaseSchema_mysql extends DatabaseSchema {
  11. /**
  12. * Maximum length of a table comment in MySQL.
  13. */
  14. const COMMENT_MAX_TABLE = 60;
  15. /**
  16. * Maximum length of a column comment in MySQL.
  17. */
  18. const COMMENT_MAX_COLUMN = 255;
  19. /**
  20. * Get information about the table and database name from the prefix.
  21. *
  22. * @return
  23. * A keyed array with information about the database, table name and prefix.
  24. */
  25. protected function getPrefixInfo($table = 'default', $add_prefix = TRUE) {
  26. $info = array('prefix' => $this->connection->tablePrefix($table));
  27. if ($add_prefix) {
  28. $table = $info['prefix'] . $table;
  29. }
  30. if (($pos = strpos($table, '.')) !== FALSE) {
  31. $info['database'] = substr($table, 0, $pos);
  32. $info['table'] = substr($table, ++$pos);
  33. }
  34. else {
  35. $db_info = Database::getConnectionInfo();
  36. $info['database'] = $db_info['default']['database'];
  37. $info['table'] = $table;
  38. }
  39. return $info;
  40. }
  41. /**
  42. * Build a condition to match a table name against a standard information_schema.
  43. *
  44. * MySQL uses databases like schemas rather than catalogs so when we build
  45. * a condition to query the information_schema.tables, we set the default
  46. * database as the schema unless specified otherwise, and exclude table_catalog
  47. * from the condition criteria.
  48. */
  49. protected function buildTableNameCondition($table_name, $operator = '=', $add_prefix = TRUE) {
  50. $info = $this->connection->getConnectionOptions();
  51. $table_info = $this->getPrefixInfo($table_name, $add_prefix);
  52. $condition = new DatabaseCondition('AND');
  53. $condition->condition('table_schema', $table_info['database']);
  54. $condition->condition('table_name', $table_info['table'], $operator);
  55. return $condition;
  56. }
  57. /**
  58. * Generate SQL to create a new table from a Drupal schema definition.
  59. *
  60. * @param $name
  61. * The name of the table to create.
  62. * @param $table
  63. * A Schema API table definition array.
  64. * @return
  65. * An array of SQL statements to create the table.
  66. */
  67. protected function createTableSql($name, $table) {
  68. $info = $this->connection->getConnectionOptions();
  69. // Provide defaults if needed.
  70. $table += array(
  71. 'mysql_engine' => 'InnoDB',
  72. 'mysql_character_set' => 'utf8',
  73. );
  74. $sql = "CREATE TABLE {" . $name . "} (\n";
  75. // Add the SQL statement for each field.
  76. foreach ($table['fields'] as $field_name => $field) {
  77. $sql .= $this->createFieldSql($field_name, $this->processField($field)) . ", \n";
  78. }
  79. // Process keys & indexes.
  80. $keys = $this->createKeysSql($table);
  81. if (count($keys)) {
  82. $sql .= implode(", \n", $keys) . ", \n";
  83. }
  84. // Remove the last comma and space.
  85. $sql = substr($sql, 0, -3) . "\n) ";
  86. $sql .= 'ENGINE = ' . $table['mysql_engine'] . ' DEFAULT CHARACTER SET ' . $table['mysql_character_set'];
  87. // By default, MySQL uses the default collation for new tables, which is
  88. // 'utf8_general_ci' for utf8. If an alternate collation has been set, it
  89. // needs to be explicitly specified.
  90. // @see DatabaseConnection_mysql
  91. if (!empty($info['collation'])) {
  92. $sql .= ' COLLATE ' . $info['collation'];
  93. }
  94. // Add table comment.
  95. if (!empty($table['description'])) {
  96. $sql .= ' COMMENT ' . $this->prepareComment($table['description'], self::COMMENT_MAX_TABLE);
  97. }
  98. return array($sql);
  99. }
  100. /**
  101. * Create an SQL string for a field to be used in table creation or alteration.
  102. *
  103. * Before passing a field out of a schema definition into this function it has
  104. * to be processed by _db_process_field().
  105. *
  106. * @param $name
  107. * Name of the field.
  108. * @param $spec
  109. * The field specification, as per the schema data structure format.
  110. */
  111. protected function createFieldSql($name, $spec) {
  112. $sql = "`" . $name . "` " . $spec['mysql_type'];
  113. if (in_array($spec['mysql_type'], array('VARCHAR', 'CHAR', 'TINYTEXT', 'MEDIUMTEXT', 'LONGTEXT', 'TEXT')) && isset($spec['length'])) {
  114. $sql .= '(' . $spec['length'] . ')';
  115. }
  116. elseif (isset($spec['precision']) && isset($spec['scale'])) {
  117. $sql .= '(' . $spec['precision'] . ', ' . $spec['scale'] . ')';
  118. }
  119. if (!empty($spec['unsigned'])) {
  120. $sql .= ' unsigned';
  121. }
  122. if (isset($spec['not null'])) {
  123. if ($spec['not null']) {
  124. $sql .= ' NOT NULL';
  125. }
  126. else {
  127. $sql .= ' NULL';
  128. }
  129. }
  130. if (!empty($spec['auto_increment'])) {
  131. $sql .= ' auto_increment';
  132. }
  133. // $spec['default'] can be NULL, so we explicitly check for the key here.
  134. if (array_key_exists('default', $spec)) {
  135. if (is_string($spec['default'])) {
  136. $spec['default'] = "'" . $spec['default'] . "'";
  137. }
  138. elseif (!isset($spec['default'])) {
  139. $spec['default'] = 'NULL';
  140. }
  141. $sql .= ' DEFAULT ' . $spec['default'];
  142. }
  143. if (empty($spec['not null']) && !isset($spec['default'])) {
  144. $sql .= ' DEFAULT NULL';
  145. }
  146. // Add column comment.
  147. if (!empty($spec['description'])) {
  148. $sql .= ' COMMENT ' . $this->prepareComment($spec['description'], self::COMMENT_MAX_COLUMN);
  149. }
  150. return $sql;
  151. }
  152. /**
  153. * Set database-engine specific properties for a field.
  154. *
  155. * @param $field
  156. * A field description array, as specified in the schema documentation.
  157. */
  158. protected function processField($field) {
  159. if (!isset($field['size'])) {
  160. $field['size'] = 'normal';
  161. }
  162. // Set the correct database-engine specific datatype.
  163. // In case one is already provided, force it to uppercase.
  164. if (isset($field['mysql_type'])) {
  165. $field['mysql_type'] = drupal_strtoupper($field['mysql_type']);
  166. }
  167. else {
  168. $map = $this->getFieldTypeMap();
  169. $field['mysql_type'] = $map[$field['type'] . ':' . $field['size']];
  170. }
  171. if (isset($field['type']) && $field['type'] == 'serial') {
  172. $field['auto_increment'] = TRUE;
  173. }
  174. return $field;
  175. }
  176. public function getFieldTypeMap() {
  177. // Put :normal last so it gets preserved by array_flip. This makes
  178. // it much easier for modules (such as schema.module) to map
  179. // database types back into schema types.
  180. // $map does not use drupal_static as its value never changes.
  181. static $map = array(
  182. 'varchar:normal' => 'VARCHAR',
  183. 'char:normal' => 'CHAR',
  184. 'text:tiny' => 'TINYTEXT',
  185. 'text:small' => 'TINYTEXT',
  186. 'text:medium' => 'MEDIUMTEXT',
  187. 'text:big' => 'LONGTEXT',
  188. 'text:normal' => 'TEXT',
  189. 'serial:tiny' => 'TINYINT',
  190. 'serial:small' => 'SMALLINT',
  191. 'serial:medium' => 'MEDIUMINT',
  192. 'serial:big' => 'BIGINT',
  193. 'serial:normal' => 'INT',
  194. 'int:tiny' => 'TINYINT',
  195. 'int:small' => 'SMALLINT',
  196. 'int:medium' => 'MEDIUMINT',
  197. 'int:big' => 'BIGINT',
  198. 'int:normal' => 'INT',
  199. 'float:tiny' => 'FLOAT',
  200. 'float:small' => 'FLOAT',
  201. 'float:medium' => 'FLOAT',
  202. 'float:big' => 'DOUBLE',
  203. 'float:normal' => 'FLOAT',
  204. 'numeric:normal' => 'DECIMAL',
  205. 'blob:big' => 'LONGBLOB',
  206. 'blob:normal' => 'BLOB',
  207. );
  208. return $map;
  209. }
  210. protected function createKeysSql($spec) {
  211. $keys = array();
  212. if (!empty($spec['primary key'])) {
  213. $keys[] = 'PRIMARY KEY (' . $this->createKeysSqlHelper($spec['primary key']) . ')';
  214. }
  215. if (!empty($spec['unique keys'])) {
  216. foreach ($spec['unique keys'] as $key => $fields) {
  217. $keys[] = 'UNIQUE KEY `' . $key . '` (' . $this->createKeysSqlHelper($fields) . ')';
  218. }
  219. }
  220. if (!empty($spec['indexes'])) {
  221. foreach ($spec['indexes'] as $index => $fields) {
  222. $keys[] = 'INDEX `' . $index . '` (' . $this->createKeysSqlHelper($fields) . ')';
  223. }
  224. }
  225. return $keys;
  226. }
  227. protected function createKeySql($fields) {
  228. $return = array();
  229. foreach ($fields as $field) {
  230. if (is_array($field)) {
  231. $return[] = '`' . $field[0] . '`(' . $field[1] . ')';
  232. }
  233. else {
  234. $return[] = '`' . $field . '`';
  235. }
  236. }
  237. return implode(', ', $return);
  238. }
  239. protected function createKeysSqlHelper($fields) {
  240. $return = array();
  241. foreach ($fields as $field) {
  242. if (is_array($field)) {
  243. $return[] = '`' . $field[0] . '`(' . $field[1] . ')';
  244. }
  245. else {
  246. $return[] = '`' . $field . '`';
  247. }
  248. }
  249. return implode(', ', $return);
  250. }
  251. public function renameTable($table, $new_name) {
  252. if (!$this->tableExists($table)) {
  253. throw new DatabaseSchemaObjectDoesNotExistException(t("Cannot rename %table to %table_new: table %table doesn't exist.", array('%table' => $table, '%table_new' => $new_name)));
  254. }
  255. if ($this->tableExists($new_name)) {
  256. throw new DatabaseSchemaObjectExistsException(t("Cannot rename %table to %table_new: table %table_new already exists.", array('%table' => $table, '%table_new' => $new_name)));
  257. }
  258. $info = $this->getPrefixInfo($new_name);
  259. return $this->connection->query('ALTER TABLE {' . $table . '} RENAME TO `' . $info['table'] . '`');
  260. }
  261. public function dropTable($table) {
  262. if (!$this->tableExists($table)) {
  263. return FALSE;
  264. }
  265. $this->connection->query('DROP TABLE {' . $table . '}');
  266. return TRUE;
  267. }
  268. public function addField($table, $field, $spec, $keys_new = array()) {
  269. if (!$this->tableExists($table)) {
  270. throw new DatabaseSchemaObjectDoesNotExistException(t("Cannot add field %table.%field: table doesn't exist.", array('%field' => $field, '%table' => $table)));
  271. }
  272. if ($this->fieldExists($table, $field)) {
  273. throw new DatabaseSchemaObjectExistsException(t("Cannot add field %table.%field: field already exists.", array('%field' => $field, '%table' => $table)));
  274. }
  275. $fixnull = FALSE;
  276. if (!empty($spec['not null']) && !isset($spec['default'])) {
  277. $fixnull = TRUE;
  278. $spec['not null'] = FALSE;
  279. }
  280. $query = 'ALTER TABLE {' . $table . '} ADD ';
  281. $query .= $this->createFieldSql($field, $this->processField($spec));
  282. if ($keys_sql = $this->createKeysSql($keys_new)) {
  283. $query .= ', ADD ' . implode(', ADD ', $keys_sql);
  284. }
  285. $this->connection->query($query);
  286. if (isset($spec['initial'])) {
  287. $this->connection->update($table)
  288. ->fields(array($field => $spec['initial']))
  289. ->execute();
  290. }
  291. if ($fixnull) {
  292. $spec['not null'] = TRUE;
  293. $this->changeField($table, $field, $field, $spec);
  294. }
  295. }
  296. public function dropField($table, $field) {
  297. if (!$this->fieldExists($table, $field)) {
  298. return FALSE;
  299. }
  300. $this->connection->query('ALTER TABLE {' . $table . '} DROP `' . $field . '`');
  301. return TRUE;
  302. }
  303. public function fieldSetDefault($table, $field, $default) {
  304. if (!$this->fieldExists($table, $field)) {
  305. throw new DatabaseSchemaObjectDoesNotExistException(t("Cannot set default value of field %table.%field: field doesn't exist.", array('%table' => $table, '%field' => $field)));
  306. }
  307. if (!isset($default)) {
  308. $default = 'NULL';
  309. }
  310. else {
  311. $default = is_string($default) ? "'$default'" : $default;
  312. }
  313. $this->connection->query('ALTER TABLE {' . $table . '} ALTER COLUMN `' . $field . '` SET DEFAULT ' . $default);
  314. }
  315. public function fieldSetNoDefault($table, $field) {
  316. if (!$this->fieldExists($table, $field)) {
  317. throw new DatabaseSchemaObjectDoesNotExistException(t("Cannot remove default value of field %table.%field: field doesn't exist.", array('%table' => $table, '%field' => $field)));
  318. }
  319. $this->connection->query('ALTER TABLE {' . $table . '} ALTER COLUMN `' . $field . '` DROP DEFAULT');
  320. }
  321. public function indexExists($table, $name) {
  322. // Returns one row for each column in the index. Result is string or FALSE.
  323. // Details at http://dev.mysql.com/doc/refman/5.0/en/show-index.html
  324. $row = $this->connection->query('SHOW INDEX FROM {' . $table . "} WHERE key_name = '$name'")->fetchAssoc();
  325. return isset($row['key_name']);
  326. }
  327. public function addPrimaryKey($table, $fields) {
  328. if (!$this->tableExists($table)) {
  329. throw new DatabaseSchemaObjectDoesNotExistException(t("Cannot add primary key to table %table: table doesn't exist.", array('%table' => $table)));
  330. }
  331. if ($this->indexExists($table, 'PRIMARY')) {
  332. throw new DatabaseSchemaObjectExistsException(t("Cannot add primary key to table %table: primary key already exists.", array('%table' => $table)));
  333. }
  334. $this->connection->query('ALTER TABLE {' . $table . '} ADD PRIMARY KEY (' . $this->createKeySql($fields) . ')');
  335. }
  336. public function dropPrimaryKey($table) {
  337. if (!$this->indexExists($table, 'PRIMARY')) {
  338. return FALSE;
  339. }
  340. $this->connection->query('ALTER TABLE {' . $table . '} DROP PRIMARY KEY');
  341. return TRUE;
  342. }
  343. public function addUniqueKey($table, $name, $fields) {
  344. if (!$this->tableExists($table)) {
  345. throw new DatabaseSchemaObjectDoesNotExistException(t("Cannot add unique key %name to table %table: table doesn't exist.", array('%table' => $table, '%name' => $name)));
  346. }
  347. if ($this->indexExists($table, $name)) {
  348. throw new DatabaseSchemaObjectExistsException(t("Cannot add unique key %name to table %table: unique key already exists.", array('%table' => $table, '%name' => $name)));
  349. }
  350. $this->connection->query('ALTER TABLE {' . $table . '} ADD UNIQUE KEY `' . $name . '` (' . $this->createKeySql($fields) . ')');
  351. }
  352. public function dropUniqueKey($table, $name) {
  353. if (!$this->indexExists($table, $name)) {
  354. return FALSE;
  355. }
  356. $this->connection->query('ALTER TABLE {' . $table . '} DROP KEY `' . $name . '`');
  357. return TRUE;
  358. }
  359. public function addIndex($table, $name, $fields) {
  360. if (!$this->tableExists($table)) {
  361. throw new DatabaseSchemaObjectDoesNotExistException(t("Cannot add index %name to table %table: table doesn't exist.", array('%table' => $table, '%name' => $name)));
  362. }
  363. if ($this->indexExists($table, $name)) {
  364. throw new DatabaseSchemaObjectExistsException(t("Cannot add index %name to table %table: index already exists.", array('%table' => $table, '%name' => $name)));
  365. }
  366. $this->connection->query('ALTER TABLE {' . $table . '} ADD INDEX `' . $name . '` (' . $this->createKeySql($fields) . ')');
  367. }
  368. public function dropIndex($table, $name) {
  369. if (!$this->indexExists($table, $name)) {
  370. return FALSE;
  371. }
  372. $this->connection->query('ALTER TABLE {' . $table . '} DROP INDEX `' . $name . '`');
  373. return TRUE;
  374. }
  375. public function changeField($table, $field, $field_new, $spec, $keys_new = array()) {
  376. if (!$this->fieldExists($table, $field)) {
  377. throw new DatabaseSchemaObjectDoesNotExistException(t("Cannot change the definition of field %table.%name: field doesn't exist.", array('%table' => $table, '%name' => $field)));
  378. }
  379. if (($field != $field_new) && $this->fieldExists($table, $field_new)) {
  380. throw new DatabaseSchemaObjectExistsException(t("Cannot rename field %table.%name to %name_new: target field already exists.", array('%table' => $table, '%name' => $field, '%name_new' => $field_new)));
  381. }
  382. $sql = 'ALTER TABLE {' . $table . '} CHANGE `' . $field . '` ' . $this->createFieldSql($field_new, $this->processField($spec));
  383. if ($keys_sql = $this->createKeysSql($keys_new)) {
  384. $sql .= ', ADD ' . implode(', ADD ', $keys_sql);
  385. }
  386. $this->connection->query($sql);
  387. }
  388. public function prepareComment($comment, $length = NULL) {
  389. // Work around a bug in some versions of PDO, see http://bugs.php.net/bug.php?id=41125
  390. $comment = str_replace("'", '’', $comment);
  391. // Truncate comment to maximum comment length.
  392. if (isset($length)) {
  393. // Add table prefixes before truncating.
  394. $comment = truncate_utf8($this->connection->prefixTables($comment), $length, TRUE, TRUE);
  395. }
  396. return $this->connection->quote($comment);
  397. }
  398. /**
  399. * Retrieve a table or column comment.
  400. */
  401. public function getComment($table, $column = NULL) {
  402. $condition = $this->buildTableNameCondition($table);
  403. if (isset($column)) {
  404. $condition->condition('column_name', $column);
  405. $condition->compile($this->connection, $this);
  406. // Don't use {} around information_schema.columns table.
  407. return $this->connection->query("SELECT column_comment FROM information_schema.columns WHERE " . (string) $condition, $condition->arguments())->fetchField();
  408. }
  409. $condition->compile($this->connection, $this);
  410. // Don't use {} around information_schema.tables table.
  411. $comment = $this->connection->query("SELECT table_comment FROM information_schema.tables WHERE " . (string) $condition, $condition->arguments())->fetchField();
  412. // Work-around for MySQL 5.0 bug http://bugs.mysql.com/bug.php?id=11379
  413. return preg_replace('/; InnoDB free:.*$/', '', $comment);
  414. }
  415. public function tableExists($table) {
  416. // The information_schema table is very slow to query under MySQL 5.0.
  417. // Instead, we try to select from the table in question. If it fails,
  418. // the most likely reason is that it does not exist. That is dramatically
  419. // faster than using information_schema.
  420. // @link http://bugs.mysql.com/bug.php?id=19588
  421. // @todo: This override should be removed once we require a version of MySQL
  422. // that has that bug fixed.
  423. try {
  424. $this->connection->queryRange("SELECT 1 FROM {" . $table . "}", 0, 1);
  425. return TRUE;
  426. }
  427. catch (Exception $e) {
  428. return FALSE;
  429. }
  430. }
  431. public function fieldExists($table, $column) {
  432. // The information_schema table is very slow to query under MySQL 5.0.
  433. // Instead, we try to select from the table and field in question. If it
  434. // fails, the most likely reason is that it does not exist. That is
  435. // dramatically faster than using information_schema.
  436. // @link http://bugs.mysql.com/bug.php?id=19588
  437. // @todo: This override should be removed once we require a version of MySQL
  438. // that has that bug fixed.
  439. try {
  440. $this->connection->queryRange("SELECT $column FROM {" . $table . "}", 0, 1);
  441. return TRUE;
  442. }
  443. catch (Exception $e) {
  444. return FALSE;
  445. }
  446. }
  447. }
  448. /**
  449. * @} End of "ingroup schemaapi".
  450. */