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 if(common_config('db','type') == 'pgsql') {
101 $res = $this->conn->query("select column_default as default, is_nullable as Null, udt_name as Type, column_name AS Field from INFORMATION_SCHEMA.COLUMNS where table_name = '$name'");
104 $res = $this->conn->query('DESCRIBE ' . $name);
107 if (PEAR::isError($res)) {
108 throw new Exception($res->getMessage());
111 $td = new TableDef();
114 $td->columns = array();
118 while ($res->fetchInto($row, DB_FETCHMODE_ASSOC)) {
119 //lower case the keys, because the php postgres driver is case insentive for column names
120 foreach($row as $k=>$v) {
121 $row[strtolower($k)] = $row[$k];
124 $cd = new ColumnDef();
126 $cd->name = $row['field'];
128 $packed = $row['type'];
130 if (preg_match('/^(\w+)\((\d+)\)$/', $packed, $match)) {
131 $cd->type = $match[1];
132 $cd->size = $match[2];
137 $cd->nullable = ($row['null'] == 'YES') ? true : false;
138 $cd->key = $row['Key'];
139 $cd->default = $row['default'];
140 $cd->extra = $row['Extra'];
142 $td->columns[] = $cd;
149 * Gets a ColumnDef object for a single column.
151 * Throws an exception if the table is not found.
153 * @param string $table name of the table
154 * @param string $column name of the column
156 * @return ColumnDef definition of the column or null
160 public function getColumnDef($table, $column)
162 $td = $this->getTableDef($table);
164 foreach ($td->columns as $cd) {
165 if ($cd->name == $column) {
174 * Creates a table with the given names and columns.
176 * @param string $name Name of the table
177 * @param array $columns Array of ColumnDef objects
180 * @return boolean success flag
183 public function createTable($name, $columns)
189 $sql = "CREATE TABLE $name (\n";
191 for ($i = 0; $i < count($columns); $i++) {
199 $sql .= $this->_columnSql($cd);
203 $uniques[] = $cd->name;
206 $primary[] = $cd->name;
209 $indices[] = $cd->name;
214 if (count($primary) > 0) { // it really should be...
215 $sql .= ",\nconstraint primary key (" . implode(',', $primary) . ")";
218 foreach ($uniques as $u) {
219 $sql .= ",\nunique index {$name}_{$u}_idx ($u)";
222 foreach ($indices as $i) {
223 $sql .= ",\nindex {$name}_{$i}_idx ($i)";
228 $res = $this->conn->query($sql);
230 if (PEAR::isError($res)) {
231 throw new Exception($res->getMessage());
238 * Drops a table from the schema
240 * Throws an exception if the table is not found.
242 * @param string $name Name of the table to drop
244 * @return boolean success flag
247 public function dropTable($name)
249 $res = $this->conn->query("DROP TABLE $name");
251 if (PEAR::isError($res)) {
252 throw new Exception($res->getMessage());
259 * Adds an index to a table.
261 * If no name is provided, a name will be made up based
262 * on the table name and column names.
264 * Throws an exception on database error, esp. if the table
267 * @param string $table Name of the table
268 * @param array $columnNames Name of columns to index
269 * @param string $name (Optional) name of the index
271 * @return boolean success flag
274 public function createIndex($table, $columnNames, $name=null)
276 if (!is_array($columnNames)) {
277 $columnNames = array($columnNames);
281 $name = "$table_".implode("_", $columnNames)."_idx";
284 $res = $this->conn->query("ALTER TABLE $table ".
286 implode(",", $columnNames).")");
288 if (PEAR::isError($res)) {
289 throw new Exception($res->getMessage());
296 * Drops a named index from a table.
298 * @param string $table name of the table the index is on.
299 * @param string $name name of the index
301 * @return boolean success flag
304 public function dropIndex($table, $name)
306 $res = $this->conn->query("ALTER TABLE $table DROP INDEX $name");
308 if (PEAR::isError($res)) {
309 throw new Exception($res->getMessage());
316 * Adds a column to a table
318 * @param string $table name of the table
319 * @param ColumnDef $columndef Definition of the new
322 * @return boolean success flag
325 public function addColumn($table, $columndef)
327 $sql = "ALTER TABLE $table ADD COLUMN " . $this->_columnSql($columndef);
329 $res = $this->conn->query($sql);
331 if (PEAR::isError($res)) {
332 throw new Exception($res->getMessage());
339 * Modifies a column in the schema.
341 * The name must match an existing column and table.
343 * @param string $table name of the table
344 * @param ColumnDef $columndef new definition of the column.
346 * @return boolean success flag
349 public function modifyColumn($table, $columndef)
351 $sql = "ALTER TABLE $table MODIFY COLUMN " .
352 $this->_columnSql($columndef);
354 $res = $this->conn->query($sql);
356 if (PEAR::isError($res)) {
357 throw new Exception($res->getMessage());
364 * Drops a column from a table
366 * The name must match an existing column.
368 * @param string $table name of the table
369 * @param string $columnName name of the column to drop
371 * @return boolean success flag
374 public function dropColumn($table, $columnName)
376 $sql = "ALTER TABLE $table DROP COLUMN $columnName";
378 $res = $this->conn->query($sql);
380 if (PEAR::isError($res)) {
381 throw new Exception($res->getMessage());
388 * Ensures that a table exists with the given
389 * name and the given column definitions.
391 * If the table does not yet exist, it will
392 * create the table. If it does exist, it will
393 * alter the table to match the column definitions.
395 * @param string $tableName name of the table
396 * @param array $columns array of ColumnDef
397 * objects for the table
399 * @return boolean success flag
402 public function ensureTable($tableName, $columns)
404 // XXX: DB engine portability -> toilet
407 $td = $this->getTableDef($tableName);
408 } catch (Exception $e) {
409 if (preg_match('/no such table/', $e->getMessage())) {
410 return $this->createTable($tableName, $columns);
416 $cur = $this->_names($td->columns);
417 $new = $this->_names($columns);
419 $toadd = array_diff($new, $cur);
420 $todrop = array_diff($cur, $new);
421 $same = array_intersect($new, $cur);
424 foreach ($same as $m) {
425 $curCol = $this->_byName($td->columns, $m);
426 $newCol = $this->_byName($columns, $m);
428 if (!$newCol->equals($curCol)) {
429 $tomod[] = $newCol->name;
433 if (count($toadd) + count($todrop) + count($tomod) == 0) {
438 // For efficiency, we want this all in one
439 // query, instead of using our methods.
443 foreach ($toadd as $columnName) {
444 $cd = $this->_byName($columns, $columnName);
446 $phrase[] = 'ADD COLUMN ' . $this->_columnSql($cd);
449 foreach ($todrop as $columnName) {
450 $phrase[] = 'DROP COLUMN ' . $columnName;
453 foreach ($tomod as $columnName) {
454 $cd = $this->_byName($columns, $columnName);
456 $phrase[] = 'MODIFY COLUMN ' . $this->_columnSql($cd);
459 $sql = 'ALTER TABLE ' . $tableName . ' ' . implode(', ', $phrase);
461 $res = $this->conn->query($sql);
463 if (PEAR::isError($res)) {
464 throw new Exception($res->getMessage());
471 * Returns the array of names from an array of
474 * @param array $cds array of ColumnDef objects
476 * @return array strings for name values
479 private function _names($cds)
483 foreach ($cds as $cd) {
484 $names[] = $cd->name;
491 * Get a ColumnDef from an array matching
494 * @param array $cds Array of ColumnDef objects
495 * @param string $name Name of the column
497 * @return ColumnDef matching item or null if no match.
500 private function _byName($cds, $name)
502 foreach ($cds as $cd) {
503 if ($cd->name == $name) {
512 * Return the proper SQL for creating or
515 * Appropriate for use in CREATE TABLE or
516 * ALTER TABLE statements.
518 * @param ColumnDef $cd column to create
520 * @return string correct SQL for that column
523 private function _columnSql($cd)
525 $sql = "{$cd->name} ";
527 if (!empty($cd->size)) {
528 $sql .= "{$cd->type}({$cd->size}) ";
530 $sql .= "{$cd->type} ";
533 if (!empty($cd->default)) {
534 $sql .= "default {$cd->default} ";
536 $sql .= ($cd->nullable) ? "null " : "not null ";
539 if (!empty($cd->auto_increment)) {
540 $sql .= " auto_increment ";
543 if (!empty($cd->extra)) {
544 $sql .= "{$cd->extra} ";