3 * StatusNet, the distributed open-source microblogging tool
5 * Database schema utilities
9 * LICENCE: This program is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU Affero General Public License as published by
11 * the Free Software Foundation, either version 3 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU Affero General Public License for more details.
19 * You should have received a copy of the GNU Affero General Public License
20 * along with this program. If not, see <http://www.gnu.org/licenses/>.
24 * @author Evan Prodromou <evan@status.net>
25 * @copyright 2009 StatusNet, Inc.
26 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
27 * @link http://status.net/
30 if (!defined('STATUSNET')) {
35 * Class representing the database schema
37 * A class representing the database schema. Can be used to
38 * manipulate the schema -- especially for plugins and upgrade
43 * @author Evan Prodromou <evan@status.net>
44 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
45 * @link http://status.net/
48 class MysqlSchema extends Schema
50 static $_single = null;
51 protected $conn = null;
55 * Main public entry point. Use this to get
56 * the singleton object.
58 * @return Schema the (single) Schema object
63 if (empty(self::$_single)) {
64 self::$_single = new Schema();
66 return self::$_single;
70 * Returns a TableDef object for the table
71 * in the schema with the given name.
73 * Throws an exception if the table is not found.
75 * @param string $table Name of the table to get
77 * @return TableDef tabledef for that table.
78 * @throws SchemaTableMissingException
81 public function getTableDef($table)
86 // Pull column data from INFORMATION_SCHEMA
87 $columns = $this->fetchMetaInfo($table, 'COLUMNS', 'ORDINAL_POSITION');
88 if (count($columns) == 0) {
89 throw new SchemaTableMissingException("No such table: $table");
92 foreach ($columns as $row) {
94 $name = $row['COLUMN_NAME'];
97 if ($row['DATA_TYPE'] !== null) {
98 $field['type'] = $row['DATA_TYPE'];
100 if ($row['CHARACTER_MAXIMUM_LENGTH'] !== null) {
101 $field['length'] = intval($row['CHARACTER_MAXIMUM_LENGTH']);
103 if ($row['NUMERIC_PRECISION'] !== null) {
104 $field['precision'] = intval($row['NUMERIC_PRECISION']);
106 if ($row['NUMERIC_SCALE'] !== null) {
107 $field['scale'] = intval($row['NUMERIC_SCALE']);
109 if ($row['IS_NULLABLE'] == 'NO') {
110 $field['not null'] = true;
112 if ($row['COLUMN_DEFAULT'] !== null) {
113 $field['default'] = $row['COLUMN_DEFAULT'];
115 if ($row['COLUMN_KEY'] !== null) {
116 // We'll need to look up key info...
119 if ($row['COLUMN_COMMENT'] !== null) {
120 $field['description'] = $row['COLUMN_COMMENT'];
123 // $row['EXTRA'] may contain 'autoincrement'
125 // $row['EXTRA'] may contain 'on update CURRENT_TIMESTAMP'
126 // ^ ...... how to specify?
127 // these seem to be the only values in curent use
129 if ($row['CHARACTER_SET_NAME'] !== null) {
130 // @fixme check against defaults?
131 //$def['charset'] = $row['CHARACTER_SET_NAME'];
132 //$def['collate'] = $row['COLLATION_NAME'];
135 $def['fields'][$name] = $field;
139 // INFORMATION_SCHEMA's CONSTRAINTS and KEY_COLUMN_USAGE tables give
140 // good info on primary and unique keys but don't list ANY info on
141 // multi-value keys, which is lame-o. Sigh.
143 // Let's go old school and use SHOW INDEX :D
145 $keyInfo = $this->fetchIndexInfo($table);
147 foreach ($keyInfo as $row) {
148 $name = $row['Key_name'];
149 $column = $row['Column_name'];
151 if (!isset($keys[$name])) {
152 $keys[$name] = array();
154 $keys[$name][] = $column;
156 if ($name == 'PRIMARY') {
157 $type = 'primary key';
158 } else if ($row['Non_unique'] == 0) {
159 $type = 'unique keys';
160 } else if ($row['Index_type'] == 'FULLTEXT') {
161 $type = 'fulltext indexes';
165 $keyTypes[$name] = $type;
168 foreach ($keyTypes as $name => $type) {
169 if ($type == 'primary key') {
170 // there can be only one
171 $def[$type] = $keys[$name];
173 $def[$type][$name] = $keys[$name];
181 * Pull the given table properties from INFORMATION_SCHEMA.
182 * Most of the good stuff is MySQL extensions.
185 * @throws Exception if table info can't be looked up
188 function getTableProperties($table, $props)
190 $data = $this->fetchMetaInfo($table, 'TABLES');
194 throw new SchemaTableMissingException("No such table: $table");
199 * Pull some INFORMATION.SCHEMA data for the given table.
201 * @param string $table
202 * @return array of arrays
204 function fetchMetaInfo($table, $infoTable, $orderBy=null)
206 $query = "SELECT * FROM INFORMATION_SCHEMA.%s " .
207 "WHERE TABLE_SCHEMA='%s' AND TABLE_NAME='%s'";
208 $schema = $this->conn->dsn['database'];
209 $sql = sprintf($query, $infoTable, $schema, $table);
211 $sql .= ' ORDER BY ' . $orderBy;
213 return $this->fetchQueryData($sql);
217 * Pull 'SHOW INDEX' data for the given table.
219 * @param string $table
220 * @return array of arrays
222 function fetchIndexInfo($table)
224 $query = "SHOW INDEX FROM `%s`";
225 $sql = sprintf($query, $table);
226 return $this->fetchQueryData($sql);
230 * Pull info from the query into a fun-fun array of dooooom
233 * @return array of arrays
235 protected function fetchQueryData($sql)
237 $res = $this->conn->query($sql);
238 if (PEAR::isError($res)) {
239 throw new Exception($res->getMessage());
244 while ($res->fetchInto($row, DB_FETCHMODE_ASSOC)) {
253 * Creates a table with the given names and columns.
255 * @param string $name Name of the table
256 * @param array $columns Array of ColumnDef objects
259 * @return boolean success flag
262 public function createTable($name, $columns)
268 $sql = "CREATE TABLE $name (\n";
270 for ($i = 0; $i < count($columns); $i++) {
278 $sql .= $this->_columnSql($cd);
281 $idx = $this->_indexList($columns);
283 if ($idx['primary']) {
284 $sql .= ",\nconstraint primary key (" . implode(',', $idx['primary']) . ")";
287 foreach ($idx['uniques'] as $u) {
288 $key = $this->_uniqueKey($name, $u);
289 $sql .= ",\nunique index $key ($u)";
292 foreach ($idx['indices'] as $i) {
293 $key = $this->_key($name, $i);
294 $sql .= ",\nindex $key ($i)";
297 $sql .= ") ENGINE=InnoDB CHARACTER SET utf8 COLLATE utf8_bin; ";
299 $res = $this->conn->query($sql);
301 if (PEAR::isError($res)) {
302 throw new Exception($res->getMessage());
309 * Look over a list of column definitions and list up which
310 * indices will be present
312 private function _indexList(array $columns)
314 $list = array('uniques' => array(),
315 'primary' => array(),
316 'indices' => array());
317 foreach ($columns as $cd) {
320 $list['uniques'][] = $cd->name;
323 $list['primary'][] = $cd->name;
326 $list['indices'][] = $cd->name;
334 * Get the unique index key name for a given column on this table
336 function _uniqueKey($tableName, $columnName)
338 return $this->_key($tableName, $columnName);
342 * Get the index key name for a given column on this table
344 function _key($tableName, $columnName)
346 return "{$tableName}_{$columnName}_idx";
350 * Ensures that a table exists with the given
351 * name and the given column definitions.
353 * If the table does not yet exist, it will
354 * create the table. If it does exist, it will
355 * alter the table to match the column definitions.
357 * @param string $tableName name of the table
358 * @param array $columns array of ColumnDef
359 * objects for the table
361 * @return boolean success flag
364 public function ensureTable($tableName, $columns)
366 // XXX: DB engine portability -> toilet
369 $td = $this->getTableDef($tableName);
370 } catch (SchemaTableMissingException $e) {
371 return $this->createTable($tableName, $columns);
374 $cur = $this->_names($td->columns);
375 $new = $this->_names($columns);
377 $dropIndex = array();
378 $toadd = array_diff($new, $cur);
379 $todrop = array_diff($cur, $new);
380 $same = array_intersect($new, $cur);
383 $tableProps = array();
385 foreach ($same as $m) {
386 $curCol = $this->_byName($td->columns, $m);
387 $newCol = $this->_byName($columns, $m);
389 if (!$newCol->equals($curCol)) {
390 $tomod[] = $newCol->name;
394 // Earlier versions may have accidentally left tables at default
395 // charsets which might be latin1 or other freakish things.
396 if ($this->_isString($curCol)) {
397 if ($curCol->charset != 'utf8') {
398 $tomod[] = $newCol->name;
404 // Find any indices we have to change...
405 $curIdx = $this->_indexList($td->columns);
406 $newIdx = $this->_indexList($columns);
408 if ($curIdx['primary'] != $newIdx['primary']) {
409 if ($curIdx['primary']) {
410 $dropIndex[] = 'drop primary key';
412 if ($newIdx['primary']) {
413 $keys = implode(',', $newIdx['primary']);
414 $addIndex[] = "add constraint primary key ($keys)";
418 $dropUnique = array_diff($curIdx['uniques'], $newIdx['uniques']);
419 $addUnique = array_diff($newIdx['uniques'], $curIdx['uniques']);
420 foreach ($dropUnique as $columnName) {
421 $dropIndex[] = 'drop key ' . $this->_uniqueKey($tableName, $columnName);
423 foreach ($addUnique as $columnName) {
424 $addIndex[] = 'add constraint unique key ' . $this->_uniqueKey($tableName, $columnName) . " ($columnName)";;
427 $dropMultiple = array_diff($curIdx['indices'], $newIdx['indices']);
428 $addMultiple = array_diff($newIdx['indices'], $curIdx['indices']);
429 foreach ($dropMultiple as $columnName) {
430 $dropIndex[] = 'drop key ' . $this->_key($tableName, $columnName);
432 foreach ($addMultiple as $columnName) {
433 $addIndex[] = 'add key ' . $this->_key($tableName, $columnName) . " ($columnName)";
436 // Check for table properties: make sure we're using a sane
437 // engine type and charset/collation.
438 // @fixme make the default engine configurable?
439 $oldProps = $this->getTableProperties($tableName, array('ENGINE', 'TABLE_COLLATION'));
440 if (strtolower($oldProps['ENGINE']) != 'innodb') {
441 $tableProps['ENGINE'] = 'InnoDB';
443 if (strtolower($oldProps['TABLE_COLLATION']) != 'utf8_bin') {
444 $tableProps['DEFAULT CHARSET'] = 'utf8';
445 $tableProps['COLLATE'] = 'utf8_bin';
448 if (count($dropIndex) + count($toadd) + count($todrop) + count($tomod) + count($addIndex) + count($tableProps) == 0) {
453 // For efficiency, we want this all in one
454 // query, instead of using our methods.
458 foreach ($dropIndex as $indexSql) {
459 $phrase[] = $indexSql;
462 foreach ($toadd as $columnName) {
463 $cd = $this->_byName($columns, $columnName);
465 $phrase[] = 'ADD COLUMN ' . $this->_columnSql($cd);
468 foreach ($todrop as $columnName) {
469 $phrase[] = 'DROP COLUMN ' . $columnName;
472 foreach ($tomod as $columnName) {
473 $cd = $this->_byName($columns, $columnName);
475 $phrase[] = 'MODIFY COLUMN ' . $this->_columnSql($cd);
478 foreach ($addIndex as $indexSql) {
479 $phrase[] = $indexSql;
482 foreach ($tableProps as $key => $val) {
483 $phrase[] = "$key=$val";
486 $sql = 'ALTER TABLE ' . $tableName . ' ' . implode(', ', $phrase);
488 common_log(LOG_DEBUG, __METHOD__ . ': ' . $sql);
489 $res = $this->conn->query($sql);
491 if (PEAR::isError($res)) {
492 throw new Exception($res->getMessage());
499 * Is this column a string type?
501 private function _isString(array $cd)
503 $strings = array('char', 'varchar', 'text');
504 return in_array(strtolower($cd['type']), $strings);
508 * Return the proper SQL for creating or
511 * Appropriate for use in CREATE TABLE or
512 * ALTER TABLE statements.
514 * @param ColumnDef $cd column to create
516 * @return string correct SQL for that column
519 function columnSql(array $cd)
522 $line[] = parent::_columnSql($cd);
524 if ($cd['type'] == 'serial') {
525 $line[] = 'auto_increment';
528 if (!empty($cd['extra'])) {
529 $line[] = $cd['extra']; // hisss boooo
532 if (!empty($cd['description'])) {
534 $line[] = $this->quote($cd['description']);
537 return implode(' ', $line);
540 function mapType($column)
542 $map = array('serial' => 'int',
544 'numeric' => 'decimal');
546 $type = $column['type'];
547 if (isset($map[$type])) {
551 if (!empty($column['size'])) {
552 $size = $column['size'];
553 if ($type == 'int' &&
554 in_array($size, array('tiny', 'small', 'medium', 'big'))) {
555 $type = $size . $type;
556 } else if (in_array($type, array('blob', 'text')) &&
557 in_array($size, array('tiny', 'medium', 'long'))) {
558 $type = $size . $type;
565 function typeAndSize($column)
567 if ($column['type'] == 'enum') {
568 $vals = array_map(array($this, 'quote'), $column['enum']);
569 return 'enum(' . implode(',', $vals) . ')';
570 } else if ($this->_isString($column)) {
571 return parent::typeAndSize($column) . ' CHARSET utf8';
573 return parent::typeAndSize($column);