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 foreach ($fields['add'] as $columnName) {
583 $this->appendAlterAddColumn($phrase, $columnName,
584 $def['fields'][$columnName]);
587 foreach ($fields['mod'] as $columnName) {
588 $this->appendAlterModifyColumn($phrase, $columnName,
589 $old['fields'][$columnName],
590 $def['fields'][$columnName]);
593 foreach ($fields['del'] as $columnName) {
594 $this->appendAlterDropColumn($phrase, $columnName);
597 foreach ($uniques['mod'] + $uniques['add'] as $keyName) {
598 $this->appendAlterAddUnique($phrase, $keyName, $def['unique keys'][$keyName]);
601 foreach ($foreign['mod'] + $foreign['add'] as $keyName) {
602 $this->appendAlterAddForeign($phrase, $keyName, $def['foreign keys'][$keyName]);
605 $this->appendAlterExtras($phrase, $tableName, $def);
607 if (count($phrase) > 0) {
608 $sql = 'ALTER TABLE ' . $tableName . ' ' . implode(",\n", $phrase);
609 $statements[] = $sql;
612 // Now create any indexes...
613 foreach ($indexes['mod'] + $indexes['add'] as $indexName) {
614 $this->appendCreateIndex($statements, $tableName, $indexName, $def['indexes'][$indexName]);
620 function diffArrays($oldDef, $newDef, $section, $compareCallback=null)
622 $old = isset($oldDef[$section]) ? $oldDef[$section] : array();
623 $new = isset($newDef[$section]) ? $newDef[$section] : array();
625 $oldKeys = array_keys($old);
626 $newKeys = array_keys($new);
628 $toadd = array_diff($newKeys, $oldKeys);
629 $todrop = array_diff($oldKeys, $newKeys);
630 $same = array_intersect($newKeys, $oldKeys);
634 // Find which fields have actually changed definition
635 // in a way that we need to tweak them for this DB type.
636 foreach ($same as $name) {
637 if ($compareCallback) {
638 $same = call_user_func($compareCallback, $old[$name], $new[$name]);
640 $same = ($old[$name] == $new[$name]);
648 return array('add' => $toadd,
652 'count' => count($toadd) + count($todrop) + count($tomod));
656 * Append phrase(s) to an array of partial ALTER TABLE chunks in order
657 * to add the given column definition to the table.
659 * @param array $phrase
660 * @param string $columnName
663 function appendAlterAddColumn(array &$phrase, $columnName, array $cd)
665 $phrase[] = 'ADD COLUMN ' .
666 $this->quoteIdentifier($columnName) .
668 $this->columnSql($cd);
672 * Append phrase(s) to an array of partial ALTER TABLE chunks in order
673 * to alter the given column from its old state to a new one.
675 * @param array $phrase
676 * @param string $columnName
677 * @param array $old previous column definition as found in DB
678 * @param array $cd current column definition
680 function appendAlterModifyColumn(array &$phrase, $columnName, array $old, array $cd)
682 $phrase[] = 'MODIFY COLUMN ' .
683 $this->quoteIdentifier($columnName) .
685 $this->columnSql($cd);
689 * Append phrase(s) to an array of partial ALTER TABLE chunks in order
690 * to drop the given column definition from the table.
692 * @param array $phrase
693 * @param string $columnName
695 function appendAlterDropColumn(array &$phrase, $columnName)
697 $phrase[] = 'DROP COLUMN ' . $this->quoteIdentifier($columnName);
700 function appendAlterAddUnique(array &$phrase, $keyName, array $def)
704 $this->appendUniqueKeyDef($sql, $keyName, $def);
705 $phrase[] = implode(' ', $sql);
708 function appendAlterAddForeign(array &$phrase, $keyName, array $def)
712 $this->appendForeignKeyDef($sql, $keyName, $def);
713 $phrase[] = implode(' ', $sql);
716 function appendAlterDropUnique(array &$phrase, $keyName)
718 $phrase[] = 'DROP CONSTRAINT ' . $keyName;
721 function appendAlterDropForeign(array &$phrase, $keyName)
723 $phrase[] = 'DROP FOREIGN KEY ' . $keyName;
726 function appendAlterExtras(array &$phrase, $tableName, array $def)
732 * Quote a db/table/column identifier if necessary.
734 * @param string $name
737 function quoteIdentifier($name)
742 function quoteDefaultValue($cd)
744 if ($cd['type'] == 'datetime' && $cd['default'] == 'CURRENT_TIMESTAMP') {
745 return $cd['default'];
747 return $this->quoteValue($cd['default']);
751 function quoteValue($val)
753 return $this->conn->quoteSmart($val);
757 * Check if two column definitions are equivalent.
758 * The default implementation checks _everything_ but in many cases
759 * you may be able to discard a bunch of equivalencies.
765 function columnsEqual(array $a, array $b)
767 return !array_diff_assoc($a, $b) && !array_diff_assoc($b, $a);
771 * Returns the array of names from an array of
774 * @param array $cds array of ColumnDef objects
776 * @return array strings for name values
779 protected function _names($cds)
783 foreach ($cds as $cd) {
784 $names[] = $cd->name;
791 * Get a ColumnDef from an array matching
794 * @param array $cds Array of ColumnDef objects
795 * @param string $name Name of the column
797 * @return ColumnDef matching item or null if no match.
800 protected function _byName($cds, $name)
802 foreach ($cds as $cd) {
803 if ($cd->name == $name) {
812 * Return the proper SQL for creating or
815 * Appropriate for use in CREATE TABLE or
816 * ALTER TABLE statements.
818 * @param ColumnDef $cd column to create
820 * @return string correct SQL for that column
823 function columnSql(array $cd)
826 $line[] = $this->typeAndSize($cd);
828 if (isset($cd['default'])) {
830 $line[] = $this->quoteDefaultValue($cd);
831 } else if (!empty($cd['not null'])) {
832 // Can't have both not null AND default!
833 $line[] = 'not null';
836 return implode(' ', $line);
841 * @param string $column canonical type name in defs
842 * @return string native DB type name
844 function mapType($column)
849 function typeAndSize($column)
851 //$type = $this->mapType($column);
852 $type = $column['type'];
853 if (isset($column['size'])) {
854 $type = $column['size'] . $type;
858 if (isset($column['precision'])) {
859 $lengths[] = $column['precision'];
860 if (isset($column['scale'])) {
861 $lengths[] = $column['scale'];
863 } else if (isset($column['length'])) {
864 $lengths[] = $column['length'];
868 return $type . '(' . implode(',', $lengths) . ')';
875 * Convert an old-style set of ColumnDef objects into the current
876 * Drupal-style schema definition array, for backwards compatibility
877 * with plugins written for 0.9.x.
879 * @param string $tableName
880 * @param array $defs: array of ColumnDef objects
883 protected function oldToNew($tableName, array $defs)
892 foreach ($defs as $cd) {
894 $column['type'] = $cd->type;
895 foreach ($prefixes as $prefix) {
896 if (substr($cd->type, 0, strlen($prefix)) == $prefix) {
897 $column['type'] = substr($cd->type, strlen($prefix));
898 $column['size'] = $prefix;
904 if ($cd->type == 'varchar' || $cd->type == 'char') {
905 $column['length'] = $cd->size;
908 if (!$cd->nullable) {
909 $column['not null'] = true;
911 if ($cd->auto_increment) {
912 $column['type'] = 'serial';
915 $column['default'] = $cd->default;
917 $table['fields'][$cd->name] = $column;
919 if ($cd->key == 'PRI') {
920 // If multiple columns are defined as primary key,
921 // we'll pile them on in sequence.
922 if (!isset($table['primary key'])) {
923 $table['primary key'] = array();
925 $table['primary key'][] = $cd->name;
926 } else if ($cd->key == 'MUL') {
927 // Individual multiple-value indexes are only per-column
928 // using the old ColumnDef syntax.
929 $idx = "{$tableName}_{$cd->name}_idx";
930 $table['indexes'][$idx] = array($cd->name);
931 } else if ($cd->key == 'UNI') {
932 // Individual unique-value indexes are only per-column
933 // using the old ColumnDef syntax.
934 $idx = "{$tableName}_{$cd->name}_idx";
935 $table['unique keys'][$idx] = array($cd->name);
943 * Filter the given table definition array to match features available
946 * This lets us strip out unsupported things like comments, foreign keys,
947 * or type variants that we wouldn't get back from getTableDef().
949 * @param array $tableDef
951 function filterDef(array $tableDef)
957 * Validate a table definition array, checking for basic structure.
959 * If necessary, converts from an old-style array of ColumnDef objects.
961 * @param string $tableName
962 * @param array $def: table definition array
963 * @return array validated table definition array
965 * @throws Exception on wildly invalid input
967 function validateDef($tableName, array $def)
969 if (isset($def[0]) && $def[0] instanceof ColumnDef) {
970 $def = $this->oldToNew($tableName, $def);
973 // A few quick checks :D
974 if (!isset($def['fields'])) {
975 throw new Exception("Invalid table definition for $tableName: no fields.");
981 function isNumericType($type)
983 $type = strtolower($type);
984 $known = array('int', 'serial', 'numeric');
985 return in_array($type, $known);
989 * Pull info from the query into a fun-fun array of dooooom
992 * @return array of arrays
994 protected function fetchQueryData($sql)
996 $res = $this->conn->query($sql);
997 if (PEAR::isError($res)) {
998 throw new Exception($res->getMessage());
1003 while ($res->fetchInto($row, DB_FETCHMODE_ASSOC)) {
1013 class SchemaTableMissingException extends Exception