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('DESCRIBE ' . $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'];
104 * Gets a ColumnDef object for a single column.
106 * Throws an exception if the table is not found.
108 * @param string $table name of the table
109 * @param string $column name of the column
111 * @return ColumnDef definition of the column or null
115 public function getColumnDef($table, $column)
117 $td = $this->getTableDef($table);
119 foreach ($td->columns as $cd) {
120 if ($cd->name == $column) {
129 * Creates a table with the given names and columns.
131 * @param string $name Name of the table
132 * @param array $columns Array of ColumnDef objects
135 * @return boolean success flag
138 public function createTable($name, $columns)
144 $sql = "CREATE TABLE $name (\n";
146 for ($i = 0; $i < count($columns); $i++) {
154 $sql .= $this->_columnSql($cd);
158 $uniques[] = $cd->name;
161 $primary[] = $cd->name;
164 $indices[] = $cd->name;
169 if (count($primary) > 0) { // it really should be...
170 $sql .= ",\nconstraint primary key (" . implode(',', $primary) . ")";
173 foreach ($uniques as $u) {
174 $sql .= ",\nunique index {$name}_{$u}_idx ($u)";
177 foreach ($indices as $i) {
178 $sql .= ",\nindex {$name}_{$i}_idx ($i)";
183 $res = $this->conn->query($sql);
185 if (PEAR::isError($res)) {
186 throw new Exception($res->getMessage());
193 * Drops a table from the schema
195 * Throws an exception if the table is not found.
197 * @param string $name Name of the table to drop
199 * @return boolean success flag
202 public function dropTable($name)
204 $res = $this->conn->query("DROP TABLE $name");
206 if (PEAR::isError($res)) {
207 throw new Exception($res->getMessage());
214 * Adds an index to a table.
216 * If no name is provided, a name will be made up based
217 * on the table name and column names.
219 * Throws an exception on database error, esp. if the table
222 * @param string $table Name of the table
223 * @param array $columnNames Name of columns to index
224 * @param string $name (Optional) name of the index
226 * @return boolean success flag
229 public function createIndex($table, $columnNames, $name=null)
231 if (!is_array($columnNames)) {
232 $columnNames = array($columnNames);
236 $name = "$table_".implode("_", $columnNames)."_idx";
239 $res = $this->conn->query("ALTER TABLE $table ".
241 implode(",", $columnNames).")");
243 if (PEAR::isError($res)) {
244 throw new Exception($res->getMessage());
251 * Drops a named index from a table.
253 * @param string $table name of the table the index is on.
254 * @param string $name name of the index
256 * @return boolean success flag
259 public function dropIndex($table, $name)
261 $res = $this->conn->query("ALTER TABLE $table DROP INDEX $name");
263 if (PEAR::isError($res)) {
264 throw new Exception($res->getMessage());
271 * Adds a column to a table
273 * @param string $table name of the table
274 * @param ColumnDef $columndef Definition of the new
277 * @return boolean success flag
280 public function addColumn($table, $columndef)
282 $sql = "ALTER TABLE $table ADD COLUMN " . $this->_columnSql($columndef);
284 $res = $this->conn->query($sql);
286 if (PEAR::isError($res)) {
287 throw new Exception($res->getMessage());
294 * Modifies a column in the schema.
296 * The name must match an existing column and table.
298 * @param string $table name of the table
299 * @param ColumnDef $columndef new definition of the column.
301 * @return boolean success flag
304 public function modifyColumn($table, $columndef)
306 $sql = "ALTER TABLE $table MODIFY COLUMN " .
307 $this->_columnSql($columndef);
309 $res = $this->conn->query($sql);
311 if (PEAR::isError($res)) {
312 throw new Exception($res->getMessage());
319 * Drops a column from a table
321 * The name must match an existing column.
323 * @param string $table name of the table
324 * @param string $columnName name of the column to drop
326 * @return boolean success flag
329 public function dropColumn($table, $columnName)
331 $sql = "ALTER TABLE $table DROP COLUMN $columnName";
333 $res = $this->conn->query($sql);
335 if (PEAR::isError($res)) {
336 throw new Exception($res->getMessage());
343 * Ensures that a table exists with the given
344 * name and the given column definitions.
346 * If the table does not yet exist, it will
347 * create the table. If it does exist, it will
348 * alter the table to match the column definitions.
350 * @param string $tableName name of the table
351 * @param array $columns array of ColumnDef
352 * objects for the table
354 * @return boolean success flag
357 public function ensureTable($tableName, $columns)
359 // XXX: DB engine portability -> toilet
362 $td = $this->getTableDef($tableName);
363 } catch (Exception $e) {
364 if (preg_match('/no such table/', $e->getMessage())) {
365 return $this->createTable($tableName, $columns);
371 $cur = $this->_names($td->columns);
372 $new = $this->_names($columns);
374 $toadd = array_diff($new, $cur);
375 $todrop = array_diff($cur, $new);
376 $same = array_intersect($new, $cur);
379 foreach ($same as $m) {
380 $curCol = $this->_byName($td->columns, $m);
381 $newCol = $this->_byName($columns, $m);
383 if (!$newCol->equals($curCol)) {
384 $tomod[] = $newCol->name;
388 if (count($toadd) + count($todrop) + count($tomod) == 0) {
393 // For efficiency, we want this all in one
394 // query, instead of using our methods.
398 foreach ($toadd as $columnName) {
399 $cd = $this->_byName($columns, $columnName);
401 $phrase[] = 'ADD COLUMN ' . $this->_columnSql($cd);
404 foreach ($todrop as $columnName) {
405 $phrase[] = 'DROP COLUMN ' . $columnName;
408 foreach ($tomod as $columnName) {
409 $cd = $this->_byName($columns, $columnName);
411 $phrase[] = 'MODIFY COLUMN ' . $this->_columnSql($cd);
414 $sql = 'ALTER TABLE ' . $tableName . ' ' . implode(', ', $phrase);
416 $res = $this->conn->query($sql);
418 if (PEAR::isError($res)) {
419 throw new Exception($res->getMessage());
426 * Returns the array of names from an array of
429 * @param array $cds array of ColumnDef objects
431 * @return array strings for name values
434 private function _names($cds)
438 foreach ($cds as $cd) {
439 $names[] = $cd->name;
446 * Get a ColumnDef from an array matching
449 * @param array $cds Array of ColumnDef objects
450 * @param string $name Name of the column
452 * @return ColumnDef matching item or null if no match.
455 private function _byName($cds, $name)
457 foreach ($cds as $cd) {
458 if ($cd->name == $name) {
467 * Return the proper SQL for creating or
470 * Appropriate for use in CREATE TABLE or
471 * ALTER TABLE statements.
473 * @param ColumnDef $cd column to create
475 * @return string correct SQL for that column
478 private function _columnSql($cd)
480 $sql = "{$cd->name} ";
482 if (!empty($cd->size)) {
483 $sql .= "{$cd->type}({$cd->size}) ";
485 $sql .= "{$cd->type} ";
488 if (!empty($cd->default)) {
489 $sql .= "default {$cd->default} ";
491 $sql .= ($cd->nullable) ? "null " : "not null ";
494 if (!empty($cd->auto_increment)) {
495 $sql .= " auto_increment ";
498 if (!empty($cd->extra)) {
499 $sql .= "{$cd->extra} ";