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 and unique 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 // Multi-value indexes are advisory and for best portability
165 // should be created as separate statements.
166 $statements = array();
167 $statements[] = $this->startCreateTable($name, $def) . "\n" .
168 implode($sql, ",\n") . "\n" .
169 $this->endCreateTable($name, $def);
170 if (!empty($def['indexes'])) {
171 foreach ($def['indexes'] as $col => $colDef) {
172 $this->appendCreateIndex($statements, $name, $col, $colDef);
180 * Set up a 'create table' SQL statement.
182 * @param string $name table name
183 * @param array $def table definition
186 function startCreateTable($name, array $def)
188 return 'CREATE TABLE ' . $this->quoteIdentifier($name) . ' (';
192 * Close out a 'create table' SQL statement.
194 * @param string $name table name
195 * @param array $def table definition
198 function endCreateTable($name, array $def)
204 * Append an SQL fragment with a column definition in a CREATE TABLE statement.
207 * @param string $name
210 function appendColumnDef(array &$sql, $name, array $def)
212 $sql[] = "$name " . $this->columnSql($def);
216 * Append an SQL fragment with a constraint definition for a primary
217 * key in a CREATE TABLE statement.
222 function appendPrimaryKeyDef(array &$sql, array $def)
224 $sql[] = "PRIMARY KEY " . $this->buildIndexList($def);
228 * Append an SQL fragment with a constraint definition for a primary
229 * key in a CREATE TABLE statement.
232 * @param string $name
235 function appendUniqueKeyDef(array &$sql, $name, array $def)
237 $sql[] = "UNIQUE $name " . $this->buildIndexList($def);
241 * Append an SQL statement with an index definition for an advisory
242 * index over one or more columns on a table.
244 * @param array $statements
245 * @param string $table
246 * @param string $name
249 function appendCreateIndex(array &$statements, $table, $name, array $def)
251 $statements[] = "CREATE INDEX $name ON $table " . $this->buildIndexList($def);
254 function buildIndexList(array $def)
257 return '(' . implode(',', array_map(array($this, 'buildIndexItem'), $def)) . ')';
260 function buildIndexItem($def)
262 if (is_array($def)) {
263 list($name, $size) = $def;
264 return $this->quoteIdentifier($name) . '(' . intval($size) . ')';
266 return $this->quoteIdentifier($def);
270 * Drops a table from the schema
272 * Throws an exception if the table is not found.
274 * @param string $name Name of the table to drop
276 * @return boolean success flag
279 public function dropTable($name)
281 $res = $this->conn->query("DROP TABLE $name");
283 if (PEAR::isError($res)) {
284 throw new Exception($res->getMessage());
291 * Adds an index to a table.
293 * If no name is provided, a name will be made up based
294 * on the table name and column names.
296 * Throws an exception on database error, esp. if the table
299 * @param string $table Name of the table
300 * @param array $columnNames Name of columns to index
301 * @param string $name (Optional) name of the index
303 * @return boolean success flag
306 public function createIndex($table, $columnNames, $name=null)
308 if (!is_array($columnNames)) {
309 $columnNames = array($columnNames);
313 $name = "{$table}_".implode("_", $columnNames)."_idx";
316 $res = $this->conn->query("ALTER TABLE $table ".
318 implode(",", $columnNames).")");
320 if (PEAR::isError($res)) {
321 throw new Exception($res->getMessage());
328 * Drops a named index from a table.
330 * @param string $table name of the table the index is on.
331 * @param string $name name of the index
333 * @return boolean success flag
336 public function dropIndex($table, $name)
338 $res = $this->conn->query("ALTER TABLE $table DROP INDEX $name");
340 if (PEAR::isError($res)) {
341 throw new Exception($res->getMessage());
348 * Adds a column to a table
350 * @param string $table name of the table
351 * @param ColumnDef $columndef Definition of the new
354 * @return boolean success flag
357 public function addColumn($table, $columndef)
359 $sql = "ALTER TABLE $table ADD COLUMN " . $this->_columnSql($columndef);
361 $res = $this->conn->query($sql);
363 if (PEAR::isError($res)) {
364 throw new Exception($res->getMessage());
371 * Modifies a column in the schema.
373 * The name must match an existing column and table.
375 * @param string $table name of the table
376 * @param ColumnDef $columndef new definition of the column.
378 * @return boolean success flag
381 public function modifyColumn($table, $columndef)
383 $sql = "ALTER TABLE $table MODIFY COLUMN " .
384 $this->_columnSql($columndef);
386 $res = $this->conn->query($sql);
388 if (PEAR::isError($res)) {
389 throw new Exception($res->getMessage());
396 * Drops a column from a table
398 * The name must match an existing column.
400 * @param string $table name of the table
401 * @param string $columnName name of the column to drop
403 * @return boolean success flag
406 public function dropColumn($table, $columnName)
408 $sql = "ALTER TABLE $table DROP COLUMN $columnName";
410 $res = $this->conn->query($sql);
412 if (PEAR::isError($res)) {
413 throw new Exception($res->getMessage());
420 * Ensures that a table exists with the given
421 * name and the given column definitions.
423 * If the table does not yet exist, it will
424 * create the table. If it does exist, it will
425 * alter the table to match the column definitions.
427 * @param string $tableName name of the table
428 * @param array $def Table definition array
430 * @return boolean success flag
433 public function ensureTable($tableName, $def)
435 $statements = $this->buildEnsureTable($tableName, $def);
436 return $this->runSqlSet($statements);
440 * Run a given set of SQL commands on the connection in sequence.
443 * @fixme if multiple statements, wrap in a transaction?
444 * @param array $statements
445 * @return boolean success flag
447 function runSqlSet(array $statements)
450 foreach ($statements as $sql) {
451 if (defined('DEBUG_INSTALLER')) {
452 echo "<tt>" . htmlspecialchars($sql) . "</tt><br/>\n";
454 $res = $this->conn->query($sql);
456 if (PEAR::isError($res)) {
457 throw new Exception($res->getMessage());
464 * Check a table's status, and if needed build a set
465 * of SQL statements which change it to be consistent
466 * with the given table definition.
468 * If the table does not yet exist, statements will
469 * be returned to create the table. If it does exist,
470 * statements will be returned to alter the table to
471 * match the column definitions.
473 * @param string $tableName name of the table
474 * @param array $columns array of ColumnDef
475 * objects for the table
477 * @return array of SQL statements
480 function buildEnsureTable($tableName, $def)
483 $old = $this->getTableDef($tableName);
484 } catch (SchemaTableMissingException $e) {
485 return $this->buildCreateTable($tableName, $def);
488 //$old = $this->filterDef($old);
489 $def = $this->filterDef($def);
491 // @fixme check if not present
492 $fields = $this->diffArrays($old, $def, 'fields', array($this, 'columnsEqual'));
493 $uniques = $this->diffArrays($old, $def, 'unique keys');
494 $indexes = $this->diffArrays($old, $def, 'indexes');
496 $total = $fields['count'] + $uniques['count'] + $indexes['count'];
502 // For efficiency, we want this all in one
503 // query, instead of using our methods.
507 foreach ($uniques['del'] + $uniques['mod'] as $keyName) {
508 $this->appendAlterDropUnique($phrase, $keyName);
511 foreach ($fields['add'] as $columnName) {
512 $this->appendAlterAddColumn($phrase, $columnName,
513 $def['fields'][$columnName]);
516 foreach ($fields['mod'] as $columnName) {
517 $this->appendAlterModifyColumn($phrase, $columnName,
518 $old['fields'][$columnName],
519 $def['fields'][$columnName]);
522 foreach ($fields['del'] as $columnName) {
523 $this->appendAlterDropColumn($phrase, $columnName);
526 foreach ($uniques['mod'] + $uniques['add'] as $keyName) {
527 $this->appendAlterAddUnique($phrase, $keyName, $def['unique keys'][$keyName]);
530 $sql = 'ALTER TABLE ' . $tableName . ' ' . implode(",\n", $phrase);
535 function diffArrays($oldDef, $newDef, $section, $compareCallback=null)
537 $old = isset($oldDef[$section]) ? $oldDef[$section] : array();
538 $new = isset($newDef[$section]) ? $newDef[$section] : array();
540 $oldKeys = array_keys($old);
541 $newKeys = array_keys($new);
543 $toadd = array_diff($newKeys, $oldKeys);
544 $todrop = array_diff($oldKeys, $newKeys);
545 $same = array_intersect($newKeys, $oldKeys);
549 // Find which fields have actually changed definition
550 // in a way that we need to tweak them for this DB type.
551 foreach ($same as $name) {
552 if ($compareCallback) {
553 $same = call_user_func($compareCallback, $old[$name], $new[$name]);
555 $same = ($old[$name] == $new[$name]);
563 return array('add' => $toadd,
567 'count' => count($toadd) + count($todrop) + count($tomod));
571 * Append phrase(s) to an array of partial ALTER TABLE chunks in order
572 * to add the given column definition to the table.
574 * @param array $phrase
575 * @param string $columnName
578 function appendAlterAddColumn(array &$phrase, $columnName, array $cd)
580 $phrase[] = 'ADD COLUMN ' .
581 $this->quoteIdentifier($columnName) .
583 $this->columnSql($cd);
587 * Append phrase(s) to an array of partial ALTER TABLE chunks in order
588 * to alter the given column from its old state to a new one.
590 * @param array $phrase
591 * @param string $columnName
592 * @param array $old previous column definition as found in DB
593 * @param array $cd current column definition
595 function appendAlterModifyColumn(array &$phrase, $columnName, array $old, array $cd)
597 $phrase[] = 'MODIFY COLUMN ' .
598 $this->quoteIdentifier($columnName) .
600 $this->columnSql($cd);
604 * Append phrase(s) to an array of partial ALTER TABLE chunks in order
605 * to drop the given column definition from the table.
607 * @param array $phrase
608 * @param string $columnName
610 function appendAlterDropColumn(array &$phrase, $columnName)
612 $phrase[] = 'DROP COLUMN ' . $this->quoteIdentifier($columnName);
615 function appendAlterAddUnique(array &$phrase, $keyName, array $def)
619 $this->appendUniqueKeyDef($sql, $keyName, $def);
620 $phrase[] = implode(' ', $sql);'ADD CONSTRAINT ' . $keyName;
623 function appendAlterDropUnique(array &$phrase, $keyName)
625 $phrase[] = 'DROP CONSTRAINT ' . $keyName;
629 * Quote a db/table/column identifier if necessary.
631 * @param string $name
634 function quoteIdentifier($name)
639 function quoteDefaultValue($cd)
641 if ($cd['type'] == 'datetime' && $cd['default'] == 'CURRENT_TIMESTAMP') {
642 return $cd['default'];
644 return $this->quoteValue($cd['default']);
648 function quoteValue($val)
650 if (is_int($val) || is_float($val) || is_double($val)) {
653 return '"' . $this->conn->escapeSimple($val) . '"';
658 * Check if two column definitions are equivalent.
659 * The default implementation checks _everything_ but in many cases
660 * you may be able to discard a bunch of equivalencies.
666 function columnsEqual(array $a, array $b)
668 return !array_diff_assoc($a, $b) && !array_diff_assoc($b, $a);
672 * Returns the array of names from an array of
675 * @param array $cds array of ColumnDef objects
677 * @return array strings for name values
680 protected function _names($cds)
684 foreach ($cds as $cd) {
685 $names[] = $cd->name;
692 * Get a ColumnDef from an array matching
695 * @param array $cds Array of ColumnDef objects
696 * @param string $name Name of the column
698 * @return ColumnDef matching item or null if no match.
701 protected function _byName($cds, $name)
703 foreach ($cds as $cd) {
704 if ($cd->name == $name) {
713 * Return the proper SQL for creating or
716 * Appropriate for use in CREATE TABLE or
717 * ALTER TABLE statements.
719 * @param ColumnDef $cd column to create
721 * @return string correct SQL for that column
724 function columnSql(array $cd)
727 $line[] = $this->typeAndSize($cd);
729 if (isset($cd['default'])) {
731 $line[] = $this->quoteDefaultValue($cd);
732 } else if (!empty($cd['not null'])) {
733 // Can't have both not null AND default!
734 $line[] = 'not null';
737 return implode(' ', $line);
742 * @param string $column canonical type name in defs
743 * @return string native DB type name
745 function mapType($column)
750 function typeAndSize($column)
752 //$type = $this->mapType($column);
753 $type = $column['type'];
754 if (isset($column['size'])) {
755 $type = $column['size'] . $type;
759 if (isset($column['precision'])) {
760 $lengths[] = $column['precision'];
761 if (isset($column['scale'])) {
762 $lengths[] = $column['scale'];
764 } else if (isset($column['length'])) {
765 $lengths[] = $column['length'];
769 return $type . '(' . implode(',', $lengths) . ')';
776 * Map a native type back to an independent type + size
778 * @param string $type
779 * @return array ($type, $size) -- $size may be null
781 protected function reverseMapType($type)
783 $sizes = array('tiny', 'small', 'medium', 'big');
784 foreach ($sizes as $prefix) {
785 if (substr($type, 0, strlen($prefix)) == $prefix) {
786 return array(substr($type, strlen($prefix)), $prefix);
789 return array($type, null);
793 * Convert an old-style set of ColumnDef objects into the current
794 * Drupal-style schema definition array, for backwards compatibility
795 * with plugins written for 0.9.x.
797 * @param string $tableName
801 function oldToNew($tableName, $defs)
810 foreach ($defs as $cd) {
811 $cd->addToTableDef($table);
813 $column['type'] = $cd->type;
814 foreach ($prefixes as $prefix) {
815 if (substr($cd->type, 0, strlen($prefix)) == $prefix) {
816 $column['type'] = substr($cd->type, strlen($prefix));
817 $column['size'] = $prefix;
823 if ($cd->type == 'varchar' || $cd->type == 'char') {
824 $column['length'] = $cd->size;
827 if (!$cd->nullable) {
828 $column['not null'] = true;
830 if ($cd->autoincrement) {
831 $column['type'] = 'serial';
834 $column['default'] = $cd->default;
836 $table['fields'][$cd->name] = $column;
838 if ($cd->key == 'PRI') {
839 // If multiple columns are defined as primary key,
840 // we'll pile them on in sequence.
841 if (!isset($table['primary key'])) {
842 $table['primary key'] = array();
844 $table['primary key'][] = $cd->name;
845 } else if ($cd->key == 'MUL') {
846 // Individual multiple-value indexes are only per-column
847 // using the old ColumnDef syntax.
848 $idx = "{$tableName}_{$cd->name}_idx";
849 $table['indexes'][$idx] = array($cd->name);
850 } else if ($cd->key == 'UNI') {
851 // Individual unique-value indexes are only per-column
852 // using the old ColumnDef syntax.
853 $idx = "{$tableName}_{$cd->name}_idx";
854 $table['unique keys'][$idx] = array($cd->name);
862 * Filter the given table definition array to match features available
865 * This lets us strip out unsupported things like comments, foreign keys,
866 * or type variants that we wouldn't get back from getTableDef().
868 * @param array $tableDef
870 function filterDef(array $tableDef)
875 function isNumericType($type)
877 $type = strtolower($type);
878 $known = array('int', 'serial', 'numeric');
879 return in_array($type, $known);
883 * Pull info from the query into a fun-fun array of dooooom
886 * @return array of arrays
888 protected function fetchQueryData($sql)
890 $res = $this->conn->query($sql);
891 if (PEAR::isError($res)) {
892 throw new Exception($res->getMessage());
897 while ($res->fetchInto($row, DB_FETCHMODE_ASSOC)) {
907 class SchemaTableMissingException extends Exception