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 .= ",\n primary key (" . implode(',', $primary) . ")";
179 foreach ($indices as $i) {
180 $sql .= ",\nindex {$name}_{$i}_idx ($i)";
186 foreach ($uniques as $u) {
187 $sql .= "\n CREATE index {$name}_{$u}_idx ON {$name} ($u); ";
189 $res = $this->conn->query($sql);
191 if (PEAR::isError($res)) {
192 throw new Exception($res->getMessage());
199 * Drops a table from the schema
201 * Throws an exception if the table is not found.
203 * @param string $name Name of the table to drop
205 * @return boolean success flag
208 public function dropTable($name)
210 $res = $this->conn->query("DROP TABLE $name");
212 if (PEAR::isError($res)) {
213 throw new Exception($res->getMessage());
220 * Translate the (mostly) mysql-ish column types into somethings more standard
221 * @param string column type
223 * @return string postgres happy column type
225 private function _columnTypeTranslation($type) {
227 'datetime' => 'timestamp'
229 if(!empty($map[$type])) {
236 * Adds an index to a table.
238 * If no name is provided, a name will be made up based
239 * on the table name and column names.
241 * Throws an exception on database error, esp. if the table
244 * @param string $table Name of the table
245 * @param array $columnNames Name of columns to index
246 * @param string $name (Optional) name of the index
248 * @return boolean success flag
251 public function createIndex($table, $columnNames, $name=null)
253 if (!is_array($columnNames)) {
254 $columnNames = array($columnNames);
258 $name = "$table_".implode("_", $columnNames)."_idx";
261 $res = $this->conn->query("ALTER TABLE $table ".
263 implode(",", $columnNames).")");
265 if (PEAR::isError($res)) {
266 throw new Exception($res->getMessage());
273 * Drops a named index from a table.
275 * @param string $table name of the table the index is on.
276 * @param string $name name of the index
278 * @return boolean success flag
281 public function dropIndex($table, $name)
283 $res = $this->conn->query("ALTER TABLE $table DROP INDEX $name");
285 if (PEAR::isError($res)) {
286 throw new Exception($res->getMessage());
293 * Adds a column to a table
295 * @param string $table name of the table
296 * @param ColumnDef $columndef Definition of the new
299 * @return boolean success flag
302 public function addColumn($table, $columndef)
304 $sql = "ALTER TABLE $table ADD COLUMN " . $this->_columnSql($columndef);
306 $res = $this->conn->query($sql);
308 if (PEAR::isError($res)) {
309 throw new Exception($res->getMessage());
316 * Modifies a column in the schema.
318 * The name must match an existing column and table.
320 * @param string $table name of the table
321 * @param ColumnDef $columndef new definition of the column.
323 * @return boolean success flag
326 public function modifyColumn($table, $columndef)
328 $sql = "ALTER TABLE $table MODIFY COLUMN " .
329 $this->_columnSql($columndef);
331 $res = $this->conn->query($sql);
333 if (PEAR::isError($res)) {
334 throw new Exception($res->getMessage());
341 * Drops a column from a table
343 * The name must match an existing column.
345 * @param string $table name of the table
346 * @param string $columnName name of the column to drop
348 * @return boolean success flag
351 public function dropColumn($table, $columnName)
353 $sql = "ALTER TABLE $table DROP COLUMN $columnName";
355 $res = $this->conn->query($sql);
357 if (PEAR::isError($res)) {
358 throw new Exception($res->getMessage());
365 * Ensures that a table exists with the given
366 * name and the given column definitions.
368 * If the table does not yet exist, it will
369 * create the table. If it does exist, it will
370 * alter the table to match the column definitions.
372 * @param string $tableName name of the table
373 * @param array $columns array of ColumnDef
374 * objects for the table
376 * @return boolean success flag
379 public function ensureTable($tableName, $columns)
381 // XXX: DB engine portability -> toilet
384 $td = $this->getTableDef($tableName);
386 } catch (Exception $e) {
387 if (preg_match('/no such table/', $e->getMessage())) {
388 return $this->createTable($tableName, $columns);
394 $cur = $this->_names($td->columns);
395 $new = $this->_names($columns);
397 $toadd = array_diff($new, $cur);
398 $todrop = array_diff($cur, $new);
399 $same = array_intersect($new, $cur);
402 foreach ($same as $m) {
403 $curCol = $this->_byName($td->columns, $m);
404 $newCol = $this->_byName($columns, $m);
406 if (!$newCol->equals($curCol)) {
407 $tomod[] = $newCol->name;
411 if (count($toadd) + count($todrop) + count($tomod) == 0) {
416 // For efficiency, we want this all in one
417 // query, instead of using our methods.
421 foreach ($toadd as $columnName) {
422 $cd = $this->_byName($columns, $columnName);
424 $phrase[] = 'ADD COLUMN ' . $this->_columnSql($cd);
427 foreach ($todrop as $columnName) {
428 $phrase[] = 'DROP COLUMN ' . $columnName;
431 foreach ($tomod as $columnName) {
432 $cd = $this->_byName($columns, $columnName);
434 $phrase[] = 'MODIFY COLUMN ' . $this->_columnSql($cd);
437 $sql = 'ALTER TABLE ' . $tableName . ' ' . implode(', ', $phrase);
439 $res = $this->conn->query($sql);
441 if (PEAR::isError($res)) {
442 throw new Exception($res->getMessage());
449 * Returns the array of names from an array of
452 * @param array $cds array of ColumnDef objects
454 * @return array strings for name values
457 private function _names($cds)
461 foreach ($cds as $cd) {
462 $names[] = $cd->name;
469 * Get a ColumnDef from an array matching
472 * @param array $cds Array of ColumnDef objects
473 * @param string $name Name of the column
475 * @return ColumnDef matching item or null if no match.
478 private function _byName($cds, $name)
480 foreach ($cds as $cd) {
481 if ($cd->name == $name) {
490 * Return the proper SQL for creating or
493 * Appropriate for use in CREATE TABLE or
494 * ALTER TABLE statements.
496 * @param ColumnDef $cd column to create
498 * @return string correct SQL for that column
501 private function _columnSql($cd)
503 $sql = "{$cd->name} ";
504 $type = $this->_columnTypeTranslation($cd->type);
506 if (!empty($cd->size)) {
507 $sql .= "{$type}({$cd->size}) ";
512 if (!empty($cd->default)) {
513 $sql .= "default {$cd->default} ";
515 $sql .= ($cd->nullable) ? "null " : "not null ";
518 if (!empty($cd->auto_increment)) {
519 $sql .= " auto_increment ";
522 if (!empty($cd->extra)) {
523 $sql .= "{$cd->extra} ";