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 $field['type'] = $type = $row['DATA_TYPE'];
101 if ($type == 'char' || $type == 'varchar') {
102 if ($row['CHARACTER_MAXIMUM_LENGTH'] !== null) {
103 $field['length'] = intval($row['CHARACTER_MAXIMUM_LENGTH']);
106 if ($type == 'decimal') {
107 // Other int types may report these values, but they're irrelevant.
109 if ($row['NUMERIC_PRECISION'] !== null) {
110 $field['precision'] = intval($row['NUMERIC_PRECISION']);
112 if ($row['NUMERIC_SCALE'] !== null) {
113 $field['scale'] = intval($row['NUMERIC_SCALE']);
116 if ($row['IS_NULLABLE'] == 'NO') {
117 $field['not null'] = true;
119 if ($row['COLUMN_DEFAULT'] !== null) {
120 $field['default'] = $row['COLUMN_DEFAULT'];
121 if ($this->isNumericType($type)) {
122 $field['default'] = intval($field['default']);
125 if ($row['COLUMN_KEY'] !== null) {
126 // We'll need to look up key info...
129 if ($row['COLUMN_COMMENT'] !== null && $row['COLUMN_COMMENT'] != '') {
130 $field['description'] = $row['COLUMN_COMMENT'];
133 $extra = $row['EXTRA'];
135 if (preg_match('/(^|\s)auto_increment(\s|$)/i', $extra)) {
136 $field['auto_increment'] = true;
138 // $row['EXTRA'] may contain 'on update CURRENT_TIMESTAMP'
139 // ^ ...... how to specify?
142 if ($row['CHARACTER_SET_NAME'] !== null) {
143 // @fixme check against defaults?
144 //$def['charset'] = $row['CHARACTER_SET_NAME'];
145 //$def['collate'] = $row['COLLATION_NAME'];
148 $def['fields'][$name] = $field;
152 // INFORMATION_SCHEMA's CONSTRAINTS and KEY_COLUMN_USAGE tables give
153 // good info on primary and unique keys but don't list ANY info on
154 // multi-value keys, which is lame-o. Sigh.
156 // Let's go old school and use SHOW INDEX :D
158 $keyInfo = $this->fetchIndexInfo($table);
160 foreach ($keyInfo as $row) {
161 $name = $row['Key_name'];
162 $column = $row['Column_name'];
164 if (!isset($keys[$name])) {
165 $keys[$name] = array();
167 $keys[$name][] = $column;
169 if ($name == 'PRIMARY') {
170 $type = 'primary key';
171 } else if ($row['Non_unique'] == 0) {
172 $type = 'unique keys';
173 } else if ($row['Index_type'] == 'FULLTEXT') {
174 $type = 'fulltext indexes';
178 $keyTypes[$name] = $type;
181 foreach ($keyTypes as $name => $type) {
182 if ($type == 'primary key') {
183 // there can be only one
184 $def[$type] = $keys[$name];
186 $def[$type][$name] = $keys[$name];
194 * Pull the given table properties from INFORMATION_SCHEMA.
195 * Most of the good stuff is MySQL extensions.
198 * @throws Exception if table info can't be looked up
201 function getTableProperties($table, $props)
203 $data = $this->fetchMetaInfo($table, 'TABLES');
207 throw new SchemaTableMissingException("No such table: $table");
212 * Pull some INFORMATION.SCHEMA data for the given table.
214 * @param string $table
215 * @return array of arrays
217 function fetchMetaInfo($table, $infoTable, $orderBy=null)
219 $query = "SELECT * FROM INFORMATION_SCHEMA.%s " .
220 "WHERE TABLE_SCHEMA='%s' AND TABLE_NAME='%s'";
221 $schema = $this->conn->dsn['database'];
222 $sql = sprintf($query, $infoTable, $schema, $table);
224 $sql .= ' ORDER BY ' . $orderBy;
226 return $this->fetchQueryData($sql);
230 * Pull 'SHOW INDEX' data for the given table.
232 * @param string $table
233 * @return array of arrays
235 function fetchIndexInfo($table)
237 $query = "SHOW INDEX FROM `%s`";
238 $sql = sprintf($query, $table);
239 return $this->fetchQueryData($sql);
243 * Close out a 'create table' SQL statement.
245 * @param string $name
249 function endCreateTable($name, array $def)
251 return ") ENGINE=InnoDB CHARACTER SET utf8 COLLATE utf8_bin";
255 * Get the unique index key name for a given column on this table
257 function _uniqueKey($tableName, $columnName)
259 return $this->_key($tableName, $columnName);
263 * Get the index key name for a given column on this table
265 function _key($tableName, $columnName)
267 return "{$tableName}_{$columnName}_idx";
271 * Ensures that a table exists with the given
272 * name and the given column definitions.
274 * If the table does not yet exist, it will
275 * create the table. If it does exist, it will
276 * alter the table to match the column definitions.
278 * @param string $tableName name of the table
279 * @param array $columns array of ColumnDef
280 * objects for the table
282 * @return boolean success flag
285 public function oldensureTable($tableName, $columns)
287 // XXX: DB engine portability -> toilet
290 $td = $this->getTableDef($tableName);
291 } catch (SchemaTableMissingException $e) {
292 return $this->createTable($tableName, $columns);
295 $cur = $this->_names($td->columns);
296 $new = $this->_names($columns);
298 $dropIndex = array();
299 $toadd = array_diff($new, $cur);
300 $todrop = array_diff($cur, $new);
301 $same = array_intersect($new, $cur);
304 $tableProps = array();
306 foreach ($same as $m) {
307 $curCol = $this->_byName($td->columns, $m);
308 $newCol = $this->_byName($columns, $m);
310 if (!$newCol->equals($curCol)) {
311 $tomod[] = $newCol->name;
315 // Earlier versions may have accidentally left tables at default
316 // charsets which might be latin1 or other freakish things.
317 if ($this->_isString($curCol)) {
318 if ($curCol->charset != 'utf8') {
319 $tomod[] = $newCol->name;
325 // Find any indices we have to change...
326 $curIdx = $this->_indexList($td->columns);
327 $newIdx = $this->_indexList($columns);
329 if ($curIdx['primary'] != $newIdx['primary']) {
330 if ($curIdx['primary']) {
331 $dropIndex[] = 'drop primary key';
333 if ($newIdx['primary']) {
334 $keys = implode(',', $newIdx['primary']);
335 $addIndex[] = "add constraint primary key ($keys)";
339 $dropUnique = array_diff($curIdx['uniques'], $newIdx['uniques']);
340 $addUnique = array_diff($newIdx['uniques'], $curIdx['uniques']);
341 foreach ($dropUnique as $columnName) {
342 $dropIndex[] = 'drop key ' . $this->_uniqueKey($tableName, $columnName);
344 foreach ($addUnique as $columnName) {
345 $addIndex[] = 'add constraint unique key ' . $this->_uniqueKey($tableName, $columnName) . " ($columnName)";;
348 $dropMultiple = array_diff($curIdx['indices'], $newIdx['indices']);
349 $addMultiple = array_diff($newIdx['indices'], $curIdx['indices']);
350 foreach ($dropMultiple as $columnName) {
351 $dropIndex[] = 'drop key ' . $this->_key($tableName, $columnName);
353 foreach ($addMultiple as $columnName) {
354 $addIndex[] = 'add key ' . $this->_key($tableName, $columnName) . " ($columnName)";
357 // Check for table properties: make sure we're using a sane
358 // engine type and charset/collation.
359 // @fixme make the default engine configurable?
360 $oldProps = $this->getTableProperties($tableName, array('ENGINE', 'TABLE_COLLATION'));
361 if (strtolower($oldProps['ENGINE']) != 'innodb') {
362 $tableProps['ENGINE'] = 'InnoDB';
364 if (strtolower($oldProps['TABLE_COLLATION']) != 'utf8_bin') {
365 $tableProps['DEFAULT CHARSET'] = 'utf8';
366 $tableProps['COLLATE'] = 'utf8_bin';
369 if (count($dropIndex) + count($toadd) + count($todrop) + count($tomod) + count($addIndex) + count($tableProps) == 0) {
374 // For efficiency, we want this all in one
375 // query, instead of using our methods.
379 foreach ($dropIndex as $indexSql) {
380 $phrase[] = $indexSql;
383 foreach ($toadd as $columnName) {
384 $cd = $this->_byName($columns, $columnName);
386 $phrase[] = 'ADD COLUMN ' . $this->_columnSql($cd);
389 foreach ($todrop as $columnName) {
390 $phrase[] = 'DROP COLUMN ' . $columnName;
393 foreach ($tomod as $columnName) {
394 $cd = $this->_byName($columns, $columnName);
396 $phrase[] = 'MODIFY COLUMN ' . $this->_columnSql($cd);
399 foreach ($addIndex as $indexSql) {
400 $phrase[] = $indexSql;
403 foreach ($tableProps as $key => $val) {
404 $phrase[] = "$key=$val";
407 $sql = 'ALTER TABLE ' . $tableName . ' ' . implode(', ', $phrase);
409 common_log(LOG_DEBUG, __METHOD__ . ': ' . $sql);
410 $res = $this->conn->query($sql);
412 if (PEAR::isError($res)) {
413 throw new Exception($res->getMessage());
420 * Is this column a string type?
422 private function _isString(array $cd)
424 $strings = array('char', 'varchar', 'text');
425 return in_array(strtolower($cd['type']), $strings);
429 * Return the proper SQL for creating or
432 * Appropriate for use in CREATE TABLE or
433 * ALTER TABLE statements.
435 * @param ColumnDef $cd column to create
437 * @return string correct SQL for that column
440 function columnSql(array $cd)
443 $line[] = parent::columnSql($cd);
445 // This'll have been added from our transform of 'serial' type
446 if (!empty($cd['auto_increment'])) {
447 $line[] = 'auto_increment';
450 if (!empty($cd['description'])) {
452 $line[] = $this->quoteValue($cd['description']);
455 return implode(' ', $line);
458 function mapType($column)
460 $map = array('serial' => 'int',
462 'numeric' => 'decimal');
464 $type = $column['type'];
465 if (isset($map[$type])) {
469 if (!empty($column['size'])) {
470 $size = $column['size'];
471 if ($type == 'int' &&
472 in_array($size, array('tiny', 'small', 'medium', 'big'))) {
473 $type = $size . $type;
474 } else if (in_array($type, array('blob', 'text')) &&
475 in_array($size, array('tiny', 'medium', 'long'))) {
476 $type = $size . $type;
483 function typeAndSize($column)
485 if ($column['type'] == 'enum') {
486 $vals = array_map(array($this, 'quote'), $column['enum']);
487 return 'enum(' . implode(',', $vals) . ')';
488 } else if ($this->_isString($column)) {
489 return parent::typeAndSize($column) . ' CHARSET utf8';
491 return parent::typeAndSize($column);
496 * Filter the given table definition array to match features available
499 * This lets us strip out unsupported things like comments, foreign keys,
500 * or type variants that we wouldn't get back from getTableDef().
502 * @param array $tableDef
504 function filterDef(array $tableDef)
506 foreach ($tableDef['fields'] as $name => &$col) {
507 if ($col['type'] == 'serial') {
508 $col['type'] = 'int';
509 $col['auto_increment'] = true;
511 if ($col['type'] == 'datetime' && isset($col['default']) && $col['default'] == 'CURRENT_TIMESTAMP') {
512 $col['type'] = 'timestamp';
514 $col['type'] = $this->mapType($col);
517 // @fixme add foreign-key support for MySQL
518 unset($tableDef['foreign keys']);