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/
48 class PgsqlSchema extends Schema
52 * Returns a TableDef object for the table
53 * in the schema with the given name.
55 * Throws an exception if the table is not found.
57 * @param string $name Name of the table to get
59 * @return TableDef tabledef for that table.
62 public function getTableDef($name)
64 $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'");
66 if (PEAR::isError($res)) {
67 throw new Exception($res->getMessage());
73 $td->columns = array();
77 while ($res->fetchInto($row, DB_FETCHMODE_ASSOC)) {
79 $cd = new ColumnDef();
81 $cd->name = $row['field'];
83 $packed = $row['type'];
85 if (preg_match('/^(\w+)\((\d+)\)$/', $packed, $match)) {
86 $cd->type = $match[1];
87 $cd->size = $match[2];
92 $cd->nullable = ($row['null'] == 'YES') ? true : false;
93 $cd->key = $row['Key'];
94 $cd->default = $row['default'];
95 $cd->extra = $row['Extra'];
103 * Gets a ColumnDef object for a single column.
105 * Throws an exception if the table is not found.
107 * @param string $table name of the table
108 * @param string $column name of the column
110 * @return ColumnDef definition of the column or null
114 public function getColumnDef($table, $column)
116 $td = $this->getTableDef($table);
118 foreach ($td->columns as $cd) {
119 if ($cd->name == $column) {
128 * Creates a table with the given names and columns.
130 * @param string $name Name of the table
131 * @param array $columns Array of ColumnDef objects
134 * @return boolean success flag
137 public function createTable($name, $columns)
143 $sql = "CREATE TABLE $name (\n";
145 for ($i = 0; $i < count($columns); $i++) {
153 $sql .= $this->_columnSql($cd);
157 $uniques[] = $cd->name;
160 $primary[] = $cd->name;
163 $indices[] = $cd->name;
168 if (count($primary) > 0) { // it really should be...
169 $sql .= ",\nconstraint primary key (" . implode(',', $primary) . ")";
172 foreach ($uniques as $u) {
173 $sql .= ",\nunique index {$name}_{$u}_idx ($u)";
176 foreach ($indices as $i) {
177 $sql .= ",\nindex {$name}_{$i}_idx ($i)";
182 $res = $this->conn->query($sql);
184 if (PEAR::isError($res)) {
185 throw new Exception($res->getMessage());
192 * Drops a table from the schema
194 * Throws an exception if the table is not found.
196 * @param string $name Name of the table to drop
198 * @return boolean success flag
201 public function dropTable($name)
203 $res = $this->conn->query("DROP TABLE $name");
205 if (PEAR::isError($res)) {
206 throw new Exception($res->getMessage());
213 * Adds an index to a table.
215 * If no name is provided, a name will be made up based
216 * on the table name and column names.
218 * Throws an exception on database error, esp. if the table
221 * @param string $table Name of the table
222 * @param array $columnNames Name of columns to index
223 * @param string $name (Optional) name of the index
225 * @return boolean success flag
228 public function createIndex($table, $columnNames, $name=null)
230 if (!is_array($columnNames)) {
231 $columnNames = array($columnNames);
235 $name = "$table_".implode("_", $columnNames)."_idx";
238 $res = $this->conn->query("ALTER TABLE $table ".
240 implode(",", $columnNames).")");
242 if (PEAR::isError($res)) {
243 throw new Exception($res->getMessage());
250 * Drops a named index from a table.
252 * @param string $table name of the table the index is on.
253 * @param string $name name of the index
255 * @return boolean success flag
258 public function dropIndex($table, $name)
260 $res = $this->conn->query("ALTER TABLE $table DROP INDEX $name");
262 if (PEAR::isError($res)) {
263 throw new Exception($res->getMessage());
270 * Adds a column to a table
272 * @param string $table name of the table
273 * @param ColumnDef $columndef Definition of the new
276 * @return boolean success flag
279 public function addColumn($table, $columndef)
281 $sql = "ALTER TABLE $table ADD COLUMN " . $this->_columnSql($columndef);
283 $res = $this->conn->query($sql);
285 if (PEAR::isError($res)) {
286 throw new Exception($res->getMessage());
293 * Modifies a column in the schema.
295 * The name must match an existing column and table.
297 * @param string $table name of the table
298 * @param ColumnDef $columndef new definition of the column.
300 * @return boolean success flag
303 public function modifyColumn($table, $columndef)
305 $sql = "ALTER TABLE $table MODIFY COLUMN " .
306 $this->_columnSql($columndef);
308 $res = $this->conn->query($sql);
310 if (PEAR::isError($res)) {
311 throw new Exception($res->getMessage());
318 * Drops a column from a table
320 * The name must match an existing column.
322 * @param string $table name of the table
323 * @param string $columnName name of the column to drop
325 * @return boolean success flag
328 public function dropColumn($table, $columnName)
330 $sql = "ALTER TABLE $table DROP COLUMN $columnName";
332 $res = $this->conn->query($sql);
334 if (PEAR::isError($res)) {
335 throw new Exception($res->getMessage());
342 * Ensures that a table exists with the given
343 * name and the given column definitions.
345 * If the table does not yet exist, it will
346 * create the table. If it does exist, it will
347 * alter the table to match the column definitions.
349 * @param string $tableName name of the table
350 * @param array $columns array of ColumnDef
351 * objects for the table
353 * @return boolean success flag
356 public function ensureTable($tableName, $columns)
358 // XXX: DB engine portability -> toilet
361 $td = $this->getTableDef($tableName);
362 } catch (Exception $e) {
363 if (preg_match('/no such table/', $e->getMessage())) {
364 return $this->createTable($tableName, $columns);
370 $cur = $this->_names($td->columns);
371 $new = $this->_names($columns);
373 $toadd = array_diff($new, $cur);
374 $todrop = array_diff($cur, $new);
375 $same = array_intersect($new, $cur);
378 foreach ($same as $m) {
379 $curCol = $this->_byName($td->columns, $m);
380 $newCol = $this->_byName($columns, $m);
382 if (!$newCol->equals($curCol)) {
383 $tomod[] = $newCol->name;
387 if (count($toadd) + count($todrop) + count($tomod) == 0) {
392 // For efficiency, we want this all in one
393 // query, instead of using our methods.
397 foreach ($toadd as $columnName) {
398 $cd = $this->_byName($columns, $columnName);
400 $phrase[] = 'ADD COLUMN ' . $this->_columnSql($cd);
403 foreach ($todrop as $columnName) {
404 $phrase[] = 'DROP COLUMN ' . $columnName;
407 foreach ($tomod as $columnName) {
408 $cd = $this->_byName($columns, $columnName);
410 $phrase[] = 'MODIFY COLUMN ' . $this->_columnSql($cd);
413 $sql = 'ALTER TABLE ' . $tableName . ' ' . implode(', ', $phrase);
415 $res = $this->conn->query($sql);
417 if (PEAR::isError($res)) {
418 throw new Exception($res->getMessage());
425 * Returns the array of names from an array of
428 * @param array $cds array of ColumnDef objects
430 * @return array strings for name values
433 private function _names($cds)
437 foreach ($cds as $cd) {
438 $names[] = $cd->name;
445 * Get a ColumnDef from an array matching
448 * @param array $cds Array of ColumnDef objects
449 * @param string $name Name of the column
451 * @return ColumnDef matching item or null if no match.
454 private function _byName($cds, $name)
456 foreach ($cds as $cd) {
457 if ($cd->name == $name) {
466 * Return the proper SQL for creating or
469 * Appropriate for use in CREATE TABLE or
470 * ALTER TABLE statements.
472 * @param ColumnDef $cd column to create
474 * @return string correct SQL for that column
477 private function _columnSql($cd)
479 $sql = "{$cd->name} ";
481 if (!empty($cd->size)) {
482 $sql .= "{$cd->type}({$cd->size}) ";
484 $sql .= "{$cd->type} ";
487 if (!empty($cd->default)) {
488 $sql .= "default {$cd->default} ";
490 $sql .= ($cd->nullable) ? "null " : "not null ";
493 if (!empty($cd->auto_increment)) {
494 $sql .= " auto_increment ";
497 if (!empty($cd->extra)) {
498 $sql .= "{$cd->extra} ";