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 // Multi-value indexes are advisory and for best portability
172 // should be created as separate statements.
173 $statements = array();
174 $statements[] = $this->startCreateTable($name, $def) . "\n" .
175 implode($sql, ",\n") . "\n" .
176 $this->endCreateTable($name, $def);
177 if (!empty($def['indexes'])) {
178 foreach ($def['indexes'] as $col => $colDef) {
179 $this->appendCreateIndex($statements, $name, $col, $colDef);
187 * Set up a 'create table' SQL statement.
189 * @param string $name table name
190 * @param array $def table definition
193 function startCreateTable($name, array $def)
195 return 'CREATE TABLE ' . $this->quoteIdentifier($name) . ' (';
199 * Close out a 'create table' SQL statement.
201 * @param string $name table name
202 * @param array $def table definition
205 function endCreateTable($name, array $def)
211 * Append an SQL fragment with a column definition in a CREATE TABLE statement.
214 * @param string $name
217 function appendColumnDef(array &$sql, $name, array $def)
219 $sql[] = "$name " . $this->columnSql($def);
223 * Append an SQL fragment with a constraint definition for a primary
224 * key in a CREATE TABLE statement.
229 function appendPrimaryKeyDef(array &$sql, array $def)
231 $sql[] = "PRIMARY KEY " . $this->buildIndexList($def);
235 * Append an SQL fragment with a constraint definition for a unique
236 * key in a CREATE TABLE statement.
239 * @param string $name
242 function appendUniqueKeyDef(array &$sql, $name, array $def)
244 $sql[] = "CONSTRAINT $name UNIQUE " . $this->buildIndexList($def);
248 * Append an SQL fragment with a constraint definition for a foreign
249 * key in a CREATE TABLE statement.
252 * @param string $name
255 function appendForeignKeyDef(array &$sql, $name, array $def)
257 list($refTable, $map) = $def;
258 $srcCols = array_keys($map);
259 $refCols = array_values($map);
260 $sql[] = "CONSTRAINT $name FOREIGN KEY " .
261 $this->buildIndexList($srcCols) .
263 $this->quoteIdentifier($refTable) .
265 $this->buildIndexList($refCols);
269 * Append an SQL statement with an index definition for an advisory
270 * index over one or more columns on a table.
272 * @param array $statements
273 * @param string $table
274 * @param string $name
277 function appendCreateIndex(array &$statements, $table, $name, array $def)
279 $statements[] = "CREATE INDEX $name ON $table " . $this->buildIndexList($def);
283 * Append an SQL statement to drop an index from a table.
285 * @param array $statements
286 * @param string $table
287 * @param string $name
290 function appendDropIndex(array &$statements, $table, $name)
292 $statements[] = "DROP INDEX $name ON " . $this->quoteIdentifier($table);
295 function buildIndexList(array $def)
298 return '(' . implode(',', array_map(array($this, 'buildIndexItem'), $def)) . ')';
301 function buildIndexItem($def)
303 if (is_array($def)) {
304 list($name, $size) = $def;
305 return $this->quoteIdentifier($name) . '(' . intval($size) . ')';
307 return $this->quoteIdentifier($def);
311 * Drops a table from the schema
313 * Throws an exception if the table is not found.
315 * @param string $name Name of the table to drop
317 * @return boolean success flag
320 public function dropTable($name)
322 $res = $this->conn->query("DROP TABLE $name");
324 if (PEAR::isError($res)) {
325 throw new Exception($res->getMessage());
332 * Adds an index to a table.
334 * If no name is provided, a name will be made up based
335 * on the table name and column names.
337 * Throws an exception on database error, esp. if the table
340 * @param string $table Name of the table
341 * @param array $columnNames Name of columns to index
342 * @param string $name (Optional) name of the index
344 * @return boolean success flag
347 public function createIndex($table, $columnNames, $name=null)
349 if (!is_array($columnNames)) {
350 $columnNames = array($columnNames);
354 $name = "{$table}_".implode("_", $columnNames)."_idx";
357 $res = $this->conn->query("ALTER TABLE $table ".
359 implode(",", $columnNames).")");
361 if (PEAR::isError($res)) {
362 throw new Exception($res->getMessage());
369 * Drops a named index from a table.
371 * @param string $table name of the table the index is on.
372 * @param string $name name of the index
374 * @return boolean success flag
377 public function dropIndex($table, $name)
379 $res = $this->conn->query("ALTER TABLE $table DROP INDEX $name");
381 if (PEAR::isError($res)) {
382 throw new Exception($res->getMessage());
389 * Adds a column to a table
391 * @param string $table name of the table
392 * @param ColumnDef $columndef Definition of the new
395 * @return boolean success flag
398 public function addColumn($table, $columndef)
400 $sql = "ALTER TABLE $table ADD COLUMN " . $this->_columnSql($columndef);
402 $res = $this->conn->query($sql);
404 if (PEAR::isError($res)) {
405 throw new Exception($res->getMessage());
412 * Modifies a column in the schema.
414 * The name must match an existing column and table.
416 * @param string $table name of the table
417 * @param ColumnDef $columndef new definition of the column.
419 * @return boolean success flag
422 public function modifyColumn($table, $columndef)
424 $sql = "ALTER TABLE $table MODIFY COLUMN " .
425 $this->_columnSql($columndef);
427 $res = $this->conn->query($sql);
429 if (PEAR::isError($res)) {
430 throw new Exception($res->getMessage());
437 * Drops a column from a table
439 * The name must match an existing column.
441 * @param string $table name of the table
442 * @param string $columnName name of the column to drop
444 * @return boolean success flag
447 public function dropColumn($table, $columnName)
449 $sql = "ALTER TABLE $table DROP COLUMN $columnName";
451 $res = $this->conn->query($sql);
453 if (PEAR::isError($res)) {
454 throw new Exception($res->getMessage());
461 * Ensures that a table exists with the given
462 * name and the given column definitions.
464 * If the table does not yet exist, it will
465 * create the table. If it does exist, it will
466 * alter the table to match the column definitions.
468 * @param string $tableName name of the table
469 * @param array $def Table definition array
471 * @return boolean success flag
474 public function ensureTable($tableName, $def)
476 $statements = $this->buildEnsureTable($tableName, $def);
477 return $this->runSqlSet($statements);
481 * Run a given set of SQL commands on the connection in sequence.
484 * @fixme if multiple statements, wrap in a transaction?
485 * @param array $statements
486 * @return boolean success flag
488 function runSqlSet(array $statements)
491 foreach ($statements as $sql) {
492 if (defined('DEBUG_INSTALLER')) {
493 echo "<tt>" . htmlspecialchars($sql) . "</tt><br/>\n";
495 $res = $this->conn->query($sql);
497 if (PEAR::isError($res)) {
498 throw new Exception($res->getMessage());
505 * Check a table's status, and if needed build a set
506 * of SQL statements which change it to be consistent
507 * with the given table definition.
509 * If the table does not yet exist, statements will
510 * be returned to create the table. If it does exist,
511 * statements will be returned to alter the table to
512 * match the column definitions.
514 * @param string $tableName name of the table
515 * @param array $columns array of ColumnDef
516 * objects for the table
518 * @return array of SQL statements
521 function buildEnsureTable($tableName, array $def)
524 $old = $this->getTableDef($tableName);
525 } catch (SchemaTableMissingException $e) {
526 return $this->buildCreateTable($tableName, $def);
529 // Filter the DB-independent table definition to match the current
530 // database engine's features and limitations.
531 $def = $this->validateDef($tableName, $def);
532 $def = $this->filterDef($def);
534 $statements = array();
535 $fields = $this->diffArrays($old, $def, 'fields', array($this, 'columnsEqual'));
536 $uniques = $this->diffArrays($old, $def, 'unique keys');
537 $indexes = $this->diffArrays($old, $def, 'indexes');
538 $foreign = $this->diffArrays($old, $def, 'foreign keys');
540 // Drop any obsolete or modified indexes ahead...
541 foreach ($indexes['del'] + $indexes['mod'] as $indexName) {
542 $this->appendDropIndex($statements, $tableName, $indexName);
545 // For efficiency, we want this all in one
546 // query, instead of using our methods.
550 foreach ($foreign['del'] + $foreign['mod'] as $keyName) {
551 $this->appendAlterDropForeign($phrase, $keyName);
554 foreach ($uniques['del'] + $uniques['mod'] as $keyName) {
555 $this->appendAlterDropUnique($phrase, $keyName);
558 foreach ($fields['add'] as $columnName) {
559 $this->appendAlterAddColumn($phrase, $columnName,
560 $def['fields'][$columnName]);
563 foreach ($fields['mod'] as $columnName) {
564 $this->appendAlterModifyColumn($phrase, $columnName,
565 $old['fields'][$columnName],
566 $def['fields'][$columnName]);
569 foreach ($fields['del'] as $columnName) {
570 $this->appendAlterDropColumn($phrase, $columnName);
573 foreach ($uniques['mod'] + $uniques['add'] as $keyName) {
574 $this->appendAlterAddUnique($phrase, $keyName, $def['unique keys'][$keyName]);
577 foreach ($foreign['mod'] + $foreign['add'] as $keyName) {
578 $this->appendAlterAddForeign($phrase, $keyName, $def['foreign keys'][$keyName]);
581 $this->appendAlterExtras($phrase, $tableName);
583 if (count($phrase) > 0) {
584 $sql = 'ALTER TABLE ' . $tableName . ' ' . implode(",\n", $phrase);
585 $statements[] = $sql;
588 // Now create any indexes...
589 foreach ($indexes['mod'] + $indexes['add'] as $indexName) {
590 $this->appendCreateIndex($statements, $tableName, $indexName, $def['indexes'][$indexName]);
596 function diffArrays($oldDef, $newDef, $section, $compareCallback=null)
598 $old = isset($oldDef[$section]) ? $oldDef[$section] : array();
599 $new = isset($newDef[$section]) ? $newDef[$section] : array();
601 $oldKeys = array_keys($old);
602 $newKeys = array_keys($new);
604 $toadd = array_diff($newKeys, $oldKeys);
605 $todrop = array_diff($oldKeys, $newKeys);
606 $same = array_intersect($newKeys, $oldKeys);
610 // Find which fields have actually changed definition
611 // in a way that we need to tweak them for this DB type.
612 foreach ($same as $name) {
613 if ($compareCallback) {
614 $same = call_user_func($compareCallback, $old[$name], $new[$name]);
616 $same = ($old[$name] == $new[$name]);
624 return array('add' => $toadd,
628 'count' => count($toadd) + count($todrop) + count($tomod));
632 * Append phrase(s) to an array of partial ALTER TABLE chunks in order
633 * to add the given column definition to the table.
635 * @param array $phrase
636 * @param string $columnName
639 function appendAlterAddColumn(array &$phrase, $columnName, array $cd)
641 $phrase[] = 'ADD COLUMN ' .
642 $this->quoteIdentifier($columnName) .
644 $this->columnSql($cd);
648 * Append phrase(s) to an array of partial ALTER TABLE chunks in order
649 * to alter the given column from its old state to a new one.
651 * @param array $phrase
652 * @param string $columnName
653 * @param array $old previous column definition as found in DB
654 * @param array $cd current column definition
656 function appendAlterModifyColumn(array &$phrase, $columnName, array $old, array $cd)
658 $phrase[] = 'MODIFY COLUMN ' .
659 $this->quoteIdentifier($columnName) .
661 $this->columnSql($cd);
665 * Append phrase(s) to an array of partial ALTER TABLE chunks in order
666 * to drop the given column definition from the table.
668 * @param array $phrase
669 * @param string $columnName
671 function appendAlterDropColumn(array &$phrase, $columnName)
673 $phrase[] = 'DROP COLUMN ' . $this->quoteIdentifier($columnName);
676 function appendAlterAddUnique(array &$phrase, $keyName, array $def)
680 $this->appendUniqueKeyDef($sql, $keyName, $def);
681 $phrase[] = implode(' ', $sql);
684 function appendAlterAddForeign(array &$phrase, $keyName, array $def)
688 $this->appendForeignKeyDef($sql, $keyName, $def);
689 $phrase[] = implode(' ', $sql);
692 function appendAlterDropUnique(array &$phrase, $keyName)
694 $phrase[] = 'DROP CONSTRAINT ' . $keyName;
697 function appendAlterDropForeign(array &$phrase, $keyName)
699 $phrase[] = 'DROP FOREIGN KEY ' . $keyName;
702 function appendAlterExtras(array &$phrase, $tableName)
708 * Quote a db/table/column identifier if necessary.
710 * @param string $name
713 function quoteIdentifier($name)
718 function quoteDefaultValue($cd)
720 if ($cd['type'] == 'datetime' && $cd['default'] == 'CURRENT_TIMESTAMP') {
721 return $cd['default'];
723 return $this->quoteValue($cd['default']);
727 function quoteValue($val)
729 return $this->conn->quoteSmart($val);
733 * Check if two column definitions are equivalent.
734 * The default implementation checks _everything_ but in many cases
735 * you may be able to discard a bunch of equivalencies.
741 function columnsEqual(array $a, array $b)
743 return !array_diff_assoc($a, $b) && !array_diff_assoc($b, $a);
747 * Returns the array of names from an array of
750 * @param array $cds array of ColumnDef objects
752 * @return array strings for name values
755 protected function _names($cds)
759 foreach ($cds as $cd) {
760 $names[] = $cd->name;
767 * Get a ColumnDef from an array matching
770 * @param array $cds Array of ColumnDef objects
771 * @param string $name Name of the column
773 * @return ColumnDef matching item or null if no match.
776 protected function _byName($cds, $name)
778 foreach ($cds as $cd) {
779 if ($cd->name == $name) {
788 * Return the proper SQL for creating or
791 * Appropriate for use in CREATE TABLE or
792 * ALTER TABLE statements.
794 * @param ColumnDef $cd column to create
796 * @return string correct SQL for that column
799 function columnSql(array $cd)
802 $line[] = $this->typeAndSize($cd);
804 if (isset($cd['default'])) {
806 $line[] = $this->quoteDefaultValue($cd);
807 } else if (!empty($cd['not null'])) {
808 // Can't have both not null AND default!
809 $line[] = 'not null';
812 return implode(' ', $line);
817 * @param string $column canonical type name in defs
818 * @return string native DB type name
820 function mapType($column)
825 function typeAndSize($column)
827 //$type = $this->mapType($column);
828 $type = $column['type'];
829 if (isset($column['size'])) {
830 $type = $column['size'] . $type;
834 if (isset($column['precision'])) {
835 $lengths[] = $column['precision'];
836 if (isset($column['scale'])) {
837 $lengths[] = $column['scale'];
839 } else if (isset($column['length'])) {
840 $lengths[] = $column['length'];
844 return $type . '(' . implode(',', $lengths) . ')';
851 * Convert an old-style set of ColumnDef objects into the current
852 * Drupal-style schema definition array, for backwards compatibility
853 * with plugins written for 0.9.x.
855 * @param string $tableName
856 * @param array $defs: array of ColumnDef objects
859 protected function oldToNew($tableName, array $defs)
868 foreach ($defs as $cd) {
870 $column['type'] = $cd->type;
871 foreach ($prefixes as $prefix) {
872 if (substr($cd->type, 0, strlen($prefix)) == $prefix) {
873 $column['type'] = substr($cd->type, strlen($prefix));
874 $column['size'] = $prefix;
880 if ($cd->type == 'varchar' || $cd->type == 'char') {
881 $column['length'] = $cd->size;
884 if (!$cd->nullable) {
885 $column['not null'] = true;
887 if ($cd->autoincrement) {
888 $column['type'] = 'serial';
891 $column['default'] = $cd->default;
893 $table['fields'][$cd->name] = $column;
895 if ($cd->key == 'PRI') {
896 // If multiple columns are defined as primary key,
897 // we'll pile them on in sequence.
898 if (!isset($table['primary key'])) {
899 $table['primary key'] = array();
901 $table['primary key'][] = $cd->name;
902 } else if ($cd->key == 'MUL') {
903 // Individual multiple-value indexes are only per-column
904 // using the old ColumnDef syntax.
905 $idx = "{$tableName}_{$cd->name}_idx";
906 $table['indexes'][$idx] = array($cd->name);
907 } else if ($cd->key == 'UNI') {
908 // Individual unique-value indexes are only per-column
909 // using the old ColumnDef syntax.
910 $idx = "{$tableName}_{$cd->name}_idx";
911 $table['unique keys'][$idx] = array($cd->name);
919 * Filter the given table definition array to match features available
922 * This lets us strip out unsupported things like comments, foreign keys,
923 * or type variants that we wouldn't get back from getTableDef().
925 * @param array $tableDef
927 function filterDef(array $tableDef)
933 * Validate a table definition array, checking for basic structure.
935 * If necessary, converts from an old-style array of ColumnDef objects.
937 * @param string $tableName
938 * @param array $def: table definition array
939 * @return array validated table definition array
941 * @throws Exception on wildly invalid input
943 function validateDef($tableName, array $def)
945 if (count($defs) && $defs[0] instanceof ColumnDef) {
946 $def = $this->oldToNew($tableName, $defs);
949 // A few quick checks :D
950 if (!isset($def['fields'])) {
951 throw new Exceptioni("Invalid table definition for $tableName: no fields.");
957 function isNumericType($type)
959 $type = strtolower($type);
960 $known = array('int', 'serial', 'numeric');
961 return in_array($type, $known);
965 * Pull info from the query into a fun-fun array of dooooom
968 * @return array of arrays
970 protected function fetchQueryData($sql)
972 $res = $this->conn->query($sql);
973 if (PEAR::isError($res)) {
974 throw new Exception($res->getMessage());
979 while ($res->fetchInto($row, DB_FETCHMODE_ASSOC)) {
989 class SchemaTableMissingException extends Exception