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 $name Name of the table to get
77 * @return TableDef tabledef for that table.
78 * @throws SchemaTableMissingException
81 public function getTableDef($name)
83 $query = "SELECT * FROM INFORMATION_SCHEMA.COLUMNS " .
84 "WHERE TABLE_SCHEMA='%s' AND TABLE_NAME='%s' " .
85 "ORDER BY ORDINAL_POSITION";
86 $schema = $this->conn->dsn['database'];
87 $sql = sprintf($query, $schema, $name);
88 $res = $this->conn->query($sql);
90 if (PEAR::isError($res)) {
91 throw new Exception($res->getMessage());
93 if ($res->numRows() == 0) {
95 throw new SchemaTableMissingException("No such table: $name");
101 $td->columns = array();
106 while ($res->fetchInto($row, DB_FETCHMODE_ASSOC)) {
108 $name = $row['COLUMN_NAME'];
111 if ($row['DATA_TYPE'] !== null) {
112 $field['type'] = $row['DATA_TYPE'];
114 if ($row['CHARACTER_MAXIMUM_LENGTH'] !== null) {
115 $field['length'] = intval($row['CHARACTER_MAXIMUM_LENGTH']);
117 if ($row['NUMERIC_PRECISION'] !== null) {
118 $field['precision'] = intval($row['NUMERIC_PRECISION']);
120 if ($row['NUMERIC_SCALE'] !== null) {
121 $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'];
130 if ($row['COLUMN_KEY'] == 'PRI') {
131 if (isset($def['primary keys'])) {
132 $def['primary keys'][] = $name;
134 $def['primary keys'][] = array($name);
136 } else if ($row['COLUMN_KEY'] == 'MUL') {
138 } else if ($row['COLUMN_KEY'] == 'UNI') {
142 if ($row['COLUMN_COMMENT'] !== null) {
143 $field['description'] = $row['COLUMN_COMMENT'];
146 // $row['EXTRA'] may contain 'autoincrement'
148 // $row['EXTRA'] may contain 'on update CURRENT_TIMESTAMP'
149 // ^ ...... how to specify?
150 // these seem to be the only values in curent use
152 if ($row['CHARACTER_SET_NAME'] !== null) {
153 // @fixme check against defaults?
154 //$def['charset'] = $row['CHARACTER_SET_NAME'];
155 //$def['collate'] = $row['COLLATION_NAME'];
158 $def['fields'][$name] = $field;
165 we need to first pull the list/types of keys
167 we could get those and the columns like this:
168 // this works but is insanely slow!
169 SELECT CONSTRAINT_NAME AS keyName,
170 (SELECT GROUP_CONCAT(COLUMN_NAME)
171 FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS keyColumns
172 WHERE keyColumns.TABLE_SCHEMA=keyDefs.TABLE_SCHEMA
173 AND keyColumns.TABLE_NAME=keyDefs.TABLE_NAME
174 AND keyColumns.CONSTRAINT_NAME=keyDefs.CONSTRAINT_NAME
175 ORDER BY ORDINAL_POSITION)
176 FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS keyDefs
177 WHERE TABLE_SCHEMA='mublog'
178 AND TABLE_NAME='subscription'
179 ORDER BY TABLE_NAME, CONSTRAINT_NAME;
181 However MySQL's query optimizer is crap here and it does something
182 insane. ;) Using constants is faster, but won't let us do bulk
183 fetches. So... maybe go ahead and fetch each table separately.
186 // Now fetch the key info...
187 $query = "SELECT * FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE " .
188 "WHERE TABLE_SCHEMA='%s' AND TABLE_NAME='%s' " .
189 "ORDER BY CONSTRAINT_NAME,ORDINAL_POSITION";
190 $schema = $this->conn->dsn['database'];
191 $sql = sprintf($query, $schema, $name);
192 $res = $this->conn->query($sql);
194 if (PEAR::isError($res)) {
195 throw new Exception($res->getMessage());
197 if ($res->numRows() == 0) {
199 throw new SchemaTableMissingException("No such table: $name");
203 while ($res->fetchInto($row, DB_FETCHMODE_ASSOC)) {
204 $keyName = $row['CONSTRAINT_NAME'];
205 $colName = $row['COLUMN_NAME'];
206 // @fixme what about prefixes?
207 if ($keyName == 'PRIMARY') {
208 if (!isset($def['primary key'])) {
209 $def['primary key'] = array();
211 $def['primary key'][] = $colName;
213 if (!isset($def['indexes'][$keyName])) {
214 $def['indexes'][$keyName] = array();
216 $def['indexes'][$keyName][] = $colName;
224 * Pull the given table properties from INFORMATION_SCHEMA.
225 * Most of the good stuff is MySQL extensions.
228 * @throws Exception if table info can't be looked up
231 function getTableProperties($table, $props)
233 $query = "SELECT %s FROM INFORMATION_SCHEMA.TABLES " .
234 "WHERE TABLE_SCHEMA='%s' AND TABLE_NAME='%s'";
235 $schema = $this->conn->dsn['database'];
236 $sql = sprintf($query, implode(',', $props), $schema, $table);
237 $res = $this->conn->query($sql);
240 $ok = $res->fetchInto($row, DB_FETCHMODE_ASSOC);
246 throw new SchemaTableMissingException("No such table: $table");
251 * Creates a table with the given names and columns.
253 * @param string $name Name of the table
254 * @param array $columns Array of ColumnDef objects
257 * @return boolean success flag
260 public function createTable($name, $columns)
266 $sql = "CREATE TABLE $name (\n";
268 for ($i = 0; $i < count($columns); $i++) {
276 $sql .= $this->_columnSql($cd);
279 $idx = $this->_indexList($columns);
281 if ($idx['primary']) {
282 $sql .= ",\nconstraint primary key (" . implode(',', $idx['primary']) . ")";
285 foreach ($idx['uniques'] as $u) {
286 $key = $this->_uniqueKey($name, $u);
287 $sql .= ",\nunique index $key ($u)";
290 foreach ($idx['indices'] as $i) {
291 $key = $this->_key($name, $i);
292 $sql .= ",\nindex $key ($i)";
295 $sql .= ") ENGINE=InnoDB CHARACTER SET utf8 COLLATE utf8_bin; ";
297 $res = $this->conn->query($sql);
299 if (PEAR::isError($res)) {
300 throw new Exception($res->getMessage());
307 * Look over a list of column definitions and list up which
308 * indices will be present
310 private function _indexList(array $columns)
312 $list = array('uniques' => array(),
313 'primary' => array(),
314 'indices' => array());
315 foreach ($columns as $cd) {
318 $list['uniques'][] = $cd->name;
321 $list['primary'][] = $cd->name;
324 $list['indices'][] = $cd->name;
332 * Get the unique index key name for a given column on this table
334 function _uniqueKey($tableName, $columnName)
336 return $this->_key($tableName, $columnName);
340 * Get the index key name for a given column on this table
342 function _key($tableName, $columnName)
344 return "{$tableName}_{$columnName}_idx";
348 * Ensures that a table exists with the given
349 * name and the given column definitions.
351 * If the table does not yet exist, it will
352 * create the table. If it does exist, it will
353 * alter the table to match the column definitions.
355 * @param string $tableName name of the table
356 * @param array $columns array of ColumnDef
357 * objects for the table
359 * @return boolean success flag
362 public function ensureTable($tableName, $columns)
364 // XXX: DB engine portability -> toilet
367 $td = $this->getTableDef($tableName);
368 } catch (SchemaTableMissingException $e) {
369 return $this->createTable($tableName, $columns);
372 $cur = $this->_names($td->columns);
373 $new = $this->_names($columns);
375 $dropIndex = array();
376 $toadd = array_diff($new, $cur);
377 $todrop = array_diff($cur, $new);
378 $same = array_intersect($new, $cur);
381 $tableProps = array();
383 foreach ($same as $m) {
384 $curCol = $this->_byName($td->columns, $m);
385 $newCol = $this->_byName($columns, $m);
387 if (!$newCol->equals($curCol)) {
388 $tomod[] = $newCol->name;
392 // Earlier versions may have accidentally left tables at default
393 // charsets which might be latin1 or other freakish things.
394 if ($this->_isString($curCol)) {
395 if ($curCol->charset != 'utf8') {
396 $tomod[] = $newCol->name;
402 // Find any indices we have to change...
403 $curIdx = $this->_indexList($td->columns);
404 $newIdx = $this->_indexList($columns);
406 if ($curIdx['primary'] != $newIdx['primary']) {
407 if ($curIdx['primary']) {
408 $dropIndex[] = 'drop primary key';
410 if ($newIdx['primary']) {
411 $keys = implode(',', $newIdx['primary']);
412 $addIndex[] = "add constraint primary key ($keys)";
416 $dropUnique = array_diff($curIdx['uniques'], $newIdx['uniques']);
417 $addUnique = array_diff($newIdx['uniques'], $curIdx['uniques']);
418 foreach ($dropUnique as $columnName) {
419 $dropIndex[] = 'drop key ' . $this->_uniqueKey($tableName, $columnName);
421 foreach ($addUnique as $columnName) {
422 $addIndex[] = 'add constraint unique key ' . $this->_uniqueKey($tableName, $columnName) . " ($columnName)";;
425 $dropMultiple = array_diff($curIdx['indices'], $newIdx['indices']);
426 $addMultiple = array_diff($newIdx['indices'], $curIdx['indices']);
427 foreach ($dropMultiple as $columnName) {
428 $dropIndex[] = 'drop key ' . $this->_key($tableName, $columnName);
430 foreach ($addMultiple as $columnName) {
431 $addIndex[] = 'add key ' . $this->_key($tableName, $columnName) . " ($columnName)";
434 // Check for table properties: make sure we're using a sane
435 // engine type and charset/collation.
436 // @fixme make the default engine configurable?
437 $oldProps = $this->getTableProperties($tableName, array('ENGINE', 'TABLE_COLLATION'));
438 if (strtolower($oldProps['ENGINE']) != 'innodb') {
439 $tableProps['ENGINE'] = 'InnoDB';
441 if (strtolower($oldProps['TABLE_COLLATION']) != 'utf8_bin') {
442 $tableProps['DEFAULT CHARSET'] = 'utf8';
443 $tableProps['COLLATE'] = 'utf8_bin';
446 if (count($dropIndex) + count($toadd) + count($todrop) + count($tomod) + count($addIndex) + count($tableProps) == 0) {
451 // For efficiency, we want this all in one
452 // query, instead of using our methods.
456 foreach ($dropIndex as $indexSql) {
457 $phrase[] = $indexSql;
460 foreach ($toadd as $columnName) {
461 $cd = $this->_byName($columns, $columnName);
463 $phrase[] = 'ADD COLUMN ' . $this->_columnSql($cd);
466 foreach ($todrop as $columnName) {
467 $phrase[] = 'DROP COLUMN ' . $columnName;
470 foreach ($tomod as $columnName) {
471 $cd = $this->_byName($columns, $columnName);
473 $phrase[] = 'MODIFY COLUMN ' . $this->_columnSql($cd);
476 foreach ($addIndex as $indexSql) {
477 $phrase[] = $indexSql;
480 foreach ($tableProps as $key => $val) {
481 $phrase[] = "$key=$val";
484 $sql = 'ALTER TABLE ' . $tableName . ' ' . implode(', ', $phrase);
486 common_log(LOG_DEBUG, __METHOD__ . ': ' . $sql);
487 $res = $this->conn->query($sql);
489 if (PEAR::isError($res)) {
490 throw new Exception($res->getMessage());
497 * Is this column a string type?
499 private function _isString(array $cd)
501 $strings = array('char', 'varchar', 'text');
502 return in_array(strtolower($cd['type']), $strings);
506 * Return the proper SQL for creating or
509 * Appropriate for use in CREATE TABLE or
510 * ALTER TABLE statements.
512 * @param ColumnDef $cd column to create
514 * @return string correct SQL for that column
517 function columnSql(array $cd)
520 $line[] = parent::_columnSql($cd);
522 if ($cd['type'] == 'serial') {
523 $line[] = 'auto_increment';
526 if (!empty($cd['extra'])) {
527 $line[] = $cd['extra']; // hisss boooo
530 if (!empty($cd['description'])) {
532 $line[] = $this->quote($cd['description']);
535 return implode(' ', $line);
538 function mapType($column)
540 $map = array('serial' => 'int',
542 'numeric' => 'decimal');
544 $type = $column['type'];
545 if (isset($map[$type])) {
549 if (!empty($column['size'])) {
550 $size = $column['size'];
551 if ($type == 'int' &&
552 in_array($size, array('tiny', 'small', 'medium', 'big'))) {
553 $type = $size . $type;
554 } else if (in_array($type, array('blob', 'text')) &&
555 in_array($size, array('tiny', 'medium', 'long'))) {
556 $type = $size . $type;
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);