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 if (count($def) != 2) {
258 throw new Exception("Invalid foreign key def for $name: " . var_export($def, true));
260 list($refTable, $map) = $def;
261 $srcCols = array_keys($map);
262 $refCols = array_values($map);
263 $sql[] = "CONSTRAINT $name FOREIGN KEY " .
264 $this->buildIndexList($srcCols) .
266 $this->quoteIdentifier($refTable) .
268 $this->buildIndexList($refCols);
272 * Append an SQL statement with an index definition for an advisory
273 * index over one or more columns on a table.
275 * @param array $statements
276 * @param string $table
277 * @param string $name
280 function appendCreateIndex(array &$statements, $table, $name, array $def)
282 $statements[] = "CREATE INDEX $name ON $table " . $this->buildIndexList($def);
286 * Append an SQL statement to drop an index from a table.
288 * @param array $statements
289 * @param string $table
290 * @param string $name
293 function appendDropIndex(array &$statements, $table, $name)
295 $statements[] = "DROP INDEX $name ON " . $this->quoteIdentifier($table);
298 function buildIndexList(array $def)
301 return '(' . implode(',', array_map(array($this, 'buildIndexItem'), $def)) . ')';
304 function buildIndexItem($def)
306 if (is_array($def)) {
307 list($name, $size) = $def;
308 return $this->quoteIdentifier($name) . '(' . intval($size) . ')';
310 return $this->quoteIdentifier($def);
314 * Drops a table from the schema
316 * Throws an exception if the table is not found.
318 * @param string $name Name of the table to drop
320 * @return boolean success flag
323 public function dropTable($name)
325 $res = $this->conn->query("DROP TABLE $name");
327 if (PEAR::isError($res)) {
328 throw new Exception($res->getMessage());
335 * Adds an index to a table.
337 * If no name is provided, a name will be made up based
338 * on the table name and column names.
340 * Throws an exception on database error, esp. if the table
343 * @param string $table Name of the table
344 * @param array $columnNames Name of columns to index
345 * @param string $name (Optional) name of the index
347 * @return boolean success flag
350 public function createIndex($table, $columnNames, $name=null)
352 if (!is_array($columnNames)) {
353 $columnNames = array($columnNames);
357 $name = "{$table}_".implode("_", $columnNames)."_idx";
360 $res = $this->conn->query("ALTER TABLE $table ".
362 implode(",", $columnNames).")");
364 if (PEAR::isError($res)) {
365 throw new Exception($res->getMessage());
372 * Drops a named index from a table.
374 * @param string $table name of the table the index is on.
375 * @param string $name name of the index
377 * @return boolean success flag
380 public function dropIndex($table, $name)
382 $res = $this->conn->query("ALTER TABLE $table DROP INDEX $name");
384 if (PEAR::isError($res)) {
385 throw new Exception($res->getMessage());
392 * Adds a column to a table
394 * @param string $table name of the table
395 * @param ColumnDef $columndef Definition of the new
398 * @return boolean success flag
401 public function addColumn($table, $columndef)
403 $sql = "ALTER TABLE $table ADD COLUMN " . $this->_columnSql($columndef);
405 $res = $this->conn->query($sql);
407 if (PEAR::isError($res)) {
408 throw new Exception($res->getMessage());
415 * Modifies a column in the schema.
417 * The name must match an existing column and table.
419 * @param string $table name of the table
420 * @param ColumnDef $columndef new definition of the column.
422 * @return boolean success flag
425 public function modifyColumn($table, $columndef)
427 $sql = "ALTER TABLE $table MODIFY COLUMN " .
428 $this->_columnSql($columndef);
430 $res = $this->conn->query($sql);
432 if (PEAR::isError($res)) {
433 throw new Exception($res->getMessage());
440 * Drops a column from a table
442 * The name must match an existing column.
444 * @param string $table name of the table
445 * @param string $columnName name of the column to drop
447 * @return boolean success flag
450 public function dropColumn($table, $columnName)
452 $sql = "ALTER TABLE $table DROP COLUMN $columnName";
454 $res = $this->conn->query($sql);
456 if (PEAR::isError($res)) {
457 throw new Exception($res->getMessage());
464 * Ensures that a table exists with the given
465 * name and the given column definitions.
467 * If the table does not yet exist, it will
468 * create the table. If it does exist, it will
469 * alter the table to match the column definitions.
471 * @param string $tableName name of the table
472 * @param array $def Table definition array
474 * @return boolean success flag
477 public function ensureTable($tableName, $def)
479 $statements = $this->buildEnsureTable($tableName, $def);
480 return $this->runSqlSet($statements);
484 * Run a given set of SQL commands on the connection in sequence.
487 * @fixme if multiple statements, wrap in a transaction?
488 * @param array $statements
489 * @return boolean success flag
491 function runSqlSet(array $statements)
494 foreach ($statements as $sql) {
495 if (defined('DEBUG_INSTALLER')) {
496 echo "<tt>" . htmlspecialchars($sql) . "</tt><br/>\n";
498 $res = $this->conn->query($sql);
500 if (PEAR::isError($res)) {
501 throw new Exception($res->getMessage());
508 * Check a table's status, and if needed build a set
509 * of SQL statements which change it to be consistent
510 * with the given table definition.
512 * If the table does not yet exist, statements will
513 * be returned to create the table. If it does exist,
514 * statements will be returned to alter the table to
515 * match the column definitions.
517 * @param string $tableName name of the table
518 * @param array $columns array of ColumnDef
519 * objects for the table
521 * @return array of SQL statements
524 function buildEnsureTable($tableName, array $def)
527 $old = $this->getTableDef($tableName);
528 } catch (SchemaTableMissingException $e) {
529 return $this->buildCreateTable($tableName, $def);
532 // Filter the DB-independent table definition to match the current
533 // database engine's features and limitations.
534 $def = $this->validateDef($tableName, $def);
535 $def = $this->filterDef($def);
537 $statements = array();
538 $fields = $this->diffArrays($old, $def, 'fields', array($this, 'columnsEqual'));
539 $uniques = $this->diffArrays($old, $def, 'unique keys');
540 $indexes = $this->diffArrays($old, $def, 'indexes');
541 $foreign = $this->diffArrays($old, $def, 'foreign keys');
543 // Drop any obsolete or modified indexes ahead...
544 foreach ($indexes['del'] + $indexes['mod'] as $indexName) {
545 $this->appendDropIndex($statements, $tableName, $indexName);
548 // For efficiency, we want this all in one
549 // query, instead of using our methods.
553 foreach ($foreign['del'] + $foreign['mod'] as $keyName) {
554 $this->appendAlterDropForeign($phrase, $keyName);
557 foreach ($uniques['del'] + $uniques['mod'] as $keyName) {
558 $this->appendAlterDropUnique($phrase, $keyName);
561 foreach ($fields['add'] as $columnName) {
562 $this->appendAlterAddColumn($phrase, $columnName,
563 $def['fields'][$columnName]);
566 foreach ($fields['mod'] as $columnName) {
567 $this->appendAlterModifyColumn($phrase, $columnName,
568 $old['fields'][$columnName],
569 $def['fields'][$columnName]);
572 foreach ($fields['del'] as $columnName) {
573 $this->appendAlterDropColumn($phrase, $columnName);
576 foreach ($uniques['mod'] + $uniques['add'] as $keyName) {
577 $this->appendAlterAddUnique($phrase, $keyName, $def['unique keys'][$keyName]);
580 foreach ($foreign['mod'] + $foreign['add'] as $keyName) {
581 $this->appendAlterAddForeign($phrase, $keyName, $def['foreign keys'][$keyName]);
584 $this->appendAlterExtras($phrase, $tableName);
586 if (count($phrase) > 0) {
587 $sql = 'ALTER TABLE ' . $tableName . ' ' . implode(",\n", $phrase);
588 $statements[] = $sql;
591 // Now create any indexes...
592 foreach ($indexes['mod'] + $indexes['add'] as $indexName) {
593 $this->appendCreateIndex($statements, $tableName, $indexName, $def['indexes'][$indexName]);
599 function diffArrays($oldDef, $newDef, $section, $compareCallback=null)
601 $old = isset($oldDef[$section]) ? $oldDef[$section] : array();
602 $new = isset($newDef[$section]) ? $newDef[$section] : array();
604 $oldKeys = array_keys($old);
605 $newKeys = array_keys($new);
607 $toadd = array_diff($newKeys, $oldKeys);
608 $todrop = array_diff($oldKeys, $newKeys);
609 $same = array_intersect($newKeys, $oldKeys);
613 // Find which fields have actually changed definition
614 // in a way that we need to tweak them for this DB type.
615 foreach ($same as $name) {
616 if ($compareCallback) {
617 $same = call_user_func($compareCallback, $old[$name], $new[$name]);
619 $same = ($old[$name] == $new[$name]);
627 return array('add' => $toadd,
631 'count' => count($toadd) + count($todrop) + count($tomod));
635 * Append phrase(s) to an array of partial ALTER TABLE chunks in order
636 * to add the given column definition to the table.
638 * @param array $phrase
639 * @param string $columnName
642 function appendAlterAddColumn(array &$phrase, $columnName, array $cd)
644 $phrase[] = 'ADD COLUMN ' .
645 $this->quoteIdentifier($columnName) .
647 $this->columnSql($cd);
651 * Append phrase(s) to an array of partial ALTER TABLE chunks in order
652 * to alter the given column from its old state to a new one.
654 * @param array $phrase
655 * @param string $columnName
656 * @param array $old previous column definition as found in DB
657 * @param array $cd current column definition
659 function appendAlterModifyColumn(array &$phrase, $columnName, array $old, array $cd)
661 $phrase[] = 'MODIFY COLUMN ' .
662 $this->quoteIdentifier($columnName) .
664 $this->columnSql($cd);
668 * Append phrase(s) to an array of partial ALTER TABLE chunks in order
669 * to drop the given column definition from the table.
671 * @param array $phrase
672 * @param string $columnName
674 function appendAlterDropColumn(array &$phrase, $columnName)
676 $phrase[] = 'DROP COLUMN ' . $this->quoteIdentifier($columnName);
679 function appendAlterAddUnique(array &$phrase, $keyName, array $def)
683 $this->appendUniqueKeyDef($sql, $keyName, $def);
684 $phrase[] = implode(' ', $sql);
687 function appendAlterAddForeign(array &$phrase, $keyName, array $def)
691 $this->appendForeignKeyDef($sql, $keyName, $def);
692 $phrase[] = implode(' ', $sql);
695 function appendAlterDropUnique(array &$phrase, $keyName)
697 $phrase[] = 'DROP CONSTRAINT ' . $keyName;
700 function appendAlterDropForeign(array &$phrase, $keyName)
702 $phrase[] = 'DROP FOREIGN KEY ' . $keyName;
705 function appendAlterExtras(array &$phrase, $tableName)
711 * Quote a db/table/column identifier if necessary.
713 * @param string $name
716 function quoteIdentifier($name)
721 function quoteDefaultValue($cd)
723 if ($cd['type'] == 'datetime' && $cd['default'] == 'CURRENT_TIMESTAMP') {
724 return $cd['default'];
726 return $this->quoteValue($cd['default']);
730 function quoteValue($val)
732 return $this->conn->quoteSmart($val);
736 * Check if two column definitions are equivalent.
737 * The default implementation checks _everything_ but in many cases
738 * you may be able to discard a bunch of equivalencies.
744 function columnsEqual(array $a, array $b)
746 return !array_diff_assoc($a, $b) && !array_diff_assoc($b, $a);
750 * Returns the array of names from an array of
753 * @param array $cds array of ColumnDef objects
755 * @return array strings for name values
758 protected function _names($cds)
762 foreach ($cds as $cd) {
763 $names[] = $cd->name;
770 * Get a ColumnDef from an array matching
773 * @param array $cds Array of ColumnDef objects
774 * @param string $name Name of the column
776 * @return ColumnDef matching item or null if no match.
779 protected function _byName($cds, $name)
781 foreach ($cds as $cd) {
782 if ($cd->name == $name) {
791 * Return the proper SQL for creating or
794 * Appropriate for use in CREATE TABLE or
795 * ALTER TABLE statements.
797 * @param ColumnDef $cd column to create
799 * @return string correct SQL for that column
802 function columnSql(array $cd)
805 $line[] = $this->typeAndSize($cd);
807 if (isset($cd['default'])) {
809 $line[] = $this->quoteDefaultValue($cd);
810 } else if (!empty($cd['not null'])) {
811 // Can't have both not null AND default!
812 $line[] = 'not null';
815 return implode(' ', $line);
820 * @param string $column canonical type name in defs
821 * @return string native DB type name
823 function mapType($column)
828 function typeAndSize($column)
830 //$type = $this->mapType($column);
831 $type = $column['type'];
832 if (isset($column['size'])) {
833 $type = $column['size'] . $type;
837 if (isset($column['precision'])) {
838 $lengths[] = $column['precision'];
839 if (isset($column['scale'])) {
840 $lengths[] = $column['scale'];
842 } else if (isset($column['length'])) {
843 $lengths[] = $column['length'];
847 return $type . '(' . implode(',', $lengths) . ')';
854 * Convert an old-style set of ColumnDef objects into the current
855 * Drupal-style schema definition array, for backwards compatibility
856 * with plugins written for 0.9.x.
858 * @param string $tableName
859 * @param array $defs: array of ColumnDef objects
862 protected function oldToNew($tableName, array $defs)
871 foreach ($defs as $cd) {
873 $column['type'] = $cd->type;
874 foreach ($prefixes as $prefix) {
875 if (substr($cd->type, 0, strlen($prefix)) == $prefix) {
876 $column['type'] = substr($cd->type, strlen($prefix));
877 $column['size'] = $prefix;
883 if ($cd->type == 'varchar' || $cd->type == 'char') {
884 $column['length'] = $cd->size;
887 if (!$cd->nullable) {
888 $column['not null'] = true;
890 if ($cd->auto_increment) {
891 $column['type'] = 'serial';
894 $column['default'] = $cd->default;
896 $table['fields'][$cd->name] = $column;
898 if ($cd->key == 'PRI') {
899 // If multiple columns are defined as primary key,
900 // we'll pile them on in sequence.
901 if (!isset($table['primary key'])) {
902 $table['primary key'] = array();
904 $table['primary key'][] = $cd->name;
905 } else if ($cd->key == 'MUL') {
906 // Individual multiple-value indexes are only per-column
907 // using the old ColumnDef syntax.
908 $idx = "{$tableName}_{$cd->name}_idx";
909 $table['indexes'][$idx] = array($cd->name);
910 } else if ($cd->key == 'UNI') {
911 // Individual unique-value indexes are only per-column
912 // using the old ColumnDef syntax.
913 $idx = "{$tableName}_{$cd->name}_idx";
914 $table['unique keys'][$idx] = array($cd->name);
922 * Filter the given table definition array to match features available
925 * This lets us strip out unsupported things like comments, foreign keys,
926 * or type variants that we wouldn't get back from getTableDef().
928 * @param array $tableDef
930 function filterDef(array $tableDef)
936 * Validate a table definition array, checking for basic structure.
938 * If necessary, converts from an old-style array of ColumnDef objects.
940 * @param string $tableName
941 * @param array $def: table definition array
942 * @return array validated table definition array
944 * @throws Exception on wildly invalid input
946 function validateDef($tableName, array $def)
948 if (isset($def[0]) && $def[0] instanceof ColumnDef) {
949 $def = $this->oldToNew($tableName, $def);
952 // A few quick checks :D
953 if (!isset($def['fields'])) {
954 throw new Exception("Invalid table definition for $tableName: no fields.");
960 function isNumericType($type)
962 $type = strtolower($type);
963 $known = array('int', 'serial', 'numeric');
964 return in_array($type, $known);
968 * Pull info from the query into a fun-fun array of dooooom
971 * @return array of arrays
973 protected function fetchQueryData($sql)
975 $res = $this->conn->query($sql);
976 if (PEAR::isError($res)) {
977 throw new Exception($res->getMessage());
982 while ($res->fetchInto($row, DB_FETCHMODE_ASSOC)) {
992 class SchemaTableMissingException extends Exception