]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/pgsqlschema.php
Merge branch '1.0.x' into schema-x
[quix0rs-gnu-social.git] / lib / pgsqlschema.php
1 <?php
2 /**
3  * StatusNet, the distributed open-source microblogging tool
4  *
5  * Database schema utilities
6  *
7  * PHP version 5
8  *
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.
13  *
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.
18  *
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/>.
21  *
22  * @category  Database
23  * @package   StatusNet
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/
28  */
29
30 if (!defined('STATUSNET')) {
31     exit(1);
32 }
33
34 /**
35  * Class representing the database schema
36  *
37  * A class representing the database schema. Can be used to
38  * manipulate the schema -- especially for plugins and upgrade
39  * utilities.
40  *
41  * @category Database
42  * @package  StatusNet
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/
47  */
48
49 class PgsqlSchema extends Schema
50 {
51
52     /**
53      * Returns a TableDef object for the table
54      * in the schema with the given name.
55      *
56      * Throws an exception if the table is not found.
57      *
58      * @param string $name Name of the table to get
59      *
60      * @return TableDef tabledef for that table.
61      */
62
63     public function getTableDef($name)
64     {
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'");
67
68         if (PEAR::isError($res)) {
69             throw new Exception($res->getMessage());
70         }
71
72         $td = new TableDef();
73
74         $td->name    = $name;
75         $td->columns = array();
76
77         if ($res->numRows() == 0 ) {
78           throw new Exception('no such table'); //pretend to be the msyql error. yeah, this sucks.
79         }
80         $row = array();
81
82         while ($res->fetchInto($row, DB_FETCHMODE_ASSOC)) {
83             $cd = new ColumnDef();
84
85             $cd->name = $row['field'];
86
87             $packed = $row['type'];
88
89             if (preg_match('/^(\w+)\((\d+)\)$/', $packed, $match)) {
90                 $cd->type = $match[1];
91                 $cd->size = $match[2];
92             } else {
93                 $cd->type = $packed;
94             }
95
96             $cd->nullable = ($row['null'] == 'YES') ? true : false;
97             $cd->key      = $row['Key'];
98             $cd->default  = $row['default'];
99             $cd->extra    = $row['Extra'];
100
101             $td->columns[] = $cd;
102         }
103         return $td;
104     }
105
106     /**
107      * Creates a table with the given names and columns.
108      *
109      * @param string $name    Name of the table
110      * @param array  $columns Array of ColumnDef objects
111      *                        for new table.
112      *
113      * @return boolean success flag
114      */
115
116     public function createTable($name, $columns)
117     {
118         $uniques = array();
119         $primary = array();
120         $indices = array();
121         $onupdate = array();
122
123         $sql = "CREATE TABLE $name (\n";
124
125         for ($i = 0; $i < count($columns); $i++) {
126
127             $cd =& $columns[$i];
128
129             if ($i > 0) {
130                 $sql .= ",\n";
131             }
132
133             $sql .= $this->_columnSql($cd);
134             switch ($cd->key) {
135             case 'UNI':
136                 $uniques[] = $cd->name;
137                 break;
138             case 'PRI':
139                 $primary[] = $cd->name;
140                 break;
141             case 'MUL':
142                 $indices[] = $cd->name;
143                 break;
144             }
145         }
146
147         if (count($primary) > 0) { // it really should be...
148             $sql .= ",\n PRIMARY KEY (" . implode(',', $primary) . ")";
149         }
150
151         $sql .= "); ";
152
153
154         foreach ($uniques as $u) {
155             $sql .= "\n CREATE index {$name}_{$u}_idx ON {$name} ($u); ";
156         }
157
158         foreach ($indices as $i) {
159             $sql .= "CREATE index {$name}_{$i}_idx ON {$name} ($i)";
160         }
161         $res = $this->conn->query($sql);
162
163         if (PEAR::isError($res)) {
164             throw new Exception($res->getMessage(). ' SQL was '. $sql);
165         }
166
167         return true;
168     }
169
170     /**
171      * Translate the (mostly) mysql-ish column types into somethings more standard
172      * @param string column type
173      *
174      * @return string postgres happy column type
175      */
176     private function _columnTypeTranslation($type) {
177       $map = array(
178       'datetime' => 'timestamp',
179       );
180       if(!empty($map[$type])) {
181         return $map[$type];
182       }
183       return $type;
184     }
185
186     /**
187      * Modifies a column in the schema.
188      *
189      * The name must match an existing column and table.
190      *
191      * @param string    $table     name of the table
192      * @param ColumnDef $columndef new definition of the column.
193      *
194      * @return boolean success flag
195      */
196
197     public function modifyColumn($table, $columndef)
198     {
199         $sql = "ALTER TABLE $table ALTER COLUMN TYPE " .
200           $this->_columnSql($columndef);
201
202         $res = $this->conn->query($sql);
203
204         if (PEAR::isError($res)) {
205             throw new Exception($res->getMessage());
206         }
207
208         return true;
209     }
210
211
212     /**
213      * Ensures that a table exists with the given
214      * name and the given column definitions.
215      *
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.
219      *
220      * @param string $tableName name of the table
221      * @param array  $columns   array of ColumnDef
222      *                          objects for the table
223      *
224      * @return boolean success flag
225      */
226
227     public function ensureTable($tableName, $columns)
228     {
229         // XXX: DB engine portability -> toilet
230
231         try {
232             $td = $this->getTableDef($tableName);
233             
234         } catch (Exception $e) {
235             if (preg_match('/no such table/', $e->getMessage())) {
236                 return $this->createTable($tableName, $columns);
237             } else {
238                 throw $e;
239             }
240         }
241
242         $cur = $this->_names($td->columns);
243         $new = $this->_names($columns);
244
245         $toadd  = array_diff($new, $cur);
246         $todrop = array_diff($cur, $new);
247         $same   = array_intersect($new, $cur);
248         $tomod  = array();
249         foreach ($same as $m) {
250             $curCol = $this->_byName($td->columns, $m);
251             $newCol = $this->_byName($columns, $m);
252             
253
254             if (!$newCol->equals($curCol)) {
255             // BIG GIANT TODO!
256             // stop it detecting different types and trying to modify on every page request
257 //                 $tomod[] = $newCol->name;
258             }
259         }
260         if (count($toadd) + count($todrop) + count($tomod) == 0) {
261             // nothing to do
262             return true;
263         }
264
265         // For efficiency, we want this all in one
266         // query, instead of using our methods.
267
268         $phrase = array();
269
270         foreach ($toadd as $columnName) {
271             $cd = $this->_byName($columns, $columnName);
272
273             $phrase[] = 'ADD COLUMN ' . $this->_columnSql($cd);
274         }
275
276         foreach ($todrop as $columnName) {
277             $phrase[] = 'DROP COLUMN ' . $columnName;
278         }
279
280         foreach ($tomod as $columnName) {
281             $cd = $this->_byName($columns, $columnName);
282
283         /* brute force */
284             $phrase[] = 'DROP COLUMN ' . $columnName;
285             $phrase[] = 'ADD COLUMN ' . $this->_columnSql($cd);
286         }
287
288         $sql = 'ALTER TABLE ' . $tableName . ' ' . implode(', ', $phrase);
289         $res = $this->conn->query($sql);
290
291         if (PEAR::isError($res)) {
292             throw new Exception($res->getMessage());
293         }
294
295         return true;
296     }
297
298     /**
299      * Return the proper SQL for creating or
300      * altering a column.
301      *
302      * Appropriate for use in CREATE TABLE or
303      * ALTER TABLE statements.
304      *
305      * @param string $tableName
306      * @param array $tableDef
307      * @param string $columnName
308      * @param array $cd column to create
309      *
310      * @return string correct SQL for that column
311      */
312
313     function columnSql($name, array $cd)
314     {
315         $line = array();
316         $line[] = parent::_columnSql($cd);
317
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) . ')';
323             }
324         }
325
326         return implode(' ', $line);
327     }
328
329     function mapType($column)
330     {
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',
334                      'blob' => 'bytea');
335
336         $type = $column['type'];
337         if (isset($map[$type])) {
338             $type = $map[$type];
339         }
340
341         if (!empty($column['size'])) {
342             $size = $column['size'];
343             if ($type == 'integer' &&
344                        in_array($size, array('small', 'big'))) {
345                 $type = $size . 'int';
346             }
347         }
348
349         return $type;
350     }
351
352     // @fixme need name... :P
353     function typeAndSize($column)
354     {
355         if ($column['type'] == 'enum') {
356             $vals = array_map(array($this, 'quote'), $column['enum']);
357             return "text check ($name in " . implode(',', $vals) . ')';
358         } else {
359             return parent::typeAndSize($column);
360         }
361     }
362
363 }