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 $name Name of the table
123 * @param array $columns Array of ColumnDef objects
126 * @return boolean success flag
129 public function createTable($name, $columns)
135 $sql = "CREATE TABLE $name (\n";
137 for ($i = 0; $i < count($columns); $i++) {
145 $sql .= $this->_columnSql($cd);
149 $uniques[] = $cd->name;
152 $primary[] = $cd->name;
155 $indices[] = $cd->name;
160 if (count($primary) > 0) { // it really should be...
161 $sql .= ",\nconstraint primary key (" . implode(',', $primary) . ")";
164 foreach ($uniques as $u) {
165 $sql .= ",\nunique index {$name}_{$u}_idx ($u)";
168 foreach ($indices as $i) {
169 $sql .= ",\nindex {$name}_{$i}_idx ($i)";
174 $res = $this->conn->query($sql);
176 if (PEAR::isError($res)) {
177 throw new Exception($res->getMessage());
184 * Drops a table from the schema
186 * Throws an exception if the table is not found.
188 * @param string $name Name of the table to drop
190 * @return boolean success flag
193 public function dropTable($name)
195 $res = $this->conn->query("DROP TABLE $name");
197 if (PEAR::isError($res)) {
198 throw new Exception($res->getMessage());
205 * Adds an index to a table.
207 * If no name is provided, a name will be made up based
208 * on the table name and column names.
210 * Throws an exception on database error, esp. if the table
213 * @param string $table Name of the table
214 * @param array $columnNames Name of columns to index
215 * @param string $name (Optional) name of the index
217 * @return boolean success flag
220 public function createIndex($table, $columnNames, $name=null)
222 if (!is_array($columnNames)) {
223 $columnNames = array($columnNames);
227 $name = "{$table}_".implode("_", $columnNames)."_idx";
230 $res = $this->conn->query("ALTER TABLE $table ".
232 implode(",", $columnNames).")");
234 if (PEAR::isError($res)) {
235 throw new Exception($res->getMessage());
242 * Drops a named index from a table.
244 * @param string $table name of the table the index is on.
245 * @param string $name name of the index
247 * @return boolean success flag
250 public function dropIndex($table, $name)
252 $res = $this->conn->query("ALTER TABLE $table DROP INDEX $name");
254 if (PEAR::isError($res)) {
255 throw new Exception($res->getMessage());
262 * Adds a column to a table
264 * @param string $table name of the table
265 * @param ColumnDef $columndef Definition of the new
268 * @return boolean success flag
271 public function addColumn($table, $columndef)
273 $sql = "ALTER TABLE $table ADD COLUMN " . $this->_columnSql($columndef);
275 $res = $this->conn->query($sql);
277 if (PEAR::isError($res)) {
278 throw new Exception($res->getMessage());
285 * Modifies a column in the schema.
287 * The name must match an existing column and table.
289 * @param string $table name of the table
290 * @param ColumnDef $columndef new definition of the column.
292 * @return boolean success flag
295 public function modifyColumn($table, $columndef)
297 $sql = "ALTER TABLE $table MODIFY COLUMN " .
298 $this->_columnSql($columndef);
300 $res = $this->conn->query($sql);
302 if (PEAR::isError($res)) {
303 throw new Exception($res->getMessage());
310 * Drops a column from a table
312 * The name must match an existing column.
314 * @param string $table name of the table
315 * @param string $columnName name of the column to drop
317 * @return boolean success flag
320 public function dropColumn($table, $columnName)
322 $sql = "ALTER TABLE $table DROP COLUMN $columnName";
324 $res = $this->conn->query($sql);
326 if (PEAR::isError($res)) {
327 throw new Exception($res->getMessage());
334 * Ensures that a table exists with the given
335 * name and the given column definitions.
337 * If the table does not yet exist, it will
338 * create the table. If it does exist, it will
339 * alter the table to match the column definitions.
341 * @param string $tableName name of the table
342 * @param array $columns array of ColumnDef
343 * objects for the table
345 * @return boolean success flag
348 public function ensureTable($tableName, $def)
350 // XXX: DB engine portability -> toilet
353 $old = $this->getTableDef($tableName);
354 } catch (Exception $e) {
355 if (preg_match('/no such table/', $e->getMessage())) {
356 return $this->createTable($tableName, $columns);
362 $cur = array_keys($old['fields']);
363 $new = array_keys($def['fields']);
365 $toadd = array_diff($new, $cur);
366 $todrop = array_diff($cur, $new);
367 $same = array_intersect($new, $cur);
370 // Find which fields have actually changed definition
371 // in a way that we need to tweak them for this DB type.
372 foreach ($same as $name) {
373 $curCol = $old['fields'][$name];
374 $newCol = $cur['fields'][$name];
376 if (!$this->columnsEqual($curCol, $newCol)) {
381 if (count($toadd) + count($todrop) + count($tomod) == 0) {
386 // For efficiency, we want this all in one
387 // query, instead of using our methods.
391 foreach ($toadd as $columnName) {
392 $this->appendAlterAddColumn($phrase, $columnName,
393 $def['fields'][$columnName]);
396 foreach ($todrop as $columnName) {
397 $this->appendAlterModifyColumn($phrase, $columnName,
398 $old['fields'][$columnName],
399 $def['fields'][$columnName]);
402 foreach ($tomod as $columnName) {
403 $this->appendAlterDropColumn($phrase, $columnName);
406 $sql = 'ALTER TABLE ' . $tableName . ' ' . implode(', ', $phrase);
408 $res = $this->conn->query($sql);
410 if (PEAR::isError($res)) {
411 throw new Exception($res->getMessage());
418 * Append phrase(s) to an array of partial ALTER TABLE chunks in order
419 * to add the given column definition to the table.
421 * @param array $phrase
422 * @param string $columnName
425 function appendAlterAddColumn(array &$phrase, $columnName, array $cd)
427 $phrase[] = 'ADD COLUMN ' .
428 $this->quoteIdentifier($columnName) .
430 $this->columnSql($cd);
434 * Append phrase(s) to an array of partial ALTER TABLE chunks in order
435 * to alter the given column from its old state to a new one.
437 * @param array $phrase
438 * @param string $columnName
439 * @param array $old previous column definition as found in DB
440 * @param array $cd current column definition
442 function appendAlterModifyColumn(array &$phrase, $columnName, array $old, array $cd)
444 $phrase[] = 'MODIFY COLUMN ' .
445 $this->quoteIdentifier($columnName) .
447 $this->columnSql($cd);
451 * Append phrase(s) to an array of partial ALTER TABLE chunks in order
452 * to drop the given column definition from the table.
454 * @param array $phrase
455 * @param string $columnName
457 function appendAlterDropColumn(array &$phrase, $columnName)
459 $phrase[] = 'DROP COLUMN ' . $this->quoteIdentifier($columnName);
463 * Quote a db/table/column identifier if necessary.
465 * @param string $name
468 function quoteIdentifier($name)
473 function quoteDefaultValue($cd)
475 if ($cd['type'] == 'datetime' && $cd['default'] == 'CURRENT_TIMESTAMP') {
476 return $cd['default'];
478 return $this->quoteValue($cd['default']);
482 function quoteValue($val)
484 return $this->conn->escape($val);
488 * Check if two column definitions are equivalent.
489 * The default implementation checks _everything_ but in many cases
490 * you may be able to discard a bunch of equivalencies.
496 function columnsEqual(array $a, array $b)
498 return !array_diff_assoc($a, $b) && !array_diff_assoc($b, $a);
502 * Returns the array of names from an array of
505 * @param array $cds array of ColumnDef objects
507 * @return array strings for name values
510 protected function _names($cds)
514 foreach ($cds as $cd) {
515 $names[] = $cd->name;
522 * Get a ColumnDef from an array matching
525 * @param array $cds Array of ColumnDef objects
526 * @param string $name Name of the column
528 * @return ColumnDef matching item or null if no match.
531 protected function _byName($cds, $name)
533 foreach ($cds as $cd) {
534 if ($cd->name == $name) {
543 * Return the proper SQL for creating or
546 * Appropriate for use in CREATE TABLE or
547 * ALTER TABLE statements.
549 * @param ColumnDef $cd column to create
551 * @return string correct SQL for that column
554 function columnSql(array $cd)
557 $line[] = $this->typeAndSize();
559 if (isset($cd['default'])) {
561 $line[] = $this->quoted($cd['default']);
562 } else if (!empty($cd['not null'])) {
563 // Can't have both not null AND default!
564 $line[] = 'not null';
567 return implode(' ', $line);
572 * @param string $column canonical type name in defs
573 * @return string native DB type name
575 function mapType($column)
580 function typeAndSize($column)
582 $type = $this->mapType($column);
585 if ($column['type'] == 'numeric') {
586 if (isset($column['precision'])) {
587 $lengths[] = $column['precision'];
588 if (isset($column['scale'])) {
589 $lengths[] = $column['scale'];
592 } else if (isset($column['length'])) {
593 $lengths[] = $column['length'];
597 return $type . '(' . implode(',', $lengths) . ')';
604 * Map a native type back to an independent type + size
606 * @param string $type
607 * @return array ($type, $size) -- $size may be null
609 protected function reverseMapType($type)
611 return array($type, null);
615 * Convert an old-style set of ColumnDef objects into the current
616 * Drupal-style schema definition array, for backwards compatibility
617 * with plugins written for 0.9.x.
619 * @param string $tableName
623 function oldToNew($tableName, $defs)
632 foreach ($defs as $cd) {
633 $cd->addToTableDef($table);
635 $column['type'] = $cd->type;
636 foreach ($prefixes as $prefix) {
637 if (substr($cd->type, 0, strlen($prefix)) == $prefix) {
638 $column['type'] = substr($cd->type, strlen($prefix));
639 $column['size'] = $prefix;
645 if ($cd->type == 'varchar' || $cd->type == 'char') {
646 $column['length'] = $cd->size;
649 if (!$cd->nullable) {
650 $column['not null'] = true;
652 if ($cd->autoincrement) {
653 $column['type'] = 'serial';
656 $column['default'] = $cd->default;
658 $table['fields'][$cd->name] = $column;
660 if ($cd->key == 'PRI') {
661 // If multiple columns are defined as primary key,
662 // we'll pile them on in sequence.
663 if (!isset($table['primary key'])) {
664 $table['primary key'] = array();
666 $table['primary key'][] = $cd->name;
667 } else if ($cd->key == 'MUL') {
668 // Individual multiple-value indexes are only per-column
669 // using the old ColumnDef syntax.
670 $idx = "{$tableName}_{$cd->name}_idx";
671 $table['indexes'][$idx] = array($cd->name);
672 } else if ($cd->key == 'UNI') {
673 // Individual unique-value indexes are only per-column
674 // using the old ColumnDef syntax.
675 $idx = "{$tableName}_{$cd->name}_idx";
676 $table['unique keys'][$idx] = array($cd->name);
683 function isNumericType($type)
685 $type = strtolower($type);
686 $known = array('int', 'serial', 'numeric');
687 return in_array($type, $known);
691 * Pull info from the query into a fun-fun array of dooooom
694 * @return array of arrays
696 protected function fetchQueryData($sql)
698 $res = $this->conn->query($sql);
699 if (PEAR::isError($res)) {
700 throw new Exception($res->getMessage());
705 while ($res->fetchInto($row, DB_FETCHMODE_ASSOC)) {
715 class SchemaTableMissingException extends Exception