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, $columns)
350 // XXX: DB engine portability -> toilet
353 $td = $this->getTableDef($tableName);
354 } catch (Exception $e) {
355 if (preg_match('/no such table/', $e->getMessage())) {
356 return $this->createTable($tableName, $columns);
362 $cur = $this->_names($td->columns);
363 $new = $this->_names($columns);
365 $toadd = array_diff($new, $cur);
366 $todrop = array_diff($cur, $new);
367 $same = array_intersect($new, $cur);
370 foreach ($same as $m) {
371 $curCol = $this->_byName($td->columns, $m);
372 $newCol = $this->_byName($columns, $m);
374 if (!$newCol->equals($curCol)) {
375 $tomod[] = $newCol->name;
379 if (count($toadd) + count($todrop) + count($tomod) == 0) {
384 // For efficiency, we want this all in one
385 // query, instead of using our methods.
389 foreach ($toadd as $columnName) {
390 $cd = $this->_byName($columns, $columnName);
392 $phrase[] = 'ADD COLUMN ' . $this->_columnSql($cd);
395 foreach ($todrop as $columnName) {
396 $phrase[] = 'DROP COLUMN ' . $columnName;
399 foreach ($tomod as $columnName) {
400 $cd = $this->_byName($columns, $columnName);
402 $phrase[] = 'MODIFY COLUMN ' . $this->_columnSql($cd);
405 $sql = 'ALTER TABLE ' . $tableName . ' ' . implode(', ', $phrase);
407 $res = $this->conn->query($sql);
409 if (PEAR::isError($res)) {
410 throw new Exception($res->getMessage());
417 * Returns the array of names from an array of
420 * @param array $cds array of ColumnDef objects
422 * @return array strings for name values
425 protected function _names($cds)
429 foreach ($cds as $cd) {
430 $names[] = $cd->name;
437 * Get a ColumnDef from an array matching
440 * @param array $cds Array of ColumnDef objects
441 * @param string $name Name of the column
443 * @return ColumnDef matching item or null if no match.
446 protected function _byName($cds, $name)
448 foreach ($cds as $cd) {
449 if ($cd->name == $name) {
458 * Return the proper SQL for creating or
461 * Appropriate for use in CREATE TABLE or
462 * ALTER TABLE statements.
464 * @param ColumnDef $cd column to create
466 * @return string correct SQL for that column
469 function columnSql(array $cd)
472 $line[] = $this->typeAndSize();
474 if (isset($cd['default'])) {
476 $line[] = $this->quoted($cd['default']);
477 } else if (!empty($cd['not null'])) {
478 // Can't have both not null AND default!
479 $line[] = 'not null';
482 return implode(' ', $line);
487 * @param string $column canonical type name in defs
488 * @return string native DB type name
490 function mapType($column)
495 function typeAndSize($column)
497 $type = $this->mapType($column);
500 if ($column['type'] == 'numeric') {
501 if (isset($column['precision'])) {
502 $lengths[] = $column['precision'];
503 if (isset($column['scale'])) {
504 $lengths[] = $column['scale'];
507 } else if (isset($column['length'])) {
508 $lengths[] = $column['length'];
512 return $type . '(' . implode(',', $lengths) . ')';
519 * Map a native type back to an independent type + size
521 * @param string $type
522 * @return array ($type, $size) -- $size may be null
524 protected function reverseMapType($type)
526 return array($type, null);
530 * Convert an old-style set of ColumnDef objects into the current
531 * Drupal-style schema definition array, for backwards compatibility
532 * with plugins written for 0.9.x.
534 * @param string $tableName
538 function oldToNew($tableName, $defs)
547 foreach ($defs as $cd) {
548 $cd->addToTableDef($table);
550 $column['type'] = $cd->type;
551 foreach ($prefixes as $prefix) {
552 if (substr($cd->type, 0, strlen($prefix)) == $prefix) {
553 $column['type'] = substr($cd->type, strlen($prefix));
554 $column['size'] = $prefix;
560 if ($cd->type == 'varchar' || $cd->type == 'char') {
561 $column['length'] = $cd->size;
564 if (!$cd->nullable) {
565 $column['not null'] = true;
567 if ($cd->autoincrement) {
568 $column['type'] = 'serial';
571 $column['default'] = $cd->default;
573 $table['fields'][$cd->name] = $column;
575 if ($cd->key == 'PRI') {
576 // If multiple columns are defined as primary key,
577 // we'll pile them on in sequence.
578 if (!isset($table['primary key'])) {
579 $table['primary key'] = array();
581 $table['primary key'][] = $cd->name;
582 } else if ($cd->key == 'MUL') {
583 // Individual multiple-value indexes are only per-column
584 // using the old ColumnDef syntax.
585 $idx = "{$tableName}_{$cd->name}_idx";
586 $table['indexes'][$idx] = array($cd->name);
587 } else if ($cd->key == 'UNI') {
588 // Individual unique-value indexes are only per-column
589 // using the old ColumnDef syntax.
590 $idx = "{$tableName}_{$cd->name}_idx";
591 $table['unique keys'][$idx] = array($cd->name);
598 function isNumericType($type)
600 $type = strtolower($type);
601 $known = array('int', 'serial', 'numeric');
602 return in_array($type, $known);
606 * Pull info from the query into a fun-fun array of dooooom
609 * @return array of arrays
611 protected function fetchQueryData($sql)
613 $res = $this->conn->query($sql);
614 if (PEAR::isError($res)) {
615 throw new Exception($res->getMessage());
620 while ($res->fetchInto($row, DB_FETCHMODE_ASSOC)) {
630 class SchemaTableMissingException extends Exception