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->validateDef($name, $def);
146 $def = $this->filterDef($def);
149 foreach ($def['fields'] as $col => $colDef) {
150 $this->appendColumnDef($sql, $col, $colDef);
153 // Primary, unique, and foreign keys are constraints, so go within
154 // the CREATE TABLE statement normally.
155 if (!empty($def['primary key'])) {
156 $this->appendPrimaryKeyDef($sql, $def['primary key']);
159 if (!empty($def['unique keys'])) {
160 foreach ($def['unique keys'] as $col => $colDef) {
161 $this->appendUniqueKeyDef($sql, $col, $colDef);
165 if (!empty($def['foreign keys'])) {
166 foreach ($def['foreign keys'] as $keyName => $keyDef) {
167 $this->appendForeignKeyDef($sql, $keyName, $keyDef);
171 // Wrap the CREATE TABLE around the main body chunks...
172 $statements = array();
173 $statements[] = $this->startCreateTable($name, $def) . "\n" .
174 implode($sql, ",\n") . "\n" .
175 $this->endCreateTable($name, $def);
177 // Multi-value indexes are advisory and for best portability
178 // should be created as separate statements.
179 if (!empty($def['indexes'])) {
180 foreach ($def['indexes'] as $col => $colDef) {
181 $this->appendCreateIndex($statements, $name, $col, $colDef);
184 if (!empty($def['fulltext indexes'])) {
185 foreach ($def['fulltext indexes'] as $col => $colDef) {
186 $this->appendCreateFulltextIndex($statements, $name, $col, $colDef);
194 * Set up a 'create table' SQL statement.
196 * @param string $name table name
197 * @param array $def table definition
200 function startCreateTable($name, array $def)
202 return 'CREATE TABLE ' . $this->quoteIdentifier($name) . ' (';
206 * Close out a 'create table' SQL statement.
208 * @param string $name table name
209 * @param array $def table definition
212 function endCreateTable($name, array $def)
218 * Append an SQL fragment with a column definition in a CREATE TABLE statement.
221 * @param string $name
224 function appendColumnDef(array &$sql, $name, array $def)
226 $sql[] = "$name " . $this->columnSql($def);
230 * Append an SQL fragment with a constraint definition for a primary
231 * key in a CREATE TABLE statement.
236 function appendPrimaryKeyDef(array &$sql, array $def)
238 $sql[] = "PRIMARY KEY " . $this->buildIndexList($def);
242 * Append an SQL fragment with a constraint definition for a unique
243 * key in a CREATE TABLE statement.
246 * @param string $name
249 function appendUniqueKeyDef(array &$sql, $name, array $def)
251 $sql[] = "CONSTRAINT $name UNIQUE " . $this->buildIndexList($def);
255 * Append an SQL fragment with a constraint definition for a foreign
256 * key in a CREATE TABLE statement.
259 * @param string $name
262 function appendForeignKeyDef(array &$sql, $name, array $def)
264 if (count($def) != 2) {
265 throw new Exception("Invalid foreign key def for $name: " . var_export($def, true));
267 list($refTable, $map) = $def;
268 $srcCols = array_keys($map);
269 $refCols = array_values($map);
270 $sql[] = "CONSTRAINT $name FOREIGN KEY " .
271 $this->buildIndexList($srcCols) .
273 $this->quoteIdentifier($refTable) .
275 $this->buildIndexList($refCols);
279 * Append an SQL statement with an index definition for an advisory
280 * index over one or more columns on a table.
282 * @param array $statements
283 * @param string $table
284 * @param string $name
287 function appendCreateIndex(array &$statements, $table, $name, array $def)
289 $statements[] = "CREATE INDEX $name ON $table " . $this->buildIndexList($def);
293 * Append an SQL statement with an index definition for a full-text search
294 * index over one or more columns on a table.
296 * @param array $statements
297 * @param string $table
298 * @param string $name
301 function appendCreateFulltextIndex(array &$statements, $table, $name, array $def)
303 throw new Exception("Fulltext index not supported in this database");
307 * Append an SQL statement to drop an index from a table.
309 * @param array $statements
310 * @param string $table
311 * @param string $name
314 function appendDropIndex(array &$statements, $table, $name)
316 $statements[] = "DROP INDEX $name ON " . $this->quoteIdentifier($table);
319 function buildIndexList(array $def)
322 return '(' . implode(',', array_map(array($this, 'buildIndexItem'), $def)) . ')';
325 function buildIndexItem($def)
327 if (is_array($def)) {
328 list($name, $size) = $def;
329 return $this->quoteIdentifier($name) . '(' . intval($size) . ')';
331 return $this->quoteIdentifier($def);
335 * Drops a table from the schema
337 * Throws an exception if the table is not found.
339 * @param string $name Name of the table to drop
341 * @return boolean success flag
344 public function dropTable($name)
346 $res = $this->conn->query("DROP TABLE $name");
348 if (PEAR::isError($res)) {
349 throw new Exception($res->getMessage());
356 * Adds an index to a table.
358 * If no name is provided, a name will be made up based
359 * on the table name and column names.
361 * Throws an exception on database error, esp. if the table
364 * @param string $table Name of the table
365 * @param array $columnNames Name of columns to index
366 * @param string $name (Optional) name of the index
368 * @return boolean success flag
371 public function createIndex($table, $columnNames, $name=null)
373 if (!is_array($columnNames)) {
374 $columnNames = array($columnNames);
378 $name = "{$table}_".implode("_", $columnNames)."_idx";
381 $res = $this->conn->query("ALTER TABLE $table ".
383 implode(",", $columnNames).")");
385 if (PEAR::isError($res)) {
386 throw new Exception($res->getMessage());
393 * Drops a named index from a table.
395 * @param string $table name of the table the index is on.
396 * @param string $name name of the index
398 * @return boolean success flag
401 public function dropIndex($table, $name)
403 $res = $this->conn->query("ALTER TABLE $table DROP INDEX $name");
405 if (PEAR::isError($res)) {
406 throw new Exception($res->getMessage());
413 * Adds a column to a table
415 * @param string $table name of the table
416 * @param ColumnDef $columndef Definition of the new
419 * @return boolean success flag
422 public function addColumn($table, $columndef)
424 $sql = "ALTER TABLE $table ADD COLUMN " . $this->_columnSql($columndef);
426 $res = $this->conn->query($sql);
428 if (PEAR::isError($res)) {
429 throw new Exception($res->getMessage());
436 * Modifies a column in the schema.
438 * The name must match an existing column and table.
440 * @param string $table name of the table
441 * @param ColumnDef $columndef new definition of the column.
443 * @return boolean success flag
446 public function modifyColumn($table, $columndef)
448 $sql = "ALTER TABLE $table MODIFY COLUMN " .
449 $this->_columnSql($columndef);
451 $res = $this->conn->query($sql);
453 if (PEAR::isError($res)) {
454 throw new Exception($res->getMessage());
461 * Drops a column from a table
463 * The name must match an existing column.
465 * @param string $table name of the table
466 * @param string $columnName name of the column to drop
468 * @return boolean success flag
471 public function dropColumn($table, $columnName)
473 $sql = "ALTER TABLE $table DROP COLUMN $columnName";
475 $res = $this->conn->query($sql);
477 if (PEAR::isError($res)) {
478 throw new Exception($res->getMessage());
485 * Ensures that a table exists with the given
486 * name and the given column definitions.
488 * If the table does not yet exist, it will
489 * create the table. If it does exist, it will
490 * alter the table to match the column definitions.
492 * @param string $tableName name of the table
493 * @param array $def Table definition array
495 * @return boolean success flag
498 public function ensureTable($tableName, $def)
500 $statements = $this->buildEnsureTable($tableName, $def);
501 return $this->runSqlSet($statements);
505 * Run a given set of SQL commands on the connection in sequence.
508 * @fixme if multiple statements, wrap in a transaction?
509 * @param array $statements
510 * @return boolean success flag
512 function runSqlSet(array $statements)
515 foreach ($statements as $sql) {
516 if (defined('DEBUG_INSTALLER')) {
517 echo "<tt>" . htmlspecialchars($sql) . "</tt><br/>\n";
519 $res = $this->conn->query($sql);
521 if (PEAR::isError($res)) {
522 throw new Exception($res->getMessage());
529 * Check a table's status, and if needed build a set
530 * of SQL statements which change it to be consistent
531 * with the given table definition.
533 * If the table does not yet exist, statements will
534 * be returned to create the table. If it does exist,
535 * statements will be returned to alter the table to
536 * match the column definitions.
538 * @param string $tableName name of the table
539 * @param array $columns array of ColumnDef
540 * objects for the table
542 * @return array of SQL statements
545 function buildEnsureTable($tableName, array $def)
548 $old = $this->getTableDef($tableName);
549 } catch (SchemaTableMissingException $e) {
550 return $this->buildCreateTable($tableName, $def);
553 // Filter the DB-independent table definition to match the current
554 // database engine's features and limitations.
555 $def = $this->validateDef($tableName, $def);
556 $def = $this->filterDef($def);
558 $statements = array();
559 $fields = $this->diffArrays($old, $def, 'fields', array($this, 'columnsEqual'));
560 $uniques = $this->diffArrays($old, $def, 'unique keys');
561 $indexes = $this->diffArrays($old, $def, 'indexes');
562 $foreign = $this->diffArrays($old, $def, 'foreign keys');
564 // Drop any obsolete or modified indexes ahead...
565 foreach ($indexes['del'] + $indexes['mod'] as $indexName) {
566 $this->appendDropIndex($statements, $tableName, $indexName);
569 // For efficiency, we want this all in one
570 // query, instead of using our methods.
574 foreach ($foreign['del'] + $foreign['mod'] as $keyName) {
575 $this->appendAlterDropForeign($phrase, $keyName);
578 foreach ($uniques['del'] + $uniques['mod'] as $keyName) {
579 $this->appendAlterDropUnique($phrase, $keyName);
582 if (isset($old['primary key']) && (!isset($def['primary key']) || $def['primary key'] != $old['primary key'])) {
583 $this->appendAlterDropPrimary($phrase);
586 foreach ($fields['add'] as $columnName) {
587 $this->appendAlterAddColumn($phrase, $columnName,
588 $def['fields'][$columnName]);
591 foreach ($fields['mod'] as $columnName) {
592 $this->appendAlterModifyColumn($phrase, $columnName,
593 $old['fields'][$columnName],
594 $def['fields'][$columnName]);
597 foreach ($fields['del'] as $columnName) {
598 $this->appendAlterDropColumn($phrase, $columnName);
601 if (isset($def['primary key']) && (!isset($old['primary key']) || $old['primary key'] != $def['primary key'])) {
602 $this->appendAlterAddPrimary($phrase, $def['primary key']);
605 foreach ($uniques['mod'] + $uniques['add'] as $keyName) {
606 $this->appendAlterAddUnique($phrase, $keyName, $def['unique keys'][$keyName]);
609 foreach ($foreign['mod'] + $foreign['add'] as $keyName) {
610 $this->appendAlterAddForeign($phrase, $keyName, $def['foreign keys'][$keyName]);
613 $this->appendAlterExtras($phrase, $tableName, $def);
615 if (count($phrase) > 0) {
616 $sql = 'ALTER TABLE ' . $tableName . ' ' . implode(",\n", $phrase);
617 $statements[] = $sql;
620 // Now create any indexes...
621 foreach ($indexes['mod'] + $indexes['add'] as $indexName) {
622 $this->appendCreateIndex($statements, $tableName, $indexName, $def['indexes'][$indexName]);
628 function diffArrays($oldDef, $newDef, $section, $compareCallback=null)
630 $old = isset($oldDef[$section]) ? $oldDef[$section] : array();
631 $new = isset($newDef[$section]) ? $newDef[$section] : array();
633 $oldKeys = array_keys($old);
634 $newKeys = array_keys($new);
636 $toadd = array_diff($newKeys, $oldKeys);
637 $todrop = array_diff($oldKeys, $newKeys);
638 $same = array_intersect($newKeys, $oldKeys);
642 // Find which fields have actually changed definition
643 // in a way that we need to tweak them for this DB type.
644 foreach ($same as $name) {
645 if ($compareCallback) {
646 $same = call_user_func($compareCallback, $old[$name], $new[$name]);
648 $same = ($old[$name] == $new[$name]);
656 return array('add' => $toadd,
660 'count' => count($toadd) + count($todrop) + count($tomod));
664 * Append phrase(s) to an array of partial ALTER TABLE chunks in order
665 * to add the given column definition to the table.
667 * @param array $phrase
668 * @param string $columnName
671 function appendAlterAddColumn(array &$phrase, $columnName, array $cd)
673 $phrase[] = 'ADD COLUMN ' .
674 $this->quoteIdentifier($columnName) .
676 $this->columnSql($cd);
680 * Append phrase(s) to an array of partial ALTER TABLE chunks in order
681 * to alter the given column from its old state to a new one.
683 * @param array $phrase
684 * @param string $columnName
685 * @param array $old previous column definition as found in DB
686 * @param array $cd current column definition
688 function appendAlterModifyColumn(array &$phrase, $columnName, array $old, array $cd)
690 $phrase[] = 'MODIFY COLUMN ' .
691 $this->quoteIdentifier($columnName) .
693 $this->columnSql($cd);
697 * Append phrase(s) to an array of partial ALTER TABLE chunks in order
698 * to drop the given column definition from the table.
700 * @param array $phrase
701 * @param string $columnName
703 function appendAlterDropColumn(array &$phrase, $columnName)
705 $phrase[] = 'DROP COLUMN ' . $this->quoteIdentifier($columnName);
708 function appendAlterAddUnique(array &$phrase, $keyName, array $def)
712 $this->appendUniqueKeyDef($sql, $keyName, $def);
713 $phrase[] = implode(' ', $sql);
716 function appendAlterAddForeign(array &$phrase, $keyName, array $def)
720 $this->appendForeignKeyDef($sql, $keyName, $def);
721 $phrase[] = implode(' ', $sql);
724 function appendAlterAddPrimary(array &$phrase, array $def)
728 $this->appendPrimaryKeyDef($sql, $def);
729 $phrase[] = implode(' ', $sql);
732 function appendAlterDropPrimary(array &$phrase)
734 $phrase[] = 'DROP CONSTRAINT PRIMARY KEY';
737 function appendAlterDropUnique(array &$phrase, $keyName)
739 $phrase[] = 'DROP CONSTRAINT ' . $keyName;
742 function appendAlterDropForeign(array &$phrase, $keyName)
744 $phrase[] = 'DROP FOREIGN KEY ' . $keyName;
747 function appendAlterExtras(array &$phrase, $tableName, array $def)
753 * Quote a db/table/column identifier if necessary.
755 * @param string $name
758 function quoteIdentifier($name)
763 function quoteDefaultValue($cd)
765 if ($cd['type'] == 'datetime' && $cd['default'] == 'CURRENT_TIMESTAMP') {
766 return $cd['default'];
768 return $this->quoteValue($cd['default']);
772 function quoteValue($val)
774 return $this->conn->quoteSmart($val);
778 * Check if two column definitions are equivalent.
779 * The default implementation checks _everything_ but in many cases
780 * you may be able to discard a bunch of equivalencies.
786 function columnsEqual(array $a, array $b)
788 return !array_diff_assoc($a, $b) && !array_diff_assoc($b, $a);
792 * Returns the array of names from an array of
795 * @param array $cds array of ColumnDef objects
797 * @return array strings for name values
800 protected function _names($cds)
804 foreach ($cds as $cd) {
805 $names[] = $cd->name;
812 * Get a ColumnDef from an array matching
815 * @param array $cds Array of ColumnDef objects
816 * @param string $name Name of the column
818 * @return ColumnDef matching item or null if no match.
821 protected function _byName($cds, $name)
823 foreach ($cds as $cd) {
824 if ($cd->name == $name) {
833 * Return the proper SQL for creating or
836 * Appropriate for use in CREATE TABLE or
837 * ALTER TABLE statements.
839 * @param ColumnDef $cd column to create
841 * @return string correct SQL for that column
844 function columnSql(array $cd)
847 $line[] = $this->typeAndSize($cd);
849 if (isset($cd['default'])) {
851 $line[] = $this->quoteDefaultValue($cd);
852 } else if (!empty($cd['not null'])) {
853 // Can't have both not null AND default!
854 $line[] = 'not null';
857 return implode(' ', $line);
862 * @param string $column canonical type name in defs
863 * @return string native DB type name
865 function mapType($column)
870 function typeAndSize($column)
872 //$type = $this->mapType($column);
873 $type = $column['type'];
874 if (isset($column['size'])) {
875 $type = $column['size'] . $type;
879 if (isset($column['precision'])) {
880 $lengths[] = $column['precision'];
881 if (isset($column['scale'])) {
882 $lengths[] = $column['scale'];
884 } else if (isset($column['length'])) {
885 $lengths[] = $column['length'];
889 return $type . '(' . implode(',', $lengths) . ')';
896 * Convert an old-style set of ColumnDef objects into the current
897 * Drupal-style schema definition array, for backwards compatibility
898 * with plugins written for 0.9.x.
900 * @param string $tableName
901 * @param array $defs: array of ColumnDef objects
904 protected function oldToNew($tableName, array $defs)
913 foreach ($defs as $cd) {
915 $column['type'] = $cd->type;
916 foreach ($prefixes as $prefix) {
917 if (substr($cd->type, 0, strlen($prefix)) == $prefix) {
918 $column['type'] = substr($cd->type, strlen($prefix));
919 $column['size'] = $prefix;
925 if ($cd->type == 'varchar' || $cd->type == 'char') {
926 $column['length'] = $cd->size;
929 if (!$cd->nullable) {
930 $column['not null'] = true;
932 if ($cd->auto_increment) {
933 $column['type'] = 'serial';
936 $column['default'] = $cd->default;
938 $table['fields'][$cd->name] = $column;
940 if ($cd->key == 'PRI') {
941 // If multiple columns are defined as primary key,
942 // we'll pile them on in sequence.
943 if (!isset($table['primary key'])) {
944 $table['primary key'] = array();
946 $table['primary key'][] = $cd->name;
947 } else if ($cd->key == 'MUL') {
948 // Individual multiple-value indexes are only per-column
949 // using the old ColumnDef syntax.
950 $idx = "{$tableName}_{$cd->name}_idx";
951 $table['indexes'][$idx] = array($cd->name);
952 } else if ($cd->key == 'UNI') {
953 // Individual unique-value indexes are only per-column
954 // using the old ColumnDef syntax.
955 $idx = "{$tableName}_{$cd->name}_idx";
956 $table['unique keys'][$idx] = array($cd->name);
964 * Filter the given table definition array to match features available
967 * This lets us strip out unsupported things like comments, foreign keys,
968 * or type variants that we wouldn't get back from getTableDef().
970 * @param array $tableDef
972 function filterDef(array $tableDef)
978 * Validate a table definition array, checking for basic structure.
980 * If necessary, converts from an old-style array of ColumnDef objects.
982 * @param string $tableName
983 * @param array $def: table definition array
984 * @return array validated table definition array
986 * @throws Exception on wildly invalid input
988 function validateDef($tableName, array $def)
990 if (isset($def[0]) && $def[0] instanceof ColumnDef) {
991 $def = $this->oldToNew($tableName, $def);
994 // A few quick checks :D
995 if (!isset($def['fields'])) {
996 throw new Exception("Invalid table definition for $tableName: no fields.");
1002 function isNumericType($type)
1004 $type = strtolower($type);
1005 $known = array('int', 'serial', 'numeric');
1006 return in_array($type, $known);
1010 * Pull info from the query into a fun-fun array of dooooom
1012 * @param string $sql
1013 * @return array of arrays
1015 protected function fetchQueryData($sql)
1017 $res = $this->conn->query($sql);
1018 if (PEAR::isError($res)) {
1019 throw new Exception($res->getMessage());
1024 while ($res->fetchInto($row, DB_FETCHMODE_ASSOC)) {
1034 class SchemaTableMissingException extends Exception