]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/pgsqlschema.php
Merge branch 'master' into 0.9.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      * Gets a ColumnDef object for a single column.
108      *
109      * Throws an exception if the table is not found.
110      *
111      * @param string $table  name of the table
112      * @param string $column name of the column
113      *
114      * @return ColumnDef definition of the column or null
115      *                   if not found.
116      */
117
118     public function getColumnDef($table, $column)
119     {
120         $td = $this->getTableDef($table);
121
122         foreach ($td->columns as $cd) {
123             if ($cd->name == $column) {
124                 return $cd;
125             }
126         }
127
128         return null;
129     }
130
131     /**
132      * Creates a table with the given names and columns.
133      *
134      * @param string $name    Name of the table
135      * @param array  $columns Array of ColumnDef objects
136      *                        for new table.
137      *
138      * @return boolean success flag
139      */
140
141     public function createTable($name, $columns)
142     {
143         $uniques = array();
144         $primary = array();
145         $indices = array();
146         $onupdate = array();
147
148         $sql = "CREATE TABLE $name (\n";
149
150         for ($i = 0; $i < count($columns); $i++) {
151
152             $cd =& $columns[$i];
153
154             if ($i > 0) {
155                 $sql .= ",\n";
156             }
157
158             $sql .= $this->_columnSql($cd);
159             switch ($cd->key) {
160             case 'UNI':
161                 $uniques[] = $cd->name;
162                 break;
163             case 'PRI':
164                 $primary[] = $cd->name;
165                 break;
166             case 'MUL':
167                 $indices[] = $cd->name;
168                 break;
169             }
170         }
171
172         if (count($primary) > 0) { // it really should be...
173             $sql .= ",\n PRIMARY KEY (" . implode(',', $primary) . ")";
174         }
175
176         $sql .= "); ";
177
178
179         foreach ($uniques as $u) {
180             $sql .= "\n CREATE index {$name}_{$u}_idx ON {$name} ($u); ";
181         }
182
183         foreach ($indices as $i) {
184             $sql .= "CREATE index {$name}_{$i}_idx ON {$name} ($i)";
185         }
186         $res = $this->conn->query($sql);
187
188         if (PEAR::isError($res)) {
189             throw new Exception($res->getMessage(). ' SQL was '. $sql);
190         }
191
192         return true;
193     }
194
195     /**
196      * Drops a table from the schema
197      *
198      * Throws an exception if the table is not found.
199      *
200      * @param string $name Name of the table to drop
201      *
202      * @return boolean success flag
203      */
204
205     public function dropTable($name)
206     {
207         $res = $this->conn->query("DROP TABLE $name");
208
209         if (PEAR::isError($res)) {
210             throw new Exception($res->getMessage());
211         }
212
213         return true;
214     }
215
216     /**
217      * Translate the (mostly) mysql-ish column types into somethings more standard
218      * @param string column type
219      *
220      * @return string postgres happy column type
221      */
222     private function _columnTypeTranslation($type) {
223       $map = array(
224       'datetime' => 'timestamp',
225       );
226       if(!empty($map[$type])) {
227         return $map[$type];
228       }
229       return $type;
230     }
231
232     /**
233      * Adds an index to a table.
234      *
235      * If no name is provided, a name will be made up based
236      * on the table name and column names.
237      *
238      * Throws an exception on database error, esp. if the table
239      * does not exist.
240      *
241      * @param string $table       Name of the table
242      * @param array  $columnNames Name of columns to index
243      * @param string $name        (Optional) name of the index
244      *
245      * @return boolean success flag
246      */
247
248     public function createIndex($table, $columnNames, $name=null)
249     {
250         if (!is_array($columnNames)) {
251             $columnNames = array($columnNames);
252         }
253
254         if (empty($name)) {
255             $name = "$table_".implode("_", $columnNames)."_idx";
256         }
257
258         $res = $this->conn->query("ALTER TABLE $table ".
259                                    "ADD INDEX $name (".
260                                    implode(",", $columnNames).")");
261
262         if (PEAR::isError($res)) {
263             throw new Exception($res->getMessage());
264         }
265
266         return true;
267     }
268
269     /**
270      * Drops a named index from a table.
271      *
272      * @param string $table name of the table the index is on.
273      * @param string $name  name of the index
274      *
275      * @return boolean success flag
276      */
277
278     public function dropIndex($table, $name)
279     {
280         $res = $this->conn->query("ALTER TABLE $table DROP INDEX $name");
281
282         if (PEAR::isError($res)) {
283             throw new Exception($res->getMessage());
284         }
285
286         return true;
287     }
288
289     /**
290      * Adds a column to a table
291      *
292      * @param string    $table     name of the table
293      * @param ColumnDef $columndef Definition of the new
294      *                             column.
295      *
296      * @return boolean success flag
297      */
298
299     public function addColumn($table, $columndef)
300     {
301         $sql = "ALTER TABLE $table ADD COLUMN " . $this->_columnSql($columndef);
302
303         $res = $this->conn->query($sql);
304
305         if (PEAR::isError($res)) {
306             throw new Exception($res->getMessage());
307         }
308
309         return true;
310     }
311
312     /**
313      * Modifies a column in the schema.
314      *
315      * The name must match an existing column and table.
316      *
317      * @param string    $table     name of the table
318      * @param ColumnDef $columndef new definition of the column.
319      *
320      * @return boolean success flag
321      */
322
323     public function modifyColumn($table, $columndef)
324     {
325         $sql = "ALTER TABLE $table ALTER COLUMN TYPE " .
326           $this->_columnSql($columndef);
327
328         $res = $this->conn->query($sql);
329
330         if (PEAR::isError($res)) {
331             throw new Exception($res->getMessage());
332         }
333
334         return true;
335     }
336
337     /**
338      * Drops a column from a table
339      *
340      * The name must match an existing column.
341      *
342      * @param string $table      name of the table
343      * @param string $columnName name of the column to drop
344      *
345      * @return boolean success flag
346      */
347
348     public function dropColumn($table, $columnName)
349     {
350         $sql = "ALTER TABLE $table DROP COLUMN $columnName";
351
352         $res = $this->conn->query($sql);
353
354         if (PEAR::isError($res)) {
355             throw new Exception($res->getMessage());
356         }
357
358         return true;
359     }
360
361     /**
362      * Ensures that a table exists with the given
363      * name and the given column definitions.
364      *
365      * If the table does not yet exist, it will
366      * create the table. If it does exist, it will
367      * alter the table to match the column definitions.
368      *
369      * @param string $tableName name of the table
370      * @param array  $columns   array of ColumnDef
371      *                          objects for the table
372      *
373      * @return boolean success flag
374      */
375
376     public function ensureTable($tableName, $columns)
377     {
378         // XXX: DB engine portability -> toilet
379
380         try {
381             $td = $this->getTableDef($tableName);
382             
383         } catch (Exception $e) {
384             if (preg_match('/no such table/', $e->getMessage())) {
385                 return $this->createTable($tableName, $columns);
386             } else {
387                 throw $e;
388             }
389         }
390
391         $cur = $this->_names($td->columns);
392         $new = $this->_names($columns);
393
394         $toadd  = array_diff($new, $cur);
395         $todrop = array_diff($cur, $new);
396         $same   = array_intersect($new, $cur);
397         $tomod  = array();
398         foreach ($same as $m) {
399             $curCol = $this->_byName($td->columns, $m);
400             $newCol = $this->_byName($columns, $m);
401             
402
403             if (!$newCol->equals($curCol)) {
404             // BIG GIANT TODO!
405             // stop it detecting different types and trying to modify on every page request
406 //                 $tomod[] = $newCol->name;
407             }
408         }
409         if (count($toadd) + count($todrop) + count($tomod) == 0) {
410             // nothing to do
411             return true;
412         }
413
414         // For efficiency, we want this all in one
415         // query, instead of using our methods.
416
417         $phrase = array();
418
419         foreach ($toadd as $columnName) {
420             $cd = $this->_byName($columns, $columnName);
421
422             $phrase[] = 'ADD COLUMN ' . $this->_columnSql($cd);
423         }
424
425         foreach ($todrop as $columnName) {
426             $phrase[] = 'DROP COLUMN ' . $columnName;
427         }
428
429         foreach ($tomod as $columnName) {
430             $cd = $this->_byName($columns, $columnName);
431
432         /* brute force */
433             $phrase[] = 'DROP COLUMN ' . $columnName;
434             $phrase[] = 'ADD COLUMN ' . $this->_columnSql($cd);
435         }
436
437         $sql = 'ALTER TABLE ' . $tableName . ' ' . implode(', ', $phrase);
438         $res = $this->conn->query($sql);
439
440         if (PEAR::isError($res)) {
441             throw new Exception($res->getMessage());
442         }
443
444         return true;
445     }
446
447     /**
448      * Returns the array of names from an array of
449      * ColumnDef objects.
450      *
451      * @param array $cds array of ColumnDef objects
452      *
453      * @return array strings for name values
454      */
455
456     private function _names($cds)
457     {
458         $names = array();
459
460         foreach ($cds as $cd) {
461             $names[] = $cd->name;
462         }
463
464         return $names;
465     }
466
467     /**
468      * Get a ColumnDef from an array matching
469      * name.
470      *
471      * @param array  $cds  Array of ColumnDef objects
472      * @param string $name Name of the column
473      *
474      * @return ColumnDef matching item or null if no match.
475      */
476
477     private function _byName($cds, $name)
478     {
479         foreach ($cds as $cd) {
480             if ($cd->name == $name) {
481                 return $cd;
482             }
483         }
484
485         return null;
486     }
487
488     /**
489      * Return the proper SQL for creating or
490      * altering a column.
491      *
492      * Appropriate for use in CREATE TABLE or
493      * ALTER TABLE statements.
494      *
495      * @param ColumnDef $cd column to create
496      *
497      * @return string correct SQL for that column
498      */
499     private function _columnSql($cd)
500     {
501         $sql = "{$cd->name} ";
502         $type = $this->_columnTypeTranslation($cd->type);
503
504         //handle those mysql enum fields that postgres doesn't support
505         if (preg_match('!^enum!', $type)) {
506           $allowed_values = preg_replace('!^enum!', '', $type);
507           $sql .= " text check ({$cd->name} in $allowed_values)";
508           return $sql;
509         }
510         if (!empty($cd->auto_increment)) {
511             $type = "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.
512         }
513
514         if (!empty($cd->size)) {
515             $sql .= "{$type}({$cd->size}) ";
516         } else {
517             $sql .= "{$type} ";
518         }
519
520         if (!empty($cd->default)) {
521             $sql .= "default {$cd->default} ";
522         } else {
523             $sql .= ($cd->nullable) ? "null " : "not null ";
524         }
525
526 //         if (!empty($cd->extra)) {
527 //             $sql .= "{$cd->extra} ";
528 //         }
529
530         return $sql;
531     }
532 }