schema.inc 19 KB

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