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 * Creates a table with the given names and columns.
109 * @param string $name Name of the table
110 * @param array $columns Array of ColumnDef objects
113 * @return boolean success flag
116 public function createTable($name, $columns)
123 $sql = "CREATE TABLE $name (\n";
125 for ($i = 0; $i < count($columns); $i++) {
133 $sql .= $this->_columnSql($cd);
136 $uniques[] = $cd->name;
139 $primary[] = $cd->name;
142 $indices[] = $cd->name;
147 if (count($primary) > 0) { // it really should be...
148 $sql .= ",\n PRIMARY KEY (" . implode(',', $primary) . ")";
154 foreach ($uniques as $u) {
155 $sql .= "\n CREATE index {$name}_{$u}_idx ON {$name} ($u); ";
158 foreach ($indices as $i) {
159 $sql .= "CREATE index {$name}_{$i}_idx ON {$name} ($i)";
161 $res = $this->conn->query($sql);
163 if (PEAR::isError($res)) {
164 throw new Exception($res->getMessage(). ' SQL was '. $sql);
171 * Translate the (mostly) mysql-ish column types into somethings more standard
172 * @param string column type
174 * @return string postgres happy column type
176 private function _columnTypeTranslation($type) {
178 'datetime' => 'timestamp',
180 if(!empty($map[$type])) {
187 * Modifies a column in the schema.
189 * The name must match an existing column and table.
191 * @param string $table name of the table
192 * @param ColumnDef $columndef new definition of the column.
194 * @return boolean success flag
197 public function modifyColumn($table, $columndef)
199 $sql = "ALTER TABLE $table ALTER COLUMN TYPE " .
200 $this->_columnSql($columndef);
202 $res = $this->conn->query($sql);
204 if (PEAR::isError($res)) {
205 throw new Exception($res->getMessage());
213 * Ensures that a table exists with the given
214 * name and the given column definitions.
216 * If the table does not yet exist, it will
217 * create the table. If it does exist, it will
218 * alter the table to match the column definitions.
220 * @param string $tableName name of the table
221 * @param array $columns array of ColumnDef
222 * objects for the table
224 * @return boolean success flag
227 public function ensureTable($tableName, $columns)
229 // XXX: DB engine portability -> toilet
232 $td = $this->getTableDef($tableName);
234 } catch (Exception $e) {
235 if (preg_match('/no such table/', $e->getMessage())) {
236 return $this->createTable($tableName, $columns);
242 $cur = $this->_names($td->columns);
243 $new = $this->_names($columns);
245 $toadd = array_diff($new, $cur);
246 $todrop = array_diff($cur, $new);
247 $same = array_intersect($new, $cur);
249 foreach ($same as $m) {
250 $curCol = $this->_byName($td->columns, $m);
251 $newCol = $this->_byName($columns, $m);
254 if (!$newCol->equals($curCol)) {
256 // stop it detecting different types and trying to modify on every page request
257 // $tomod[] = $newCol->name;
260 if (count($toadd) + count($todrop) + count($tomod) == 0) {
265 // For efficiency, we want this all in one
266 // query, instead of using our methods.
270 foreach ($toadd as $columnName) {
271 $cd = $this->_byName($columns, $columnName);
273 $phrase[] = 'ADD COLUMN ' . $this->_columnSql($cd);
276 foreach ($todrop as $columnName) {
277 $phrase[] = 'DROP COLUMN ' . $columnName;
280 foreach ($tomod as $columnName) {
281 $cd = $this->_byName($columns, $columnName);
284 $phrase[] = 'DROP COLUMN ' . $columnName;
285 $phrase[] = 'ADD COLUMN ' . $this->_columnSql($cd);
288 $sql = 'ALTER TABLE ' . $tableName . ' ' . implode(', ', $phrase);
289 $res = $this->conn->query($sql);
291 if (PEAR::isError($res)) {
292 throw new Exception($res->getMessage());
299 * Return the proper SQL for creating or
302 * Appropriate for use in CREATE TABLE or
303 * ALTER TABLE statements.
305 * @param string $tableName
306 * @param array $tableDef
307 * @param string $columnName
308 * @param array $cd column to create
310 * @return string correct SQL for that column
313 function columnSql($name, array $cd)
316 $line[] = parent::_columnSql($cd);
318 if ($table['foreign keys'][$name]) {
319 foreach ($table['foreign keys'][$name] as $foreignTable => $foreignColumn) {
320 $line[] = 'references';
321 $line[] = $this->quoteId($foreignTable);
322 $line[] = '(' . $this->quoteId($foreignColumn) . ')';
326 return implode(' ', $line);
329 function mapType($column)
331 $map = array('serial' => 'bigserial', // FIXME: creates the wrong name for the sequence for some internal sequence-lookup function, so better fix this to do the real 'create sequence' dance.
332 'numeric' => 'decimal',
333 'datetime' => 'timestamp',
336 $type = $column['type'];
337 if (isset($map[$type])) {
341 if (!empty($column['size'])) {
342 $size = $column['size'];
343 if ($type == 'integer' &&
344 in_array($size, array('small', 'big'))) {
345 $type = $size . 'int';
352 // @fixme need name... :P
353 function typeAndSize($column)
355 if ($column['type'] == 'enum') {
356 $vals = array_map(array($this, 'quote'), $column['enum']);
357 return "text check ($name in " . implode(',', $vals) . ')';
359 return parent::typeAndSize($column);