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 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
45 * @link http://status.net/
50 static $_single = null;
51 protected $conn = null;
54 * Constructor. Only run once for singleton object.
57 protected function __construct()
59 // XXX: there should be an easier way to do this.
62 $this->conn = $user->getDatabaseConnection();
70 * Main public entry point. Use this to get
71 * the singleton object.
73 * @return Schema the (single) Schema object
78 $type = common_config('db', 'type');
79 if (empty(self::$_single)) {
80 include "lib/schema.{$type}.php";
81 $class = $type.='Schema';
82 self::$_single = new $class();
84 return self::$_single;
88 * Returns a TableDef object for the table
89 * in the schema with the given name.
91 * Throws an exception if the table is not found.
93 * @param string $name Name of the table to get
95 * @return TableDef tabledef for that table.
98 public function getTableDef($name)
100 $res = $this->conn->query('DESCRIBE ' . $name);
102 if (PEAR::isError($res)) {
103 throw new Exception($res->getMessage());
106 $td = new TableDef();
109 $td->columns = array();
113 while ($res->fetchInto($row, DB_FETCHMODE_ASSOC)) {
115 $cd = new ColumnDef();
117 $cd->name = $row['Field'];
119 $packed = $row['Type'];
121 if (preg_match('/^(\w+)\((\d+)\)$/', $packed, $match)) {
122 $cd->type = $match[1];
123 $cd->size = $match[2];
128 $cd->nullable = ($row['Null'] == 'YES') ? true : false;
129 $cd->key = $row['Key'];
130 $cd->default = $row['Default'];
131 $cd->extra = $row['Extra'];
133 $td->columns[] = $cd;
140 * Gets a ColumnDef object for a single column.
142 * Throws an exception if the table is not found.
144 * @param string $table name of the table
145 * @param string $column name of the column
147 * @return ColumnDef definition of the column or null
151 public function getColumnDef($table, $column)
153 $td = $this->getTableDef($table);
155 foreach ($td->columns as $cd) {
156 if ($cd->name == $column) {
165 * Creates a table with the given names and columns.
167 * @param string $name Name of the table
168 * @param array $columns Array of ColumnDef objects
171 * @return boolean success flag
174 public function createTable($name, $columns)
180 $sql = "CREATE TABLE $name (\n";
182 for ($i = 0; $i < count($columns); $i++) {
190 $sql .= $this->_columnSql($cd);
194 $uniques[] = $cd->name;
197 $primary[] = $cd->name;
200 $indices[] = $cd->name;
205 if (count($primary) > 0) { // it really should be...
206 $sql .= ",\nconstraint primary key (" . implode(',', $primary) . ")";
209 foreach ($uniques as $u) {
210 $sql .= ",\nunique index {$name}_{$u}_idx ($u)";
213 foreach ($indices as $i) {
214 $sql .= ",\nindex {$name}_{$i}_idx ($i)";
219 $res = $this->conn->query($sql);
221 if (PEAR::isError($res)) {
222 throw new Exception($res->getMessage());
229 * Drops a table from the schema
231 * Throws an exception if the table is not found.
233 * @param string $name Name of the table to drop
235 * @return boolean success flag
238 public function dropTable($name)
240 $res = $this->conn->query("DROP TABLE $name");
242 if (PEAR::isError($res)) {
243 throw new Exception($res->getMessage());
250 * Adds an index to a table.
252 * If no name is provided, a name will be made up based
253 * on the table name and column names.
255 * Throws an exception on database error, esp. if the table
258 * @param string $table Name of the table
259 * @param array $columnNames Name of columns to index
260 * @param string $name (Optional) name of the index
262 * @return boolean success flag
265 public function createIndex($table, $columnNames, $name=null)
267 if (!is_array($columnNames)) {
268 $columnNames = array($columnNames);
272 $name = "$table_".implode("_", $columnNames)."_idx";
275 $res = $this->conn->query("ALTER TABLE $table ".
277 implode(",", $columnNames).")");
279 if (PEAR::isError($res)) {
280 throw new Exception($res->getMessage());
287 * Drops a named index from a table.
289 * @param string $table name of the table the index is on.
290 * @param string $name name of the index
292 * @return boolean success flag
295 public function dropIndex($table, $name)
297 $res = $this->conn->query("ALTER TABLE $table DROP INDEX $name");
299 if (PEAR::isError($res)) {
300 throw new Exception($res->getMessage());
307 * Adds a column to a table
309 * @param string $table name of the table
310 * @param ColumnDef $columndef Definition of the new
313 * @return boolean success flag
316 public function addColumn($table, $columndef)
318 $sql = "ALTER TABLE $table ADD COLUMN " . $this->_columnSql($columndef);
320 $res = $this->conn->query($sql);
322 if (PEAR::isError($res)) {
323 throw new Exception($res->getMessage());
330 * Modifies a column in the schema.
332 * The name must match an existing column and table.
334 * @param string $table name of the table
335 * @param ColumnDef $columndef new definition of the column.
337 * @return boolean success flag
340 public function modifyColumn($table, $columndef)
342 $sql = "ALTER TABLE $table MODIFY COLUMN " .
343 $this->_columnSql($columndef);
345 $res = $this->conn->query($sql);
347 if (PEAR::isError($res)) {
348 throw new Exception($res->getMessage());
355 * Drops a column from a table
357 * The name must match an existing column.
359 * @param string $table name of the table
360 * @param string $columnName name of the column to drop
362 * @return boolean success flag
365 public function dropColumn($table, $columnName)
367 $sql = "ALTER TABLE $table DROP COLUMN $columnName";
369 $res = $this->conn->query($sql);
371 if (PEAR::isError($res)) {
372 throw new Exception($res->getMessage());
379 * Ensures that a table exists with the given
380 * name and the given column definitions.
382 * If the table does not yet exist, it will
383 * create the table. If it does exist, it will
384 * alter the table to match the column definitions.
386 * @param string $tableName name of the table
387 * @param array $columns array of ColumnDef
388 * objects for the table
390 * @return boolean success flag
393 public function ensureTable($tableName, $columns)
395 // XXX: DB engine portability -> toilet
398 $td = $this->getTableDef($tableName);
399 } catch (Exception $e) {
400 if (preg_match('/no such table/', $e->getMessage())) {
401 return $this->createTable($tableName, $columns);
407 $cur = $this->_names($td->columns);
408 $new = $this->_names($columns);
410 $toadd = array_diff($new, $cur);
411 $todrop = array_diff($cur, $new);
412 $same = array_intersect($new, $cur);
415 foreach ($same as $m) {
416 $curCol = $this->_byName($td->columns, $m);
417 $newCol = $this->_byName($columns, $m);
419 if (!$newCol->equals($curCol)) {
420 $tomod[] = $newCol->name;
424 if (count($toadd) + count($todrop) + count($tomod) == 0) {
429 // For efficiency, we want this all in one
430 // query, instead of using our methods.
434 foreach ($toadd as $columnName) {
435 $cd = $this->_byName($columns, $columnName);
437 $phrase[] = 'ADD COLUMN ' . $this->_columnSql($cd);
440 foreach ($todrop as $columnName) {
441 $phrase[] = 'DROP COLUMN ' . $columnName;
444 foreach ($tomod as $columnName) {
445 $cd = $this->_byName($columns, $columnName);
447 $phrase[] = 'MODIFY COLUMN ' . $this->_columnSql($cd);
450 $sql = 'ALTER TABLE ' . $tableName . ' ' . implode(', ', $phrase);
452 $res = $this->conn->query($sql);
454 if (PEAR::isError($res)) {
455 throw new Exception($res->getMessage());
462 * Returns the array of names from an array of
465 * @param array $cds array of ColumnDef objects
467 * @return array strings for name values
470 private function _names($cds)
474 foreach ($cds as $cd) {
475 $names[] = $cd->name;
482 * Get a ColumnDef from an array matching
485 * @param array $cds Array of ColumnDef objects
486 * @param string $name Name of the column
488 * @return ColumnDef matching item or null if no match.
491 private function _byName($cds, $name)
493 foreach ($cds as $cd) {
494 if ($cd->name == $name) {
503 * Return the proper SQL for creating or
506 * Appropriate for use in CREATE TABLE or
507 * ALTER TABLE statements.
509 * @param ColumnDef $cd column to create
511 * @return string correct SQL for that column
514 private function _columnSql($cd)
516 $sql = "{$cd->name} ";
518 if (!empty($cd->size)) {
519 $sql .= "{$cd->type}({$cd->size}) ";
521 $sql .= "{$cd->type} ";
524 if (!empty($cd->default)) {
525 $sql .= "default {$cd->default} ";
527 $sql .= ($cd->nullable) ? "null " : "not null ";
530 if (!empty($cd->auto_increment)) {
531 $sql .= " auto_increment ";
534 if (!empty($cd->extra)) {
535 $sql .= "{$cd->extra} ";