schema.inc 18 KB

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