4 * StatusNet, the distributed open-source microblogging tool
6 * Database schema utilities
10 * LICENCE: This program is free software: you can redistribute it and/or modify
11 * it under the terms of the GNU Affero General Public License as published by
12 * the Free Software Foundation, either version 3 of the License, or
13 * (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU Affero General Public License for more details.
20 * You should have received a copy of the GNU Affero General Public License
21 * along with this program. If not, see <http://www.gnu.org/licenses/>.
25 * @author Evan Prodromou <evan@status.net>
26 * @copyright 2009 StatusNet, Inc.
27 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
28 * @link http://status.net/
31 if (!defined('STATUSNET')) {
36 * Class representing the database schema
38 * A class representing the database schema. Can be used to
39 * manipulate the schema -- especially for plugins and upgrade
44 * @author Evan Prodromou <evan@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/
49 class PgsqlSchema extends Schema
53 * Returns a TableDef object for the table
54 * in the schema with the given name.
56 * Throws an exception if the table is not found.
58 * @param string $name Name of the table to get
60 * @return TableDef tabledef for that table.
63 public function getTableDef($name)
65 $res = $this->conn->query("SELECT *, column_default as default, is_nullable as Null,
66 udt_name as Type, column_name AS Field from INFORMATION_SCHEMA.COLUMNS where table_name = '$name'");
68 if (PEAR::isError($res)) {
69 throw new Exception($res->getMessage());
75 $td->columns = array();
77 if ($res->numRows() == 0 ) {
78 throw new Exception('no such table'); //pretend to be the msyql error. yeah, this sucks.
82 while ($res->fetchInto($row, DB_FETCHMODE_ASSOC)) {
84 $cd = new ColumnDef();
86 $cd->name = $row['field'];
88 $packed = $row['type'];
90 if (preg_match('/^(\w+)\((\d+)\)$/', $packed, $match)) {
91 $cd->type = $match[1];
92 $cd->size = $match[2];
97 $cd->nullable = ($row['null'] == 'YES') ? true : false;
98 $cd->key = $row['Key'];
99 $cd->default = $row['default'];
100 $cd->extra = $row['Extra'];
102 $td->columns[] = $cd;
108 * Gets a ColumnDef object for a single column.
110 * Throws an exception if the table is not found.
112 * @param string $table name of the table
113 * @param string $column name of the column
115 * @return ColumnDef definition of the column or null
119 public function getColumnDef($table, $column)
121 $td = $this->getTableDef($table);
123 foreach ($td->columns as $cd) {
124 if ($cd->name == $column) {
133 * Creates a table with the given names and columns.
135 * @param string $name Name of the table
136 * @param array $columns Array of ColumnDef objects
139 * @return boolean success flag
142 public function createTable($name, $columns)
148 $sql = "CREATE TABLE $name (\n";
150 for ($i = 0; $i < count($columns); $i++) {
158 $sql .= $this->_columnSql($cd);
162 $uniques[] = $cd->name;
165 $primary[] = $cd->name;
168 $indices[] = $cd->name;
173 if (count($primary) > 0) { // it really should be...
174 $sql .= ",\nconstraint primary key (" . implode(',', $primary) . ")";
177 foreach ($uniques as $u) {
178 $sql .= ",\nunique index {$name}_{$u}_idx ($u)";
181 foreach ($indices as $i) {
182 $sql .= ",\nindex {$name}_{$i}_idx ($i)";
187 $res = $this->conn->query($sql);
189 if (PEAR::isError($res)) {
190 throw new Exception($res->getMessage());
197 * Drops a table from the schema
199 * Throws an exception if the table is not found.
201 * @param string $name Name of the table to drop
203 * @return boolean success flag
206 public function dropTable($name)
208 $res = $this->conn->query("DROP TABLE $name");
210 if (PEAR::isError($res)) {
211 throw new Exception($res->getMessage());
218 * Adds an index to a table.
220 * If no name is provided, a name will be made up based
221 * on the table name and column names.
223 * Throws an exception on database error, esp. if the table
226 * @param string $table Name of the table
227 * @param array $columnNames Name of columns to index
228 * @param string $name (Optional) name of the index
230 * @return boolean success flag
233 public function createIndex($table, $columnNames, $name=null)
235 if (!is_array($columnNames)) {
236 $columnNames = array($columnNames);
240 $name = "$table_".implode("_", $columnNames)."_idx";
243 $res = $this->conn->query("ALTER TABLE $table ".
245 implode(",", $columnNames).")");
247 if (PEAR::isError($res)) {
248 throw new Exception($res->getMessage());
255 * Drops a named index from a table.
257 * @param string $table name of the table the index is on.
258 * @param string $name name of the index
260 * @return boolean success flag
263 public function dropIndex($table, $name)
265 $res = $this->conn->query("ALTER TABLE $table DROP INDEX $name");
267 if (PEAR::isError($res)) {
268 throw new Exception($res->getMessage());
275 * Adds a column to a table
277 * @param string $table name of the table
278 * @param ColumnDef $columndef Definition of the new
281 * @return boolean success flag
284 public function addColumn($table, $columndef)
286 $sql = "ALTER TABLE $table ADD COLUMN " . $this->_columnSql($columndef);
288 $res = $this->conn->query($sql);
290 if (PEAR::isError($res)) {
291 throw new Exception($res->getMessage());
298 * Modifies a column in the schema.
300 * The name must match an existing column and table.
302 * @param string $table name of the table
303 * @param ColumnDef $columndef new definition of the column.
305 * @return boolean success flag
308 public function modifyColumn($table, $columndef)
310 $sql = "ALTER TABLE $table MODIFY COLUMN " .
311 $this->_columnSql($columndef);
313 $res = $this->conn->query($sql);
315 if (PEAR::isError($res)) {
316 throw new Exception($res->getMessage());
323 * Drops a column from a table
325 * The name must match an existing column.
327 * @param string $table name of the table
328 * @param string $columnName name of the column to drop
330 * @return boolean success flag
333 public function dropColumn($table, $columnName)
335 $sql = "ALTER TABLE $table DROP COLUMN $columnName";
337 $res = $this->conn->query($sql);
339 if (PEAR::isError($res)) {
340 throw new Exception($res->getMessage());
347 * Ensures that a table exists with the given
348 * name and the given column definitions.
350 * If the table does not yet exist, it will
351 * create the table. If it does exist, it will
352 * alter the table to match the column definitions.
354 * @param string $tableName name of the table
355 * @param array $columns array of ColumnDef
356 * objects for the table
358 * @return boolean success flag
361 public function ensureTable($tableName, $columns)
363 // XXX: DB engine portability -> toilet
366 $td = $this->getTableDef($tableName);
368 } catch (Exception $e) {
369 if (preg_match('/no such table/', $e->getMessage())) {
370 return $this->createTable($tableName, $columns);
376 $cur = $this->_names($td->columns);
377 $new = $this->_names($columns);
379 $toadd = array_diff($new, $cur);
380 $todrop = array_diff($cur, $new);
381 $same = array_intersect($new, $cur);
384 foreach ($same as $m) {
385 $curCol = $this->_byName($td->columns, $m);
386 $newCol = $this->_byName($columns, $m);
388 if (!$newCol->equals($curCol)) {
389 $tomod[] = $newCol->name;
393 if (count($toadd) + count($todrop) + count($tomod) == 0) {
398 // For efficiency, we want this all in one
399 // query, instead of using our methods.
403 foreach ($toadd as $columnName) {
404 $cd = $this->_byName($columns, $columnName);
406 $phrase[] = 'ADD COLUMN ' . $this->_columnSql($cd);
409 foreach ($todrop as $columnName) {
410 $phrase[] = 'DROP COLUMN ' . $columnName;
413 foreach ($tomod as $columnName) {
414 $cd = $this->_byName($columns, $columnName);
416 $phrase[] = 'MODIFY COLUMN ' . $this->_columnSql($cd);
419 $sql = 'ALTER TABLE ' . $tableName . ' ' . implode(', ', $phrase);
421 $res = $this->conn->query($sql);
423 if (PEAR::isError($res)) {
424 throw new Exception($res->getMessage());
431 * Returns the array of names from an array of
434 * @param array $cds array of ColumnDef objects
436 * @return array strings for name values
439 private function _names($cds)
443 foreach ($cds as $cd) {
444 $names[] = $cd->name;
451 * Get a ColumnDef from an array matching
454 * @param array $cds Array of ColumnDef objects
455 * @param string $name Name of the column
457 * @return ColumnDef matching item or null if no match.
460 private function _byName($cds, $name)
462 foreach ($cds as $cd) {
463 if ($cd->name == $name) {
472 * Return the proper SQL for creating or
475 * Appropriate for use in CREATE TABLE or
476 * ALTER TABLE statements.
478 * @param ColumnDef $cd column to create
480 * @return string correct SQL for that column
483 private function _columnSql($cd)
485 $sql = "{$cd->name} ";
487 if (!empty($cd->size)) {
488 $sql .= "{$cd->type}({$cd->size}) ";
490 $sql .= "{$cd->type} ";
493 if (!empty($cd->default)) {
494 $sql .= "default {$cd->default} ";
496 $sql .= ($cd->nullable) ? "null " : "not null ";
499 if (!empty($cd->auto_increment)) {
500 $sql .= " auto_increment ";
503 if (!empty($cd->extra)) {
504 $sql .= "{$cd->extra} ";