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 $schema = $this->conn->dsn['database'];
86 $sql = sprintf($query, $schema, $name);
87 $res = $this->conn->query($sql);
89 if (PEAR::isError($res)) {
90 throw new Exception($res->getMessage());
92 if ($res->numRows() == 0) {
94 throw new SchemaTableMissingException("No such table: $name");
100 $td->columns = array();
104 while ($res->fetchInto($row, DB_FETCHMODE_ASSOC)) {
106 $cd = new ColumnDef();
108 $cd->name = $row['COLUMN_NAME'];
110 $packed = $row['COLUMN_TYPE'];
112 if (preg_match('/^(\w+)\((\d+)\)$/', $packed, $match)) {
113 $cd->type = $match[1];
114 $cd->size = $match[2];
119 $cd->nullable = ($row['IS_NULLABLE'] == 'YES') ? true : false;
120 $cd->key = $row['COLUMN_KEY'];
121 $cd->default = $row['COLUMN_DEFAULT'];
122 $cd->extra = $row['EXTRA'];
124 // Autoincrement is stuck into the extra column.
125 // Pull it out so we don't accidentally mod it every time...
126 $extra = preg_replace('/(^|\s)auto_increment(\s|$)/i', '$1$2', $cd->extra);
127 if ($extra != $cd->extra) {
128 $cd->extra = trim($extra);
129 $cd->auto_increment = true;
132 // mysql extensions -- not (yet) used by base class
133 $cd->charset = $row['CHARACTER_SET_NAME'];
134 $cd->collate = $row['COLLATION_NAME'];
136 $td->columns[] = $cd;
144 * Pull the given table properties from INFORMATION_SCHEMA.
145 * Most of the good stuff is MySQL extensions.
148 * @throws Exception if table info can't be looked up
151 function getTableProperties($table, $props)
153 $query = "SELECT %s FROM INFORMATION_SCHEMA.TABLES " .
154 "WHERE TABLE_SCHEMA='%s' AND TABLE_NAME='%s'";
155 $schema = $this->conn->dsn['database'];
156 $sql = sprintf($query, implode(',', $props), $schema, $table);
157 $res = $this->conn->query($sql);
160 $ok = $res->fetchInto($row, DB_FETCHMODE_ASSOC);
166 throw new SchemaTableMissingException("No such table: $table");
171 * Gets a ColumnDef object for a single column.
173 * Throws an exception if the table is not found.
175 * @param string $table name of the table
176 * @param string $column name of the column
178 * @return ColumnDef definition of the column or null
182 public function getColumnDef($table, $column)
184 $td = $this->getTableDef($table);
186 foreach ($td->columns as $cd) {
187 if ($cd->name == $column) {
196 * Creates a table with the given names and columns.
198 * @param string $name Name of the table
199 * @param array $columns Array of ColumnDef objects
202 * @return boolean success flag
205 public function createTable($name, $columns)
211 $sql = "CREATE TABLE $name (\n";
213 for ($i = 0; $i < count($columns); $i++) {
221 $sql .= $this->_columnSql($cd);
224 $idx = $this->_indexList($columns);
226 if ($idx['primary']) {
227 $sql .= ",\nconstraint primary key (" . implode(',', $idx['primary']) . ")";
230 foreach ($idx['uniques'] as $u) {
231 $key = $this->_uniqueKey($name, $u);
232 $sql .= ",\nunique index $key ($u)";
235 foreach ($idx['indices'] as $i) {
236 $key = $this->_key($name, $i);
237 $sql .= ",\nindex $key ($i)";
240 $sql .= ") ENGINE=InnoDB CHARACTER SET utf8 COLLATE utf8_bin; ";
242 $res = $this->conn->query($sql);
244 if (PEAR::isError($res)) {
245 throw new Exception($res->getMessage());
252 * Look over a list of column definitions and list up which
253 * indices will be present
255 private function _indexList(array $columns)
257 $list = array('uniques' => array(),
258 'primary' => array(),
259 'indices' => array());
260 foreach ($columns as $cd) {
263 $list['uniques'][] = $cd->name;
266 $list['primary'][] = $cd->name;
269 $list['indices'][] = $cd->name;
277 * Get the unique index key name for a given column on this table
279 function _uniqueKey($tableName, $columnName)
281 return $this->_key($tableName, $columnName);
285 * Get the index key name for a given column on this table
287 function _key($tableName, $columnName)
289 return "{$tableName}_{$columnName}_idx";
293 * Drops a table from the schema
295 * Throws an exception if the table is not found.
297 * @param string $name Name of the table to drop
299 * @return boolean success flag
302 public function dropTable($name)
304 $res = $this->conn->query("DROP TABLE $name");
306 if (PEAR::isError($res)) {
307 throw new Exception($res->getMessage());
314 * Adds an index to a table.
316 * If no name is provided, a name will be made up based
317 * on the table name and column names.
319 * Throws an exception on database error, esp. if the table
322 * @param string $table Name of the table
323 * @param array $columnNames Name of columns to index
324 * @param string $name (Optional) name of the index
326 * @return boolean success flag
329 public function createIndex($table, $columnNames, $name=null)
331 if (!is_array($columnNames)) {
332 $columnNames = array($columnNames);
336 $name = "$table_".implode("_", $columnNames)."_idx";
339 $res = $this->conn->query("ALTER TABLE $table ".
341 implode(",", $columnNames).")");
343 if (PEAR::isError($res)) {
344 throw new Exception($res->getMessage());
351 * Drops a named index from a table.
353 * @param string $table name of the table the index is on.
354 * @param string $name name of the index
356 * @return boolean success flag
359 public function dropIndex($table, $name)
361 $res = $this->conn->query("ALTER TABLE $table DROP INDEX $name");
363 if (PEAR::isError($res)) {
364 throw new Exception($res->getMessage());
371 * Adds a column to a table
373 * @param string $table name of the table
374 * @param ColumnDef $columndef Definition of the new
377 * @return boolean success flag
380 public function addColumn($table, $columndef)
382 $sql = "ALTER TABLE $table ADD COLUMN " . $this->_columnSql($columndef);
384 $res = $this->conn->query($sql);
386 if (PEAR::isError($res)) {
387 throw new Exception($res->getMessage());
394 * Modifies a column in the schema.
396 * The name must match an existing column and table.
398 * @param string $table name of the table
399 * @param ColumnDef $columndef new definition of the column.
401 * @return boolean success flag
404 public function modifyColumn($table, $columndef)
406 $sql = "ALTER TABLE $table MODIFY COLUMN " .
407 $this->_columnSql($columndef);
409 $res = $this->conn->query($sql);
411 if (PEAR::isError($res)) {
412 throw new Exception($res->getMessage());
419 * Drops a column from a table
421 * The name must match an existing column.
423 * @param string $table name of the table
424 * @param string $columnName name of the column to drop
426 * @return boolean success flag
429 public function dropColumn($table, $columnName)
431 $sql = "ALTER TABLE $table DROP COLUMN $columnName";
433 $res = $this->conn->query($sql);
435 if (PEAR::isError($res)) {
436 throw new Exception($res->getMessage());
443 * Ensures that a table exists with the given
444 * name and the given column definitions.
446 * If the table does not yet exist, it will
447 * create the table. If it does exist, it will
448 * alter the table to match the column definitions.
450 * @param string $tableName name of the table
451 * @param array $columns array of ColumnDef
452 * objects for the table
454 * @return boolean success flag
457 public function ensureTable($tableName, $columns)
459 // XXX: DB engine portability -> toilet
462 $td = $this->getTableDef($tableName);
463 } catch (SchemaTableMissingException $e) {
464 return $this->createTable($tableName, $columns);
467 $cur = $this->_names($td->columns);
468 $new = $this->_names($columns);
470 $dropIndex = array();
471 $toadd = array_diff($new, $cur);
472 $todrop = array_diff($cur, $new);
473 $same = array_intersect($new, $cur);
476 $tableProps = array();
478 foreach ($same as $m) {
479 $curCol = $this->_byName($td->columns, $m);
480 $newCol = $this->_byName($columns, $m);
482 if (!$newCol->equals($curCol)) {
483 $tomod[] = $newCol->name;
487 // Earlier versions may have accidentally left tables at default
488 // charsets which might be latin1 or other freakish things.
489 if ($this->_isString($curCol)) {
490 if ($curCol->charset != 'utf8') {
491 $tomod[] = $newCol->name;
497 // Find any indices we have to change...
498 $curIdx = $this->_indexList($td->columns);
499 $newIdx = $this->_indexList($columns);
501 if ($curIdx['primary'] != $newIdx['primary']) {
502 if ($curIdx['primary']) {
503 $dropIndex[] = 'drop primary key';
505 if ($newIdx['primary']) {
506 $keys = implode(',', $newIdx['primary']);
507 $addIndex[] = "add constraint primary key ($keys)";
511 $dropUnique = array_diff($curIdx['uniques'], $newIdx['uniques']);
512 $addUnique = array_diff($newIdx['uniques'], $curIdx['uniques']);
513 foreach ($dropUnique as $columnName) {
514 $dropIndex[] = 'drop key ' . $this->_uniqueKey($tableName, $columnName);
516 foreach ($addUnique as $columnName) {
517 $addIndex[] = 'add constraint unique key ' . $this->_uniqueKey($tableName, $columnName) . " ($columnName)";;
520 $dropMultiple = array_diff($curIdx['indices'], $newIdx['indices']);
521 $addMultiple = array_diff($newIdx['indices'], $curIdx['indices']);
522 foreach ($dropMultiple as $columnName) {
523 $dropIndex[] = 'drop key ' . $this->_key($tableName, $columnName);
525 foreach ($addMultiple as $columnName) {
526 $addIndex[] = 'add key ' . $this->_key($tableName, $columnName) . " ($columnName)";
529 // Check for table properties: make sure we're using a sane
530 // engine type and charset/collation.
531 // @fixme make the default engine configurable?
532 $oldProps = $this->getTableProperties($tableName, array('ENGINE', 'TABLE_COLLATION'));
533 if (strtolower($oldProps['ENGINE']) != 'innodb') {
534 $tableProps['ENGINE'] = 'InnoDB';
536 if (strtolower($oldProps['TABLE_COLLATION']) != 'utf8_bin') {
537 $tableProps['DEFAULT CHARSET'] = 'utf8';
538 $tableProps['COLLATE'] = 'utf8_bin';
541 if (count($dropIndex) + count($toadd) + count($todrop) + count($tomod) + count($addIndex) + count($tableProps) == 0) {
546 // For efficiency, we want this all in one
547 // query, instead of using our methods.
551 foreach ($dropIndex as $indexSql) {
552 $phrase[] = $indexSql;
555 foreach ($toadd as $columnName) {
556 $cd = $this->_byName($columns, $columnName);
558 $phrase[] = 'ADD COLUMN ' . $this->_columnSql($cd);
561 foreach ($todrop as $columnName) {
562 $phrase[] = 'DROP COLUMN ' . $columnName;
565 foreach ($tomod as $columnName) {
566 $cd = $this->_byName($columns, $columnName);
568 $phrase[] = 'MODIFY COLUMN ' . $this->_columnSql($cd);
571 foreach ($addIndex as $indexSql) {
572 $phrase[] = $indexSql;
575 foreach ($tableProps as $key => $val) {
576 $phrase[] = "$key=$val";
579 $sql = 'ALTER TABLE ' . $tableName . ' ' . implode(', ', $phrase);
581 common_log(LOG_DEBUG, __METHOD__ . ': ' . $sql);
582 $res = $this->conn->query($sql);
584 if (PEAR::isError($res)) {
585 throw new Exception($res->getMessage());
592 * Returns the array of names from an array of
595 * @param array $cds array of ColumnDef objects
597 * @return array strings for name values
600 private function _names($cds)
604 foreach ($cds as $cd) {
605 $names[] = $cd->name;
612 * Get a ColumnDef from an array matching
615 * @param array $cds Array of ColumnDef objects
616 * @param string $name Name of the column
618 * @return ColumnDef matching item or null if no match.
621 private function _byName($cds, $name)
623 foreach ($cds as $cd) {
624 if ($cd->name == $name) {
633 * Return the proper SQL for creating or
636 * Appropriate for use in CREATE TABLE or
637 * ALTER TABLE statements.
639 * @param ColumnDef $cd column to create
641 * @return string correct SQL for that column
644 private function _columnSql($cd)
646 $sql = "{$cd->name} ";
648 if (!empty($cd->size)) {
649 $sql .= "{$cd->type}({$cd->size}) ";
651 $sql .= "{$cd->type} ";
654 if ($this->_isString($cd)) {
655 $sql .= " CHARACTER SET utf8 ";
658 if (!empty($cd->default)) {
659 $sql .= "default {$cd->default} ";
661 $sql .= ($cd->nullable) ? "null " : "not null ";
664 if (!empty($cd->auto_increment)) {
665 $sql .= " auto_increment ";
668 if (!empty($cd->extra)) {
669 $sql .= "{$cd->extra} ";
676 * Is this column a string type?
678 private function _isString(ColumnDef $cd)
680 $strings = array('char', 'varchar', 'text');
681 return in_array(strtolower($cd->type), $strings);