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