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 * @author Brion Vibber <brion@status.net>
45 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
46 * @link http://status.net/
51 static $_static = null;
52 protected $conn = null;
55 * Constructor. Only run once for singleton object.
58 protected function __construct($conn = null)
61 // XXX: there should be an easier way to do this.
63 $conn = $user->getDatabaseConnection();
72 * Main public entry point. Use this to get
75 * @return Schema the Schema object for the connection
78 static function get($conn = null)
83 $key = md5(serialize($conn->dsn));
86 $type = common_config('db', 'type');
87 if (empty(self::$_static[$key])) {
88 $schemaClass = ucfirst($type).'Schema';
89 self::$_static[$key] = new $schemaClass($conn);
91 return self::$_static[$key];
95 * Gets a ColumnDef object for a single column.
97 * Throws an exception if the table is not found.
99 * @param string $table name of the table
100 * @param string $column name of the column
102 * @return ColumnDef definition of the column or null
106 public function getColumnDef($table, $column)
108 $td = $this->getTableDef($table);
110 foreach ($td->columns as $cd) {
111 if ($cd->name == $column) {
120 * Creates a table with the given names and columns.
122 * @param string $tableName Name of the table
123 * @param array $def Table definition array listing fields and indexes.
125 * @return boolean success flag
128 public function createTable($tableName, $def)
130 $statements = $this->buildCreateTable($tableName, $def);
131 return $this->runSqlSet($statements);
135 * Build a set of SQL statements to create a table with the given
138 * @param string $name Name of the table
139 * @param array $def Table definition array
141 * @return boolean success flag
143 public function buildCreateTable($name, $def)
145 $def = $this->filterDef($def);
148 foreach ($def['fields'] as $col => $colDef) {
149 $this->appendColumnDef($sql, $col, $colDef);
152 // Primary, unique, and foreign keys are constraints, so go within
153 // the CREATE TABLE statement normally.
154 if (!empty($def['primary key'])) {
155 $this->appendPrimaryKeyDef($sql, $def['primary key']);
158 if (!empty($def['unique keys'])) {
159 foreach ($def['unique keys'] as $col => $colDef) {
160 $this->appendUniqueKeyDef($sql, $col, $colDef);
164 if (!empty($def['foreign keys'])) {
165 foreach ($def['foreign keys'] as $keyName => $keyDef) {
166 $this->appendForeignKeyDef($sql, $keyName, $keyDef);
170 // Multi-value indexes are advisory and for best portability
171 // should be created as separate statements.
172 $statements = array();
173 $statements[] = $this->startCreateTable($name, $def) . "\n" .
174 implode($sql, ",\n") . "\n" .
175 $this->endCreateTable($name, $def);
176 if (!empty($def['indexes'])) {
177 foreach ($def['indexes'] as $col => $colDef) {
178 $this->appendCreateIndex($statements, $name, $col, $colDef);
186 * Set up a 'create table' SQL statement.
188 * @param string $name table name
189 * @param array $def table definition
192 function startCreateTable($name, array $def)
194 return 'CREATE TABLE ' . $this->quoteIdentifier($name) . ' (';
198 * Close out a 'create table' SQL statement.
200 * @param string $name table name
201 * @param array $def table definition
204 function endCreateTable($name, array $def)
210 * Append an SQL fragment with a column definition in a CREATE TABLE statement.
213 * @param string $name
216 function appendColumnDef(array &$sql, $name, array $def)
218 $sql[] = "$name " . $this->columnSql($def);
222 * Append an SQL fragment with a constraint definition for a primary
223 * key in a CREATE TABLE statement.
228 function appendPrimaryKeyDef(array &$sql, array $def)
230 $sql[] = "PRIMARY KEY " . $this->buildIndexList($def);
234 * Append an SQL fragment with a constraint definition for a unique
235 * key in a CREATE TABLE statement.
238 * @param string $name
241 function appendUniqueKeyDef(array &$sql, $name, array $def)
243 $sql[] = "CONSTRAINT $name UNIQUE " . $this->buildIndexList($def);
247 * Append an SQL fragment with a constraint definition for a foreign
248 * key in a CREATE TABLE statement.
251 * @param string $name
254 function appendForeignKeyDef(array &$sql, $name, array $def)
256 list($refTable, $map) = $def;
257 $srcCols = array_keys($map);
258 $refCols = array_values($map);
259 $sql[] = "CONSTRAINT $name FOREIGN KEY " .
260 $this->buildIndexList($srcCols) .
262 $this->quoteIdentifier($refTable) .
264 $this->buildIndexList($refCols);
268 * Append an SQL statement with an index definition for an advisory
269 * index over one or more columns on a table.
271 * @param array $statements
272 * @param string $table
273 * @param string $name
276 function appendCreateIndex(array &$statements, $table, $name, array $def)
278 $statements[] = "CREATE INDEX $name ON $table " . $this->buildIndexList($def);
282 * Append an SQL statement to drop an index from a table.
284 * @param array $statements
285 * @param string $table
286 * @param string $name
289 function appendDropIndex(array &$statements, $table, $name)
291 $statements[] = "DROP INDEX $name ON " . $this->quoteIdentifier($table);
294 function buildIndexList(array $def)
297 return '(' . implode(',', array_map(array($this, 'buildIndexItem'), $def)) . ')';
300 function buildIndexItem($def)
302 if (is_array($def)) {
303 list($name, $size) = $def;
304 return $this->quoteIdentifier($name) . '(' . intval($size) . ')';
306 return $this->quoteIdentifier($def);
310 * Drops a table from the schema
312 * Throws an exception if the table is not found.
314 * @param string $name Name of the table to drop
316 * @return boolean success flag
319 public function dropTable($name)
321 $res = $this->conn->query("DROP TABLE $name");
323 if (PEAR::isError($res)) {
324 throw new Exception($res->getMessage());
331 * Adds an index to a table.
333 * If no name is provided, a name will be made up based
334 * on the table name and column names.
336 * Throws an exception on database error, esp. if the table
339 * @param string $table Name of the table
340 * @param array $columnNames Name of columns to index
341 * @param string $name (Optional) name of the index
343 * @return boolean success flag
346 public function createIndex($table, $columnNames, $name=null)
348 if (!is_array($columnNames)) {
349 $columnNames = array($columnNames);
353 $name = "{$table}_".implode("_", $columnNames)."_idx";
356 $res = $this->conn->query("ALTER TABLE $table ".
358 implode(",", $columnNames).")");
360 if (PEAR::isError($res)) {
361 throw new Exception($res->getMessage());
368 * Drops a named index from a table.
370 * @param string $table name of the table the index is on.
371 * @param string $name name of the index
373 * @return boolean success flag
376 public function dropIndex($table, $name)
378 $res = $this->conn->query("ALTER TABLE $table DROP INDEX $name");
380 if (PEAR::isError($res)) {
381 throw new Exception($res->getMessage());
388 * Adds a column to a table
390 * @param string $table name of the table
391 * @param ColumnDef $columndef Definition of the new
394 * @return boolean success flag
397 public function addColumn($table, $columndef)
399 $sql = "ALTER TABLE $table ADD COLUMN " . $this->_columnSql($columndef);
401 $res = $this->conn->query($sql);
403 if (PEAR::isError($res)) {
404 throw new Exception($res->getMessage());
411 * Modifies a column in the schema.
413 * The name must match an existing column and table.
415 * @param string $table name of the table
416 * @param ColumnDef $columndef new definition of the column.
418 * @return boolean success flag
421 public function modifyColumn($table, $columndef)
423 $sql = "ALTER TABLE $table MODIFY COLUMN " .
424 $this->_columnSql($columndef);
426 $res = $this->conn->query($sql);
428 if (PEAR::isError($res)) {
429 throw new Exception($res->getMessage());
436 * Drops a column from a table
438 * The name must match an existing column.
440 * @param string $table name of the table
441 * @param string $columnName name of the column to drop
443 * @return boolean success flag
446 public function dropColumn($table, $columnName)
448 $sql = "ALTER TABLE $table DROP COLUMN $columnName";
450 $res = $this->conn->query($sql);
452 if (PEAR::isError($res)) {
453 throw new Exception($res->getMessage());
460 * Ensures that a table exists with the given
461 * name and the given column definitions.
463 * If the table does not yet exist, it will
464 * create the table. If it does exist, it will
465 * alter the table to match the column definitions.
467 * @param string $tableName name of the table
468 * @param array $def Table definition array
470 * @return boolean success flag
473 public function ensureTable($tableName, $def)
475 $statements = $this->buildEnsureTable($tableName, $def);
476 return $this->runSqlSet($statements);
480 * Run a given set of SQL commands on the connection in sequence.
483 * @fixme if multiple statements, wrap in a transaction?
484 * @param array $statements
485 * @return boolean success flag
487 function runSqlSet(array $statements)
490 foreach ($statements as $sql) {
491 if (defined('DEBUG_INSTALLER')) {
492 echo "<tt>" . htmlspecialchars($sql) . "</tt><br/>\n";
494 $res = $this->conn->query($sql);
496 if (PEAR::isError($res)) {
497 throw new Exception($res->getMessage());
504 * Check a table's status, and if needed build a set
505 * of SQL statements which change it to be consistent
506 * with the given table definition.
508 * If the table does not yet exist, statements will
509 * be returned to create the table. If it does exist,
510 * statements will be returned to alter the table to
511 * match the column definitions.
513 * @param string $tableName name of the table
514 * @param array $columns array of ColumnDef
515 * objects for the table
517 * @return array of SQL statements
520 function buildEnsureTable($tableName, $def)
523 $old = $this->getTableDef($tableName);
524 } catch (SchemaTableMissingException $e) {
525 return $this->buildCreateTable($tableName, $def);
528 // Filter the DB-independent table definition to match the current
529 // database engine's features and limitations.
530 $def = $this->filterDef($def);
532 $statements = array();
533 $fields = $this->diffArrays($old, $def, 'fields', array($this, 'columnsEqual'));
534 $uniques = $this->diffArrays($old, $def, 'unique keys');
535 $indexes = $this->diffArrays($old, $def, 'indexes');
536 $foreign = $this->diffArrays($old, $def, 'foreign keys');
538 // Drop any obsolete or modified indexes ahead...
539 foreach ($indexes['del'] + $indexes['mod'] as $indexName) {
540 $this->appendDropIndex($statements, $tableName, $indexName);
543 // For efficiency, we want this all in one
544 // query, instead of using our methods.
548 foreach ($foreign['del'] + $foreign['mod'] as $keyName) {
549 $this->appendAlterDropForeign($phrase, $keyName);
552 foreach ($uniques['del'] + $uniques['mod'] as $keyName) {
553 $this->appendAlterDropUnique($phrase, $keyName);
556 foreach ($fields['add'] as $columnName) {
557 $this->appendAlterAddColumn($phrase, $columnName,
558 $def['fields'][$columnName]);
561 foreach ($fields['mod'] as $columnName) {
562 $this->appendAlterModifyColumn($phrase, $columnName,
563 $old['fields'][$columnName],
564 $def['fields'][$columnName]);
567 foreach ($fields['del'] as $columnName) {
568 $this->appendAlterDropColumn($phrase, $columnName);
571 foreach ($uniques['mod'] + $uniques['add'] as $keyName) {
572 $this->appendAlterAddUnique($phrase, $keyName, $def['unique keys'][$keyName]);
575 foreach ($foreign['mod'] + $foreign['add'] as $keyName) {
576 $this->appendAlterAddForeign($phrase, $keyName, $def['foreign keys'][$keyName]);
579 $this->appendAlterExtras($phrase, $tableName);
581 if (count($phrase) > 0) {
582 $sql = 'ALTER TABLE ' . $tableName . ' ' . implode(",\n", $phrase);
583 $statements[] = $sql;
586 // Now create any indexes...
587 foreach ($indexes['mod'] + $indexes['add'] as $indexName) {
588 $this->appendCreateIndex($statements, $tableName, $indexName, $def['indexes'][$indexName]);
594 function diffArrays($oldDef, $newDef, $section, $compareCallback=null)
596 $old = isset($oldDef[$section]) ? $oldDef[$section] : array();
597 $new = isset($newDef[$section]) ? $newDef[$section] : array();
599 $oldKeys = array_keys($old);
600 $newKeys = array_keys($new);
602 $toadd = array_diff($newKeys, $oldKeys);
603 $todrop = array_diff($oldKeys, $newKeys);
604 $same = array_intersect($newKeys, $oldKeys);
608 // Find which fields have actually changed definition
609 // in a way that we need to tweak them for this DB type.
610 foreach ($same as $name) {
611 if ($compareCallback) {
612 $same = call_user_func($compareCallback, $old[$name], $new[$name]);
614 $same = ($old[$name] == $new[$name]);
622 return array('add' => $toadd,
626 'count' => count($toadd) + count($todrop) + count($tomod));
630 * Append phrase(s) to an array of partial ALTER TABLE chunks in order
631 * to add the given column definition to the table.
633 * @param array $phrase
634 * @param string $columnName
637 function appendAlterAddColumn(array &$phrase, $columnName, array $cd)
639 $phrase[] = 'ADD COLUMN ' .
640 $this->quoteIdentifier($columnName) .
642 $this->columnSql($cd);
646 * Append phrase(s) to an array of partial ALTER TABLE chunks in order
647 * to alter the given column from its old state to a new one.
649 * @param array $phrase
650 * @param string $columnName
651 * @param array $old previous column definition as found in DB
652 * @param array $cd current column definition
654 function appendAlterModifyColumn(array &$phrase, $columnName, array $old, array $cd)
656 $phrase[] = 'MODIFY COLUMN ' .
657 $this->quoteIdentifier($columnName) .
659 $this->columnSql($cd);
663 * Append phrase(s) to an array of partial ALTER TABLE chunks in order
664 * to drop the given column definition from the table.
666 * @param array $phrase
667 * @param string $columnName
669 function appendAlterDropColumn(array &$phrase, $columnName)
671 $phrase[] = 'DROP COLUMN ' . $this->quoteIdentifier($columnName);
674 function appendAlterAddUnique(array &$phrase, $keyName, array $def)
678 $this->appendUniqueKeyDef($sql, $keyName, $def);
679 $phrase[] = implode(' ', $sql);
682 function appendAlterAddForeign(array &$phrase, $keyName, array $def)
686 $this->appendForeignKeyDef($sql, $keyName, $def);
687 $phrase[] = implode(' ', $sql);
690 function appendAlterDropUnique(array &$phrase, $keyName)
692 $phrase[] = 'DROP CONSTRAINT ' . $keyName;
695 function appendAlterDropForeign(array &$phrase, $keyName)
697 $phrase[] = 'DROP FOREIGN KEY ' . $keyName;
700 function appendAlterExtras(array &$phrase, $tableName)
706 * Quote a db/table/column identifier if necessary.
708 * @param string $name
711 function quoteIdentifier($name)
716 function quoteDefaultValue($cd)
718 if ($cd['type'] == 'datetime' && $cd['default'] == 'CURRENT_TIMESTAMP') {
719 return $cd['default'];
721 return $this->quoteValue($cd['default']);
725 function quoteValue($val)
727 return $this->conn->quoteSmart($val);
731 * Check if two column definitions are equivalent.
732 * The default implementation checks _everything_ but in many cases
733 * you may be able to discard a bunch of equivalencies.
739 function columnsEqual(array $a, array $b)
741 return !array_diff_assoc($a, $b) && !array_diff_assoc($b, $a);
745 * Returns the array of names from an array of
748 * @param array $cds array of ColumnDef objects
750 * @return array strings for name values
753 protected function _names($cds)
757 foreach ($cds as $cd) {
758 $names[] = $cd->name;
765 * Get a ColumnDef from an array matching
768 * @param array $cds Array of ColumnDef objects
769 * @param string $name Name of the column
771 * @return ColumnDef matching item or null if no match.
774 protected function _byName($cds, $name)
776 foreach ($cds as $cd) {
777 if ($cd->name == $name) {
786 * Return the proper SQL for creating or
789 * Appropriate for use in CREATE TABLE or
790 * ALTER TABLE statements.
792 * @param ColumnDef $cd column to create
794 * @return string correct SQL for that column
797 function columnSql(array $cd)
800 $line[] = $this->typeAndSize($cd);
802 if (isset($cd['default'])) {
804 $line[] = $this->quoteDefaultValue($cd);
805 } else if (!empty($cd['not null'])) {
806 // Can't have both not null AND default!
807 $line[] = 'not null';
810 return implode(' ', $line);
815 * @param string $column canonical type name in defs
816 * @return string native DB type name
818 function mapType($column)
823 function typeAndSize($column)
825 //$type = $this->mapType($column);
826 $type = $column['type'];
827 if (isset($column['size'])) {
828 $type = $column['size'] . $type;
832 if (isset($column['precision'])) {
833 $lengths[] = $column['precision'];
834 if (isset($column['scale'])) {
835 $lengths[] = $column['scale'];
837 } else if (isset($column['length'])) {
838 $lengths[] = $column['length'];
842 return $type . '(' . implode(',', $lengths) . ')';
849 * Convert an old-style set of ColumnDef objects into the current
850 * Drupal-style schema definition array, for backwards compatibility
851 * with plugins written for 0.9.x.
853 * @param string $tableName
857 function oldToNew($tableName, $defs)
866 foreach ($defs as $cd) {
867 $cd->addToTableDef($table);
869 $column['type'] = $cd->type;
870 foreach ($prefixes as $prefix) {
871 if (substr($cd->type, 0, strlen($prefix)) == $prefix) {
872 $column['type'] = substr($cd->type, strlen($prefix));
873 $column['size'] = $prefix;
879 if ($cd->type == 'varchar' || $cd->type == 'char') {
880 $column['length'] = $cd->size;
883 if (!$cd->nullable) {
884 $column['not null'] = true;
886 if ($cd->autoincrement) {
887 $column['type'] = 'serial';
890 $column['default'] = $cd->default;
892 $table['fields'][$cd->name] = $column;
894 if ($cd->key == 'PRI') {
895 // If multiple columns are defined as primary key,
896 // we'll pile them on in sequence.
897 if (!isset($table['primary key'])) {
898 $table['primary key'] = array();
900 $table['primary key'][] = $cd->name;
901 } else if ($cd->key == 'MUL') {
902 // Individual multiple-value indexes are only per-column
903 // using the old ColumnDef syntax.
904 $idx = "{$tableName}_{$cd->name}_idx";
905 $table['indexes'][$idx] = array($cd->name);
906 } else if ($cd->key == 'UNI') {
907 // Individual unique-value indexes are only per-column
908 // using the old ColumnDef syntax.
909 $idx = "{$tableName}_{$cd->name}_idx";
910 $table['unique keys'][$idx] = array($cd->name);
918 * Filter the given table definition array to match features available
921 * This lets us strip out unsupported things like comments, foreign keys,
922 * or type variants that we wouldn't get back from getTableDef().
924 * @param array $tableDef
926 function filterDef(array $tableDef)
931 function isNumericType($type)
933 $type = strtolower($type);
934 $known = array('int', 'serial', 'numeric');
935 return in_array($type, $known);
939 * Pull info from the query into a fun-fun array of dooooom
942 * @return array of arrays
944 protected function fetchQueryData($sql)
946 $res = $this->conn->query($sql);
947 if (PEAR::isError($res)) {
948 throw new Exception($res->getMessage());
953 while ($res->fetchInto($row, DB_FETCHMODE_ASSOC)) {
963 class SchemaTableMissingException extends Exception