]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/pgsqlschema.php
Merge commit 'origin/master' into testing
[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  * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
45  * @link     http://status.net/
46  */
47
48 class PgsqlSchema extends Schema
49 {
50
51     /**
52      * Returns a TableDef object for the table
53      * in the schema with the given name.
54      *
55      * Throws an exception if the table is not found.
56      *
57      * @param string $name Name of the table to get
58      *
59      * @return TableDef tabledef for that table.
60      */
61
62     public function getTableDef($name)
63     {
64         $res = $this->conn->query("SELECT *, column_default as default, is_nullable as Null,
65         udt_name as Type, column_name AS Field from INFORMATION_SCHEMA.COLUMNS where table_name = '$name'");
66
67         if (PEAR::isError($res)) {
68             throw new Exception($res->getMessage());
69         }
70
71         $td = new TableDef();
72
73         $td->name    = $name;
74         $td->columns = array();
75
76         if ($res->numRows() == 0 ) {
77           throw new Exception('no such table'); //pretend to be the msyql error. yeah, this sucks.
78         }
79         $row = array();
80
81         while ($res->fetchInto($row, DB_FETCHMODE_ASSOC)) {
82 //             var_dump($row);
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
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
177
178         foreach ($indices as $i) {
179             $sql .= ",\nindex {$name}_{$i}_idx ($i)";
180         }
181
182         $sql .= "); ";
183
184
185         foreach ($uniques as $u) {
186             $sql .= "\n CREATE index {$name}_{$u}_idx ON {$name} ($u); ";
187         }
188         $res = $this->conn->query($sql);
189
190         if (PEAR::isError($res)) {
191             throw new Exception($res->getMessage());
192         }
193
194         return true;
195     }
196
197     /**
198      * Drops a table from the schema
199      *
200      * Throws an exception if the table is not found.
201      *
202      * @param string $name Name of the table to drop
203      *
204      * @return boolean success flag
205      */
206
207     public function dropTable($name)
208     {
209         $res = $this->conn->query("DROP TABLE $name");
210
211         if (PEAR::isError($res)) {
212             throw new Exception($res->getMessage());
213         }
214
215         return true;
216     }
217
218     /**
219      * Translate the (mostly) mysql-ish column types into somethings more standard
220      * @param string column type
221      *
222      * @return string postgres happy column type
223      */
224     private function _columnTypeTranslation($type) {
225       $map = array(
226       'datetime' => 'timestamp'
227       );
228       if(!empty($map[$type])) {
229         return $map[$type];
230       }
231       return $type;
232     }
233
234     /**
235      * Adds an index to a table.
236      *
237      * If no name is provided, a name will be made up based
238      * on the table name and column names.
239      *
240      * Throws an exception on database error, esp. if the table
241      * does not exist.
242      *
243      * @param string $table       Name of the table
244      * @param array  $columnNames Name of columns to index
245      * @param string $name        (Optional) name of the index
246      *
247      * @return boolean success flag
248      */
249
250     public function createIndex($table, $columnNames, $name=null)
251     {
252         if (!is_array($columnNames)) {
253             $columnNames = array($columnNames);
254         }
255
256         if (empty($name)) {
257             $name = "$table_".implode("_", $columnNames)."_idx";
258         }
259
260         $res = $this->conn->query("ALTER TABLE $table ".
261                                    "ADD INDEX $name (".
262                                    implode(",", $columnNames).")");
263
264         if (PEAR::isError($res)) {
265             throw new Exception($res->getMessage());
266         }
267
268         return true;
269     }
270
271     /**
272      * Drops a named index from a table.
273      *
274      * @param string $table name of the table the index is on.
275      * @param string $name  name of the index
276      *
277      * @return boolean success flag
278      */
279
280     public function dropIndex($table, $name)
281     {
282         $res = $this->conn->query("ALTER TABLE $table DROP INDEX $name");
283
284         if (PEAR::isError($res)) {
285             throw new Exception($res->getMessage());
286         }
287
288         return true;
289     }
290
291     /**
292      * Adds a column to a table
293      *
294      * @param string    $table     name of the table
295      * @param ColumnDef $columndef Definition of the new
296      *                             column.
297      *
298      * @return boolean success flag
299      */
300
301     public function addColumn($table, $columndef)
302     {
303         $sql = "ALTER TABLE $table ADD COLUMN " . $this->_columnSql($columndef);
304
305         $res = $this->conn->query($sql);
306
307         if (PEAR::isError($res)) {
308             throw new Exception($res->getMessage());
309         }
310
311         return true;
312     }
313
314     /**
315      * Modifies a column in the schema.
316      *
317      * The name must match an existing column and table.
318      *
319      * @param string    $table     name of the table
320      * @param ColumnDef $columndef new definition of the column.
321      *
322      * @return boolean success flag
323      */
324
325     public function modifyColumn($table, $columndef)
326     {
327         $sql = "ALTER TABLE $table MODIFY COLUMN " .
328           $this->_columnSql($columndef);
329
330         $res = $this->conn->query($sql);
331
332         if (PEAR::isError($res)) {
333             throw new Exception($res->getMessage());
334         }
335
336         return true;
337     }
338
339     /**
340      * Drops a column from a table
341      *
342      * The name must match an existing column.
343      *
344      * @param string $table      name of the table
345      * @param string $columnName name of the column to drop
346      *
347      * @return boolean success flag
348      */
349
350     public function dropColumn($table, $columnName)
351     {
352         $sql = "ALTER TABLE $table DROP COLUMN $columnName";
353
354         $res = $this->conn->query($sql);
355
356         if (PEAR::isError($res)) {
357             throw new Exception($res->getMessage());
358         }
359
360         return true;
361     }
362
363     /**
364      * Ensures that a table exists with the given
365      * name and the given column definitions.
366      *
367      * If the table does not yet exist, it will
368      * create the table. If it does exist, it will
369      * alter the table to match the column definitions.
370      *
371      * @param string $tableName name of the table
372      * @param array  $columns   array of ColumnDef
373      *                          objects for the table
374      *
375      * @return boolean success flag
376      */
377
378     public function ensureTable($tableName, $columns)
379     {
380         // XXX: DB engine portability -> toilet
381
382         try {
383             $td = $this->getTableDef($tableName);
384             
385         } catch (Exception $e) {
386             if (preg_match('/no such table/', $e->getMessage())) {
387                 return $this->createTable($tableName, $columns);
388             } else {
389                 throw $e;
390             }
391         }
392
393         $cur = $this->_names($td->columns);
394         $new = $this->_names($columns);
395
396         $toadd  = array_diff($new, $cur);
397         $todrop = array_diff($cur, $new);
398         $same   = array_intersect($new, $cur);
399         $tomod  = array();
400
401         foreach ($same as $m) {
402             $curCol = $this->_byName($td->columns, $m);
403             $newCol = $this->_byName($columns, $m);
404
405             if (!$newCol->equals($curCol)) {
406                 $tomod[] = $newCol->name;
407             }
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
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
500     private function _columnSql($cd)
501     {
502         $sql = "{$cd->name} ";
503         $type = $this->_columnTypeTranslation($cd->type);
504
505         if (!empty($cd->size)) {
506             $sql .= "{$type}({$cd->size}) ";
507         } else {
508             $sql .= "{$type} ";
509         }
510
511         if (!empty($cd->default)) {
512             $sql .= "default {$cd->default} ";
513         } else {
514             $sql .= ($cd->nullable) ? "null " : "not null ";
515         }
516         
517         if (!empty($cd->auto_increment)) {
518             $sql .= " auto_increment ";
519         }
520
521         if (!empty($cd->extra)) {
522             $sql .= "{$cd->extra} ";
523         }
524
525         return $sql;
526     }
527 }