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 // warning -- 'unsigned' attr on numbers isn't given in DATA_TYPE and friends.
98 // It is stuck in on COLUMN_TYPE though (eg 'bigint(20) unsigned')
99 list($type, $size) = $this->reverseMapType($row['DATA_TYPE']);
100 $field['type'] = $type;
101 if ($size !== null) {
102 $field['size'] = $size;
105 if ($type == 'char' || $type == 'varchar') {
106 if ($row['CHARACTER_MAXIMUM_LENGTH'] !== null) {
107 $field['length'] = intval($row['CHARACTER_MAXIMUM_LENGTH']);
110 if ($type == 'numeric') {
111 // Other int types may report these values, but they're irrelevant.
113 if ($row['NUMERIC_PRECISION'] !== null) {
114 $field['precision'] = intval($row['NUMERIC_PRECISION']);
116 if ($row['NUMERIC_SCALE'] !== null) {
117 $field['scale'] = intval($row['NUMERIC_SCALE']);
120 if ($row['IS_NULLABLE'] == 'NO') {
121 $field['not null'] = true;
123 if ($row['COLUMN_DEFAULT'] !== null) {
124 $field['default'] = $row['COLUMN_DEFAULT'];
125 if ($this->isNumericType($type)) {
126 $field['default'] = intval($field['default']);
129 if ($row['COLUMN_KEY'] !== null) {
130 // We'll need to look up key info...
133 if ($row['COLUMN_COMMENT'] !== null && $row['COLUMN_COMMENT'] != '') {
134 $field['description'] = $row['COLUMN_COMMENT'];
137 $extra = $row['EXTRA'];
139 if (preg_match('/(^|\s)auto_increment(\s|$)/i', $extra)) {
140 $field['type'] = 'serial';
142 // $row['EXTRA'] may contain 'on update CURRENT_TIMESTAMP'
143 // ^ ...... how to specify?
146 if ($row['CHARACTER_SET_NAME'] !== null) {
147 // @fixme check against defaults?
148 //$def['charset'] = $row['CHARACTER_SET_NAME'];
149 //$def['collate'] = $row['COLLATION_NAME'];
152 $def['fields'][$name] = $field;
156 // INFORMATION_SCHEMA's CONSTRAINTS and KEY_COLUMN_USAGE tables give
157 // good info on primary and unique keys but don't list ANY info on
158 // multi-value keys, which is lame-o. Sigh.
160 // Let's go old school and use SHOW INDEX :D
162 $keyInfo = $this->fetchIndexInfo($table);
164 foreach ($keyInfo as $row) {
165 $name = $row['Key_name'];
166 $column = $row['Column_name'];
168 if (!isset($keys[$name])) {
169 $keys[$name] = array();
171 $keys[$name][] = $column;
173 if ($name == 'PRIMARY') {
174 $type = 'primary key';
175 } else if ($row['Non_unique'] == 0) {
176 $type = 'unique keys';
177 } else if ($row['Index_type'] == 'FULLTEXT') {
178 $type = 'fulltext indexes';
182 $keyTypes[$name] = $type;
185 foreach ($keyTypes as $name => $type) {
186 if ($type == 'primary key') {
187 // there can be only one
188 $def[$type] = $keys[$name];
190 $def[$type][$name] = $keys[$name];
198 * Pull the given table properties from INFORMATION_SCHEMA.
199 * Most of the good stuff is MySQL extensions.
202 * @throws Exception if table info can't be looked up
205 function getTableProperties($table, $props)
207 $data = $this->fetchMetaInfo($table, 'TABLES');
211 throw new SchemaTableMissingException("No such table: $table");
216 * Pull some INFORMATION.SCHEMA data for the given table.
218 * @param string $table
219 * @return array of arrays
221 function fetchMetaInfo($table, $infoTable, $orderBy=null)
223 $query = "SELECT * FROM INFORMATION_SCHEMA.%s " .
224 "WHERE TABLE_SCHEMA='%s' AND TABLE_NAME='%s'";
225 $schema = $this->conn->dsn['database'];
226 $sql = sprintf($query, $infoTable, $schema, $table);
228 $sql .= ' ORDER BY ' . $orderBy;
230 return $this->fetchQueryData($sql);
234 * Pull 'SHOW INDEX' data for the given table.
236 * @param string $table
237 * @return array of arrays
239 function fetchIndexInfo($table)
241 $query = "SHOW INDEX FROM `%s`";
242 $sql = sprintf($query, $table);
243 return $this->fetchQueryData($sql);
247 * Creates a table with the given names and columns.
249 * @param string $name Name of the table
250 * @param array $columns Array of ColumnDef objects
253 * @return boolean success flag
256 public function createTable($name, $columns)
262 $sql = "CREATE TABLE $name (\n";
264 for ($i = 0; $i < count($columns); $i++) {
272 $sql .= $this->_columnSql($cd);
275 $idx = $this->_indexList($columns);
277 if ($idx['primary']) {
278 $sql .= ",\nconstraint primary key (" . implode(',', $idx['primary']) . ")";
281 foreach ($idx['uniques'] as $u) {
282 $key = $this->_uniqueKey($name, $u);
283 $sql .= ",\nunique index $key ($u)";
286 foreach ($idx['indices'] as $i) {
287 $key = $this->_key($name, $i);
288 $sql .= ",\nindex $key ($i)";
291 $sql .= ") ENGINE=InnoDB CHARACTER SET utf8 COLLATE utf8_bin; ";
293 $res = $this->conn->query($sql);
295 if (PEAR::isError($res)) {
296 throw new Exception($res->getMessage());
303 * Get the unique index key name for a given column on this table
305 function _uniqueKey($tableName, $columnName)
307 return $this->_key($tableName, $columnName);
311 * Get the index key name for a given column on this table
313 function _key($tableName, $columnName)
315 return "{$tableName}_{$columnName}_idx";
319 * Ensures that a table exists with the given
320 * name and the given column definitions.
322 * If the table does not yet exist, it will
323 * create the table. If it does exist, it will
324 * alter the table to match the column definitions.
326 * @param string $tableName name of the table
327 * @param array $columns array of ColumnDef
328 * objects for the table
330 * @return boolean success flag
333 public function ensureTable($tableName, $columns)
335 // XXX: DB engine portability -> toilet
338 $td = $this->getTableDef($tableName);
339 } catch (SchemaTableMissingException $e) {
340 return $this->createTable($tableName, $columns);
343 $cur = $this->_names($td->columns);
344 $new = $this->_names($columns);
346 $dropIndex = array();
347 $toadd = array_diff($new, $cur);
348 $todrop = array_diff($cur, $new);
349 $same = array_intersect($new, $cur);
352 $tableProps = array();
354 foreach ($same as $m) {
355 $curCol = $this->_byName($td->columns, $m);
356 $newCol = $this->_byName($columns, $m);
358 if (!$newCol->equals($curCol)) {
359 $tomod[] = $newCol->name;
363 // Earlier versions may have accidentally left tables at default
364 // charsets which might be latin1 or other freakish things.
365 if ($this->_isString($curCol)) {
366 if ($curCol->charset != 'utf8') {
367 $tomod[] = $newCol->name;
373 // Find any indices we have to change...
374 $curIdx = $this->_indexList($td->columns);
375 $newIdx = $this->_indexList($columns);
377 if ($curIdx['primary'] != $newIdx['primary']) {
378 if ($curIdx['primary']) {
379 $dropIndex[] = 'drop primary key';
381 if ($newIdx['primary']) {
382 $keys = implode(',', $newIdx['primary']);
383 $addIndex[] = "add constraint primary key ($keys)";
387 $dropUnique = array_diff($curIdx['uniques'], $newIdx['uniques']);
388 $addUnique = array_diff($newIdx['uniques'], $curIdx['uniques']);
389 foreach ($dropUnique as $columnName) {
390 $dropIndex[] = 'drop key ' . $this->_uniqueKey($tableName, $columnName);
392 foreach ($addUnique as $columnName) {
393 $addIndex[] = 'add constraint unique key ' . $this->_uniqueKey($tableName, $columnName) . " ($columnName)";;
396 $dropMultiple = array_diff($curIdx['indices'], $newIdx['indices']);
397 $addMultiple = array_diff($newIdx['indices'], $curIdx['indices']);
398 foreach ($dropMultiple as $columnName) {
399 $dropIndex[] = 'drop key ' . $this->_key($tableName, $columnName);
401 foreach ($addMultiple as $columnName) {
402 $addIndex[] = 'add key ' . $this->_key($tableName, $columnName) . " ($columnName)";
405 // Check for table properties: make sure we're using a sane
406 // engine type and charset/collation.
407 // @fixme make the default engine configurable?
408 $oldProps = $this->getTableProperties($tableName, array('ENGINE', 'TABLE_COLLATION'));
409 if (strtolower($oldProps['ENGINE']) != 'innodb') {
410 $tableProps['ENGINE'] = 'InnoDB';
412 if (strtolower($oldProps['TABLE_COLLATION']) != 'utf8_bin') {
413 $tableProps['DEFAULT CHARSET'] = 'utf8';
414 $tableProps['COLLATE'] = 'utf8_bin';
417 if (count($dropIndex) + count($toadd) + count($todrop) + count($tomod) + count($addIndex) + count($tableProps) == 0) {
422 // For efficiency, we want this all in one
423 // query, instead of using our methods.
427 foreach ($dropIndex as $indexSql) {
428 $phrase[] = $indexSql;
431 foreach ($toadd as $columnName) {
432 $cd = $this->_byName($columns, $columnName);
434 $phrase[] = 'ADD COLUMN ' . $this->_columnSql($cd);
437 foreach ($todrop as $columnName) {
438 $phrase[] = 'DROP COLUMN ' . $columnName;
441 foreach ($tomod as $columnName) {
442 $cd = $this->_byName($columns, $columnName);
444 $phrase[] = 'MODIFY COLUMN ' . $this->_columnSql($cd);
447 foreach ($addIndex as $indexSql) {
448 $phrase[] = $indexSql;
451 foreach ($tableProps as $key => $val) {
452 $phrase[] = "$key=$val";
455 $sql = 'ALTER TABLE ' . $tableName . ' ' . implode(', ', $phrase);
457 common_log(LOG_DEBUG, __METHOD__ . ': ' . $sql);
458 $res = $this->conn->query($sql);
460 if (PEAR::isError($res)) {
461 throw new Exception($res->getMessage());
468 * Is this column a string type?
470 private function _isString(array $cd)
472 $strings = array('char', 'varchar', 'text');
473 return in_array(strtolower($cd['type']), $strings);
477 * Return the proper SQL for creating or
480 * Appropriate for use in CREATE TABLE or
481 * ALTER TABLE statements.
483 * @param ColumnDef $cd column to create
485 * @return string correct SQL for that column
488 function columnSql(array $cd)
491 $line[] = parent::_columnSql($cd);
493 if ($cd['type'] == 'serial') {
494 $line[] = 'auto_increment';
497 if (!empty($cd['extra'])) {
498 $line[] = $cd['extra']; // hisss boooo
501 if (!empty($cd['description'])) {
503 $line[] = $this->quote($cd['description']);
506 return implode(' ', $line);
509 function mapType($column)
511 $map = array('serial' => 'int',
513 'numeric' => 'decimal');
515 $type = $column['type'];
516 if (isset($map[$type])) {
520 if (!empty($column['size'])) {
521 $size = $column['size'];
522 if ($type == 'int' &&
523 in_array($size, array('tiny', 'small', 'medium', 'big'))) {
524 $type = $size . $type;
525 } else if (in_array($type, array('blob', 'text')) &&
526 in_array($size, array('tiny', 'medium', 'long'))) {
527 $type = $size . $type;
535 * Map a MySQL native type back to an independent type + size
537 * @param string $type
538 * @return array ($type, $size) -- $size may be null
540 protected function reverseMapType($type)
542 $type = strtolower($type);
544 'decimal' => array('numeric', null),
545 'tinyint' => array('int', 'tiny'),
546 'smallint' => array('int', 'small'),
547 'mediumint' => array('int', 'medium'),
548 'bigint' => array('int', 'big'),
549 'tinyblob' => array('blob', 'tiny'),
550 'mediumblob' => array('blob', 'medium'),
551 'longblob' => array('blob', 'long'),
552 'tinytext' => array('text', 'tiny'),
553 'mediumtext' => array('text', 'medium'),
554 'longtext' => array('text', 'long'),
556 if (isset($map[$type])) {
559 return array($type, null);
563 function typeAndSize($column)
565 if ($column['type'] == 'enum') {
566 $vals = array_map(array($this, 'quote'), $column['enum']);
567 return 'enum(' . implode(',', $vals) . ')';
568 } else if ($this->_isString($column)) {
569 return parent::typeAndSize($column) . ' CHARSET utf8';
571 return parent::typeAndSize($column);