schema.inc 19 KB

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