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 * @author Brenda Wallace <shiny@cpan.org>
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)) {
83 $cd = new ColumnDef();
85 $cd->name = $row['field'];
87 $packed = $row['type'];
89 if (preg_match('/^(\w+)\((\d+)\)$/', $packed, $match)) {
90 $cd->type = $match[1];
91 $cd->size = $match[2];
96 $cd->nullable = ($row['null'] == 'YES') ? true : false;
97 $cd->key = $row['Key'];
98 $cd->default = $row['default'];
99 $cd->extra = $row['Extra'];
101 $td->columns[] = $cd;
107 * Gets a ColumnDef object for a single column.
109 * Throws an exception if the table is not found.
111 * @param string $table name of the table
112 * @param string $column name of the column
114 * @return ColumnDef definition of the column or null
118 public function getColumnDef($table, $column)
120 $td = $this->getTableDef($table);
122 foreach ($td->columns as $cd) {
123 if ($cd->name == $column) {
132 * Creates a table with the given names and columns.
134 * @param string $name Name of the table
135 * @param array $columns Array of ColumnDef objects
138 * @return boolean success flag
141 public function createTable($name, $columns)
147 $sql = "CREATE TABLE $name (\n";
149 for ($i = 0; $i < count($columns); $i++) {
157 $sql .= $this->_columnSql($cd);
160 $uniques[] = $cd->name;
163 $primary[] = $cd->name;
166 $indices[] = $cd->name;
171 if (count($primary) > 0) { // it really should be...
172 $sql .= ",\n primary key (" . implode(',', $primary) . ")";
178 foreach ($uniques as $u) {
179 $sql .= "\n CREATE index {$name}_{$u}_idx ON {$name} ($u); ";
182 foreach ($indices as $i) {
183 $sql .= "CREATE index {$name}_{$i}_idx on {$name} ($i)";
185 $res = $this->conn->query($sql);
187 if (PEAR::isError($res)) {
188 throw new Exception($res->getMessage(). ' SQL was '. $sql);
195 * Drops a table from the schema
197 * Throws an exception if the table is not found.
199 * @param string $name Name of the table to drop
201 * @return boolean success flag
204 public function dropTable($name)
206 $res = $this->conn->query("DROP TABLE $name");
208 if (PEAR::isError($res)) {
209 throw new Exception($res->getMessage());
216 * Translate the (mostly) mysql-ish column types into somethings more standard
217 * @param string column type
219 * @return string postgres happy column type
221 private function _columnTypeTranslation($type) {
223 'datetime' => 'timestamp',
225 if(!empty($map[$type])) {
232 * Adds an index to a table.
234 * If no name is provided, a name will be made up based
235 * on the table name and column names.
237 * Throws an exception on database error, esp. if the table
240 * @param string $table Name of the table
241 * @param array $columnNames Name of columns to index
242 * @param string $name (Optional) name of the index
244 * @return boolean success flag
247 public function createIndex($table, $columnNames, $name=null)
249 if (!is_array($columnNames)) {
250 $columnNames = array($columnNames);
254 $name = "$table_".implode("_", $columnNames)."_idx";
257 $res = $this->conn->query("ALTER TABLE $table ".
259 implode(",", $columnNames).")");
261 if (PEAR::isError($res)) {
262 throw new Exception($res->getMessage());
269 * Drops a named index from a table.
271 * @param string $table name of the table the index is on.
272 * @param string $name name of the index
274 * @return boolean success flag
277 public function dropIndex($table, $name)
279 $res = $this->conn->query("ALTER TABLE $table DROP INDEX $name");
281 if (PEAR::isError($res)) {
282 throw new Exception($res->getMessage());
289 * Adds a column to a table
291 * @param string $table name of the table
292 * @param ColumnDef $columndef Definition of the new
295 * @return boolean success flag
298 public function addColumn($table, $columndef)
300 $sql = "ALTER TABLE $table ADD COLUMN " . $this->_columnSql($columndef);
302 $res = $this->conn->query($sql);
304 if (PEAR::isError($res)) {
305 throw new Exception($res->getMessage());
312 * Modifies a column in the schema.
314 * The name must match an existing column and table.
316 * @param string $table name of the table
317 * @param ColumnDef $columndef new definition of the column.
319 * @return boolean success flag
322 public function modifyColumn($table, $columndef)
324 $sql = "ALTER TABLE $table MODIFY COLUMN " .
325 $this->_columnSql($columndef);
327 $res = $this->conn->query($sql);
329 if (PEAR::isError($res)) {
330 throw new Exception($res->getMessage());
337 * Drops a column from a table
339 * The name must match an existing column.
341 * @param string $table name of the table
342 * @param string $columnName name of the column to drop
344 * @return boolean success flag
347 public function dropColumn($table, $columnName)
349 $sql = "ALTER TABLE $table DROP COLUMN $columnName";
351 $res = $this->conn->query($sql);
353 if (PEAR::isError($res)) {
354 throw new Exception($res->getMessage());
361 * Ensures that a table exists with the given
362 * name and the given column definitions.
364 * If the table does not yet exist, it will
365 * create the table. If it does exist, it will
366 * alter the table to match the column definitions.
368 * @param string $tableName name of the table
369 * @param array $columns array of ColumnDef
370 * objects for the table
372 * @return boolean success flag
375 public function ensureTable($tableName, $columns)
377 // XXX: DB engine portability -> toilet
380 $td = $this->getTableDef($tableName);
382 } catch (Exception $e) {
383 if (preg_match('/no such table/', $e->getMessage())) {
384 return $this->createTable($tableName, $columns);
390 $cur = $this->_names($td->columns);
391 $new = $this->_names($columns);
393 $toadd = array_diff($new, $cur);
394 $todrop = array_diff($cur, $new);
395 $same = array_intersect($new, $cur);
397 foreach ($same as $m) {
398 $curCol = $this->_byName($td->columns, $m);
399 $newCol = $this->_byName($columns, $m);
402 if (!$newCol->equals($curCol)) {
404 // stop it detecting different types and trying to modify on every page request
405 // $tomod[] = $newCol->name;
408 if (count($toadd) + count($todrop) + count($tomod) == 0) {
413 // For efficiency, we want this all in one
414 // query, instead of using our methods.
418 foreach ($toadd as $columnName) {
419 $cd = $this->_byName($columns, $columnName);
421 $phrase[] = 'ADD COLUMN ' . $this->_columnSql($cd);
424 foreach ($todrop as $columnName) {
425 $phrase[] = 'DROP COLUMN ' . $columnName;
428 foreach ($tomod as $columnName) {
429 $cd = $this->_byName($columns, $columnName);
431 $phrase[] = 'MODIFY COLUMN ' . $this->_columnSql($cd);
434 $sql = 'ALTER TABLE ' . $tableName . ' ' . implode(', ', $phrase);
435 $res = $this->conn->query($sql);
437 if (PEAR::isError($res)) {
438 throw new Exception($res->getMessage());
445 * Returns the array of names from an array of
448 * @param array $cds array of ColumnDef objects
450 * @return array strings for name values
453 private function _names($cds)
457 foreach ($cds as $cd) {
458 $names[] = $cd->name;
465 * Get a ColumnDef from an array matching
468 * @param array $cds Array of ColumnDef objects
469 * @param string $name Name of the column
471 * @return ColumnDef matching item or null if no match.
474 private function _byName($cds, $name)
476 foreach ($cds as $cd) {
477 if ($cd->name == $name) {
486 * Return the proper SQL for creating or
489 * Appropriate for use in CREATE TABLE or
490 * ALTER TABLE statements.
492 * @param ColumnDef $cd column to create
494 * @return string correct SQL for that column
496 private function _columnSql($cd)
498 $sql = "{$cd->name} ";
499 $type = $this->_columnTypeTranslation($cd->type);
501 //handle those mysql enum fields that postgres doesn't support
502 if (preg_match('!^enum!', $type)) {
503 $allowed_values = preg_replace('!^enum!', '', $type);
504 $sql .= " text check ({$cd->name} in $allowed_values)";
507 if (!empty($cd->auto_increment)) {
511 if (!empty($cd->size)) {
512 $sql .= "{$type}({$cd->size}) ";
517 if (!empty($cd->default)) {
518 $sql .= "default {$cd->default} ";
520 $sql .= ($cd->nullable) ? "null " : "not null ";
523 if (!empty($cd->extra)) {
524 $sql .= "{$cd->extra} ";