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 if (empty(self::$_single)) {
79 self::$_single = new Schema();
81 return self::$_single;
85 * Returns a TableDef object for the table
86 * in the schema with the given name.
88 * Throws an exception if the table is not found.
90 * @param string $name Name of the table to get
92 * @return TableDef tabledef for that table.
95 public function getTableDef($name)
97 if(common_config('db','type') == 'pgsql') {
98 $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'");
101 $res = $this->conn->query('DESCRIBE ' . $name);
104 if (PEAR::isError($res)) {
105 throw new Exception($res->getMessage());
108 $td = new TableDef();
111 $td->columns = array();
115 while ($res->fetchInto($row, DB_FETCHMODE_ASSOC)) {
116 //lower case the keys, because the php postgres driver is case insentive for column names
117 foreach($row as $k=>$v) {
118 $row[strtolower($k)] = $row[$k];
121 $cd = new ColumnDef();
123 $cd->name = $row['field'];
125 $packed = $row['type'];
127 if (preg_match('/^(\w+)\((\d+)\)$/', $packed, $match)) {
128 $cd->type = $match[1];
129 $cd->size = $match[2];
134 $cd->nullable = ($row['null'] == 'YES') ? true : false;
135 $cd->key = $row['Key'];
136 $cd->default = $row['default'];
137 $cd->extra = $row['Extra'];
139 $td->columns[] = $cd;
146 * Gets a ColumnDef object for a single column.
148 * Throws an exception if the table is not found.
150 * @param string $table name of the table
151 * @param string $column name of the column
153 * @return ColumnDef definition of the column or null
157 public function getColumnDef($table, $column)
159 $td = $this->getTableDef($table);
161 foreach ($td->columns as $cd) {
162 if ($cd->name == $column) {
171 * Creates a table with the given names and columns.
173 * @param string $name Name of the table
174 * @param array $columns Array of ColumnDef objects
177 * @return boolean success flag
180 public function createTable($name, $columns)
186 $sql = "CREATE TABLE $name (\n";
188 for ($i = 0; $i < count($columns); $i++) {
196 $sql .= $this->_columnSql($cd);
200 $uniques[] = $cd->name;
203 $primary[] = $cd->name;
206 $indices[] = $cd->name;
211 if (count($primary) > 0) { // it really should be...
212 $sql .= ",\nconstraint primary key (" . implode(',', $primary) . ")";
215 foreach ($uniques as $u) {
216 $sql .= ",\nunique index {$name}_{$u}_idx ($u)";
219 foreach ($indices as $i) {
220 $sql .= ",\nindex {$name}_{$i}_idx ($i)";
225 $res = $this->conn->query($sql);
227 if (PEAR::isError($res)) {
228 throw new Exception($res->getMessage());
235 * Drops a table from the schema
237 * Throws an exception if the table is not found.
239 * @param string $name Name of the table to drop
241 * @return boolean success flag
244 public function dropTable($name)
246 $res = $this->conn->query("DROP TABLE $name");
248 if (PEAR::isError($res)) {
249 throw new Exception($res->getMessage());
256 * Adds an index to a table.
258 * If no name is provided, a name will be made up based
259 * on the table name and column names.
261 * Throws an exception on database error, esp. if the table
264 * @param string $table Name of the table
265 * @param array $columnNames Name of columns to index
266 * @param string $name (Optional) name of the index
268 * @return boolean success flag
271 public function createIndex($table, $columnNames, $name=null)
273 if (!is_array($columnNames)) {
274 $columnNames = array($columnNames);
278 $name = "$table_".implode("_", $columnNames)."_idx";
281 $res = $this->conn->query("ALTER TABLE $table ".
283 implode(",", $columnNames).")");
285 if (PEAR::isError($res)) {
286 throw new Exception($res->getMessage());
293 * Drops a named index from a table.
295 * @param string $table name of the table the index is on.
296 * @param string $name name of the index
298 * @return boolean success flag
301 public function dropIndex($table, $name)
303 $res = $this->conn->query("ALTER TABLE $table DROP INDEX $name");
305 if (PEAR::isError($res)) {
306 throw new Exception($res->getMessage());
313 * Adds a column to a table
315 * @param string $table name of the table
316 * @param ColumnDef $columndef Definition of the new
319 * @return boolean success flag
322 public function addColumn($table, $columndef)
324 $sql = "ALTER TABLE $table ADD COLUMN " . $this->_columnSql($columndef);
326 $res = $this->conn->query($sql);
328 if (PEAR::isError($res)) {
329 throw new Exception($res->getMessage());
336 * Modifies a column in the schema.
338 * The name must match an existing column and table.
340 * @param string $table name of the table
341 * @param ColumnDef $columndef new definition of the column.
343 * @return boolean success flag
346 public function modifyColumn($table, $columndef)
348 $sql = "ALTER TABLE $table MODIFY COLUMN " .
349 $this->_columnSql($columndef);
351 $res = $this->conn->query($sql);
353 if (PEAR::isError($res)) {
354 throw new Exception($res->getMessage());
361 * Drops a column from a table
363 * The name must match an existing column.
365 * @param string $table name of the table
366 * @param string $columnName name of the column to drop
368 * @return boolean success flag
371 public function dropColumn($table, $columnName)
373 $sql = "ALTER TABLE $table DROP COLUMN $columnName";
375 $res = $this->conn->query($sql);
377 if (PEAR::isError($res)) {
378 throw new Exception($res->getMessage());
385 * Ensures that a table exists with the given
386 * name and the given column definitions.
388 * If the table does not yet exist, it will
389 * create the table. If it does exist, it will
390 * alter the table to match the column definitions.
392 * @param string $tableName name of the table
393 * @param array $columns array of ColumnDef
394 * objects for the table
396 * @return boolean success flag
399 public function ensureTable($tableName, $columns)
401 // XXX: DB engine portability -> toilet
404 $td = $this->getTableDef($tableName);
405 } catch (Exception $e) {
406 if (preg_match('/no such table/', $e->getMessage())) {
407 return $this->createTable($tableName, $columns);
413 $cur = $this->_names($td->columns);
414 $new = $this->_names($columns);
416 $toadd = array_diff($new, $cur);
417 $todrop = array_diff($cur, $new);
418 $same = array_intersect($new, $cur);
421 foreach ($same as $m) {
422 $curCol = $this->_byName($td->columns, $m);
423 $newCol = $this->_byName($columns, $m);
425 if (!$newCol->equals($curCol)) {
426 $tomod[] = $newCol->name;
430 if (count($toadd) + count($todrop) + count($tomod) == 0) {
435 // For efficiency, we want this all in one
436 // query, instead of using our methods.
440 foreach ($toadd as $columnName) {
441 $cd = $this->_byName($columns, $columnName);
443 $phrase[] = 'ADD COLUMN ' . $this->_columnSql($cd);
446 foreach ($todrop as $columnName) {
447 $phrase[] = 'DROP COLUMN ' . $columnName;
450 foreach ($tomod as $columnName) {
451 $cd = $this->_byName($columns, $columnName);
453 $phrase[] = 'MODIFY COLUMN ' . $this->_columnSql($cd);
456 $sql = 'ALTER TABLE ' . $tableName . ' ' . implode(', ', $phrase);
458 $res = $this->conn->query($sql);
460 if (PEAR::isError($res)) {
461 throw new Exception($res->getMessage());
468 * Returns the array of names from an array of
471 * @param array $cds array of ColumnDef objects
473 * @return array strings for name values
476 private function _names($cds)
480 foreach ($cds as $cd) {
481 $names[] = $cd->name;
488 * Get a ColumnDef from an array matching
491 * @param array $cds Array of ColumnDef objects
492 * @param string $name Name of the column
494 * @return ColumnDef matching item or null if no match.
497 private function _byName($cds, $name)
499 foreach ($cds as $cd) {
500 if ($cd->name == $name) {
509 * Return the proper SQL for creating or
512 * Appropriate for use in CREATE TABLE or
513 * ALTER TABLE statements.
515 * @param ColumnDef $cd column to create
517 * @return string correct SQL for that column
520 private function _columnSql($cd)
522 $sql = "{$cd->name} ";
524 if (!empty($cd->size)) {
525 $sql .= "{$cd->type}({$cd->size}) ";
527 $sql .= "{$cd->type} ";
530 if (!empty($cd->default)) {
531 $sql .= "default {$cd->default} ";
533 $sql .= ($cd->nullable) ? "null " : "not null ";
536 if (!empty($cd->auto_increment)) {
537 $sql .= " auto_increment ";
540 if (!empty($cd->extra)) {
541 $sql .= "{$cd->extra} ";