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 * Adds an index to a table.
222 * If no name is provided, a name will be made up based
223 * on the table name and column names.
225 * Throws an exception on database error, esp. if the table
228 * @param string $table Name of the table
229 * @param array $columnNames Name of columns to index
230 * @param string $name (Optional) name of the index
232 * @return boolean success flag
235 public function createIndex($table, $columnNames, $name=null)
237 if (!is_array($columnNames)) {
238 $columnNames = array($columnNames);
242 $name = "$table_".implode("_", $columnNames)."_idx";
245 $res = $this->conn->query("ALTER TABLE $table ".
247 implode(",", $columnNames).")");
249 if (PEAR::isError($res)) {
250 throw new Exception($res->getMessage());
257 * Drops a named index from a table.
259 * @param string $table name of the table the index is on.
260 * @param string $name name of the index
262 * @return boolean success flag
265 public function dropIndex($table, $name)
267 $res = $this->conn->query("ALTER TABLE $table DROP INDEX $name");
269 if (PEAR::isError($res)) {
270 throw new Exception($res->getMessage());
277 * Adds a column to a table
279 * @param string $table name of the table
280 * @param ColumnDef $columndef Definition of the new
283 * @return boolean success flag
286 public function addColumn($table, $columndef)
288 $sql = "ALTER TABLE $table ADD COLUMN " . $this->_columnSql($columndef);
290 $res = $this->conn->query($sql);
292 if (PEAR::isError($res)) {
293 throw new Exception($res->getMessage());
300 * Modifies a column in the schema.
302 * The name must match an existing column and table.
304 * @param string $table name of the table
305 * @param ColumnDef $columndef new definition of the column.
307 * @return boolean success flag
310 public function modifyColumn($table, $columndef)
312 $sql = "ALTER TABLE $table MODIFY COLUMN " .
313 $this->_columnSql($columndef);
315 $res = $this->conn->query($sql);
317 if (PEAR::isError($res)) {
318 throw new Exception($res->getMessage());
325 * Drops a column from a table
327 * The name must match an existing column.
329 * @param string $table name of the table
330 * @param string $columnName name of the column to drop
332 * @return boolean success flag
335 public function dropColumn($table, $columnName)
337 $sql = "ALTER TABLE $table DROP COLUMN $columnName";
339 $res = $this->conn->query($sql);
341 if (PEAR::isError($res)) {
342 throw new Exception($res->getMessage());
349 * Ensures that a table exists with the given
350 * name and the given column definitions.
352 * If the table does not yet exist, it will
353 * create the table. If it does exist, it will
354 * alter the table to match the column definitions.
356 * @param string $tableName name of the table
357 * @param array $columns array of ColumnDef
358 * objects for the table
360 * @return boolean success flag
363 public function ensureTable($tableName, $columns)
365 // XXX: DB engine portability -> toilet
368 $td = $this->getTableDef($tableName);
370 } catch (Exception $e) {
371 if (preg_match('/no such table/', $e->getMessage())) {
372 return $this->createTable($tableName, $columns);
378 $cur = $this->_names($td->columns);
379 $new = $this->_names($columns);
381 $toadd = array_diff($new, $cur);
382 $todrop = array_diff($cur, $new);
383 $same = array_intersect($new, $cur);
386 foreach ($same as $m) {
387 $curCol = $this->_byName($td->columns, $m);
388 $newCol = $this->_byName($columns, $m);
390 if (!$newCol->equals($curCol)) {
391 $tomod[] = $newCol->name;
395 if (count($toadd) + count($todrop) + count($tomod) == 0) {
400 // For efficiency, we want this all in one
401 // query, instead of using our methods.
405 foreach ($toadd as $columnName) {
406 $cd = $this->_byName($columns, $columnName);
408 $phrase[] = 'ADD COLUMN ' . $this->_columnSql($cd);
411 foreach ($todrop as $columnName) {
412 $phrase[] = 'DROP COLUMN ' . $columnName;
415 foreach ($tomod as $columnName) {
416 $cd = $this->_byName($columns, $columnName);
418 $phrase[] = 'MODIFY COLUMN ' . $this->_columnSql($cd);
421 $sql = 'ALTER TABLE ' . $tableName . ' ' . implode(', ', $phrase);
423 $res = $this->conn->query($sql);
425 if (PEAR::isError($res)) {
426 throw new Exception($res->getMessage());
433 * Returns the array of names from an array of
436 * @param array $cds array of ColumnDef objects
438 * @return array strings for name values
441 private function _names($cds)
445 foreach ($cds as $cd) {
446 $names[] = $cd->name;
453 * Get a ColumnDef from an array matching
456 * @param array $cds Array of ColumnDef objects
457 * @param string $name Name of the column
459 * @return ColumnDef matching item or null if no match.
462 private function _byName($cds, $name)
464 foreach ($cds as $cd) {
465 if ($cd->name == $name) {
474 * Return the proper SQL for creating or
477 * Appropriate for use in CREATE TABLE or
478 * ALTER TABLE statements.
480 * @param ColumnDef $cd column to create
482 * @return string correct SQL for that column
485 private function _columnSql($cd)
487 $sql = "{$cd->name} ";
489 if (!empty($cd->size)) {
490 $sql .= "{$cd->type}({$cd->size}) ";
492 $sql .= "{$cd->type} ";
495 if (!empty($cd->default)) {
496 $sql .= "default {$cd->default} ";
498 $sql .= ($cd->nullable) ? "null " : "not null ";
501 if (!empty($cd->auto_increment)) {
502 $sql .= " auto_increment ";
505 if (!empty($cd->extra)) {
506 $sql .= "{$cd->extra} ";