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')
100 list($type, $size) = $this->reverseMapType($row['DATA_TYPE']);
101 $field['type'] = $type;
102 if ($size !== null) {
103 $field['size'] = $size;
106 $field['type'] = $type = $row['DATA_TYPE'];
108 if ($type == 'char' || $type == 'varchar') {
109 if ($row['CHARACTER_MAXIMUM_LENGTH'] !== null) {
110 $field['length'] = intval($row['CHARACTER_MAXIMUM_LENGTH']);
113 if ($type == 'decimal') {
114 // Other int types may report these values, but they're irrelevant.
116 if ($row['NUMERIC_PRECISION'] !== null) {
117 $field['precision'] = intval($row['NUMERIC_PRECISION']);
119 if ($row['NUMERIC_SCALE'] !== null) {
120 $field['scale'] = intval($row['NUMERIC_SCALE']);
123 if ($row['IS_NULLABLE'] == 'NO') {
124 $field['not null'] = true;
126 if ($row['COLUMN_DEFAULT'] !== null) {
127 $field['default'] = $row['COLUMN_DEFAULT'];
128 if ($this->isNumericType($type)) {
129 $field['default'] = intval($field['default']);
132 if ($row['COLUMN_KEY'] !== null) {
133 // We'll need to look up key info...
136 if ($row['COLUMN_COMMENT'] !== null && $row['COLUMN_COMMENT'] != '') {
137 $field['description'] = $row['COLUMN_COMMENT'];
140 $extra = $row['EXTRA'];
142 if (preg_match('/(^|\s)auto_increment(\s|$)/i', $extra)) {
143 $field['auto_increment'] = true;
145 // $row['EXTRA'] may contain 'on update CURRENT_TIMESTAMP'
146 // ^ ...... how to specify?
149 if ($row['CHARACTER_SET_NAME'] !== null) {
150 // @fixme check against defaults?
151 //$def['charset'] = $row['CHARACTER_SET_NAME'];
152 //$def['collate'] = $row['COLLATION_NAME'];
155 $def['fields'][$name] = $field;
159 // INFORMATION_SCHEMA's CONSTRAINTS and KEY_COLUMN_USAGE tables give
160 // good info on primary and unique keys but don't list ANY info on
161 // multi-value keys, which is lame-o. Sigh.
163 // Let's go old school and use SHOW INDEX :D
165 $keyInfo = $this->fetchIndexInfo($table);
167 foreach ($keyInfo as $row) {
168 $name = $row['Key_name'];
169 $column = $row['Column_name'];
171 if (!isset($keys[$name])) {
172 $keys[$name] = array();
174 $keys[$name][] = $column;
176 if ($name == 'PRIMARY') {
177 $type = 'primary key';
178 } else if ($row['Non_unique'] == 0) {
179 $type = 'unique keys';
180 } else if ($row['Index_type'] == 'FULLTEXT') {
181 $type = 'fulltext indexes';
185 $keyTypes[$name] = $type;
188 foreach ($keyTypes as $name => $type) {
189 if ($type == 'primary key') {
190 // there can be only one
191 $def[$type] = $keys[$name];
193 $def[$type][$name] = $keys[$name];
201 * Pull the given table properties from INFORMATION_SCHEMA.
202 * Most of the good stuff is MySQL extensions.
205 * @throws Exception if table info can't be looked up
208 function getTableProperties($table, $props)
210 $data = $this->fetchMetaInfo($table, 'TABLES');
214 throw new SchemaTableMissingException("No such table: $table");
219 * Pull some INFORMATION.SCHEMA data for the given table.
221 * @param string $table
222 * @return array of arrays
224 function fetchMetaInfo($table, $infoTable, $orderBy=null)
226 $query = "SELECT * FROM INFORMATION_SCHEMA.%s " .
227 "WHERE TABLE_SCHEMA='%s' AND TABLE_NAME='%s'";
228 $schema = $this->conn->dsn['database'];
229 $sql = sprintf($query, $infoTable, $schema, $table);
231 $sql .= ' ORDER BY ' . $orderBy;
233 return $this->fetchQueryData($sql);
237 * Pull 'SHOW INDEX' data for the given table.
239 * @param string $table
240 * @return array of arrays
242 function fetchIndexInfo($table)
244 $query = "SHOW INDEX FROM `%s`";
245 $sql = sprintf($query, $table);
246 return $this->fetchQueryData($sql);
250 * Close out a 'create table' SQL statement.
252 * @param string $name
256 function endCreateTable($name, array $def)
258 return ") ENGINE=InnoDB CHARACTER SET utf8 COLLATE utf8_bin";
262 * Get the unique index key name for a given column on this table
264 function _uniqueKey($tableName, $columnName)
266 return $this->_key($tableName, $columnName);
270 * Get the index key name for a given column on this table
272 function _key($tableName, $columnName)
274 return "{$tableName}_{$columnName}_idx";
278 * Ensures that a table exists with the given
279 * name and the given column definitions.
281 * If the table does not yet exist, it will
282 * create the table. If it does exist, it will
283 * alter the table to match the column definitions.
285 * @param string $tableName name of the table
286 * @param array $columns array of ColumnDef
287 * objects for the table
289 * @return boolean success flag
292 public function oldensureTable($tableName, $columns)
294 // XXX: DB engine portability -> toilet
297 $td = $this->getTableDef($tableName);
298 } catch (SchemaTableMissingException $e) {
299 return $this->createTable($tableName, $columns);
302 $cur = $this->_names($td->columns);
303 $new = $this->_names($columns);
305 $dropIndex = array();
306 $toadd = array_diff($new, $cur);
307 $todrop = array_diff($cur, $new);
308 $same = array_intersect($new, $cur);
311 $tableProps = array();
313 foreach ($same as $m) {
314 $curCol = $this->_byName($td->columns, $m);
315 $newCol = $this->_byName($columns, $m);
317 if (!$newCol->equals($curCol)) {
318 $tomod[] = $newCol->name;
322 // Earlier versions may have accidentally left tables at default
323 // charsets which might be latin1 or other freakish things.
324 if ($this->_isString($curCol)) {
325 if ($curCol->charset != 'utf8') {
326 $tomod[] = $newCol->name;
332 // Find any indices we have to change...
333 $curIdx = $this->_indexList($td->columns);
334 $newIdx = $this->_indexList($columns);
336 if ($curIdx['primary'] != $newIdx['primary']) {
337 if ($curIdx['primary']) {
338 $dropIndex[] = 'drop primary key';
340 if ($newIdx['primary']) {
341 $keys = implode(',', $newIdx['primary']);
342 $addIndex[] = "add constraint primary key ($keys)";
346 $dropUnique = array_diff($curIdx['uniques'], $newIdx['uniques']);
347 $addUnique = array_diff($newIdx['uniques'], $curIdx['uniques']);
348 foreach ($dropUnique as $columnName) {
349 $dropIndex[] = 'drop key ' . $this->_uniqueKey($tableName, $columnName);
351 foreach ($addUnique as $columnName) {
352 $addIndex[] = 'add constraint unique key ' . $this->_uniqueKey($tableName, $columnName) . " ($columnName)";;
355 $dropMultiple = array_diff($curIdx['indices'], $newIdx['indices']);
356 $addMultiple = array_diff($newIdx['indices'], $curIdx['indices']);
357 foreach ($dropMultiple as $columnName) {
358 $dropIndex[] = 'drop key ' . $this->_key($tableName, $columnName);
360 foreach ($addMultiple as $columnName) {
361 $addIndex[] = 'add key ' . $this->_key($tableName, $columnName) . " ($columnName)";
364 // Check for table properties: make sure we're using a sane
365 // engine type and charset/collation.
366 // @fixme make the default engine configurable?
367 $oldProps = $this->getTableProperties($tableName, array('ENGINE', 'TABLE_COLLATION'));
368 if (strtolower($oldProps['ENGINE']) != 'innodb') {
369 $tableProps['ENGINE'] = 'InnoDB';
371 if (strtolower($oldProps['TABLE_COLLATION']) != 'utf8_bin') {
372 $tableProps['DEFAULT CHARSET'] = 'utf8';
373 $tableProps['COLLATE'] = 'utf8_bin';
376 if (count($dropIndex) + count($toadd) + count($todrop) + count($tomod) + count($addIndex) + count($tableProps) == 0) {
381 // For efficiency, we want this all in one
382 // query, instead of using our methods.
386 foreach ($dropIndex as $indexSql) {
387 $phrase[] = $indexSql;
390 foreach ($toadd as $columnName) {
391 $cd = $this->_byName($columns, $columnName);
393 $phrase[] = 'ADD COLUMN ' . $this->_columnSql($cd);
396 foreach ($todrop as $columnName) {
397 $phrase[] = 'DROP COLUMN ' . $columnName;
400 foreach ($tomod as $columnName) {
401 $cd = $this->_byName($columns, $columnName);
403 $phrase[] = 'MODIFY COLUMN ' . $this->_columnSql($cd);
406 foreach ($addIndex as $indexSql) {
407 $phrase[] = $indexSql;
410 foreach ($tableProps as $key => $val) {
411 $phrase[] = "$key=$val";
414 $sql = 'ALTER TABLE ' . $tableName . ' ' . implode(', ', $phrase);
416 common_log(LOG_DEBUG, __METHOD__ . ': ' . $sql);
417 $res = $this->conn->query($sql);
419 if (PEAR::isError($res)) {
420 throw new Exception($res->getMessage());
427 * Is this column a string type?
429 private function _isString(array $cd)
431 $strings = array('char', 'varchar', 'text');
432 return in_array(strtolower($cd['type']), $strings);
436 * Return the proper SQL for creating or
439 * Appropriate for use in CREATE TABLE or
440 * ALTER TABLE statements.
442 * @param ColumnDef $cd column to create
444 * @return string correct SQL for that column
447 function columnSql(array $cd)
450 $line[] = parent::columnSql($cd);
452 // This'll have been added from our transform of 'serial' type
453 if (!empty($cd['auto_increment'])) {
454 $line[] = 'auto_increment';
457 if (!empty($cd['description'])) {
459 $line[] = $this->quoteValue($cd['description']);
462 return implode(' ', $line);
465 function mapType($column)
467 $map = array('serial' => 'int',
469 'numeric' => 'decimal');
471 $type = $column['type'];
472 if (isset($map[$type])) {
476 if (!empty($column['size'])) {
477 $size = $column['size'];
478 if ($type == 'int' &&
479 in_array($size, array('tiny', 'small', 'medium', 'big'))) {
480 $type = $size . $type;
481 } else if (in_array($type, array('blob', 'text')) &&
482 in_array($size, array('tiny', 'medium', 'long'))) {
483 $type = $size . $type;
491 * Map a MySQL native type back to an independent type + size
493 * @param string $type
494 * @return array ($type, $size) -- $size may be null
497 protected function reverseMapType($type)
499 $type = strtolower($type);
501 'decimal' => array('numeric', null),
502 'tinyint' => array('int', 'tiny'),
503 'smallint' => array('int', 'small'),
504 'mediumint' => array('int', 'medium'),
505 'bigint' => array('int', 'big'),
506 'tinyblob' => array('blob', 'tiny'),
507 'mediumblob' => array('blob', 'medium'),
508 'longblob' => array('blob', 'long'),
509 'tinytext' => array('text', 'tiny'),
510 'mediumtext' => array('text', 'medium'),
511 'longtext' => array('text', 'long'),
513 if (isset($map[$type])) {
516 return array($type, null);
521 function typeAndSize($column)
523 if ($column['type'] == 'enum') {
524 $vals = array_map(array($this, 'quote'), $column['enum']);
525 return 'enum(' . implode(',', $vals) . ')';
526 } else if ($this->_isString($column)) {
527 return parent::typeAndSize($column) . ' CHARSET utf8';
529 return parent::typeAndSize($column);
534 * Filter the given table definition array to match features available
537 * This lets us strip out unsupported things like comments, foreign keys,
538 * or type variants that we wouldn't get back from getTableDef().
540 * @param array $tableDef
542 function filterDef(array $tableDef)
544 foreach ($tableDef['fields'] as $name => &$col) {
545 if ($col['type'] == 'serial') {
546 $col['type'] = 'int';
547 $col['auto_increment'] = true;
549 if ($col['type'] == 'datetime' && isset($col['default']) && $col['default'] == 'CURRENT_TIMESTAMP') {
550 $col['type'] = 'timestamp';
552 $col['type'] = $this->mapType($col);
555 // @fixme add foreign-key support for MySQL
556 unset($tableDef['foreign keys']);