]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/pgsqlschema.php
Merge branch 'testing' of git@gitorious.org:statusnet/mainline into 0.9.x
[quix0rs-gnu-social.git] / lib / pgsqlschema.php
1
2 <?php
3 /**
4  * StatusNet, the distributed open-source microblogging tool
5  *
6  * Database schema utilities
7  *
8  * PHP version 5
9  *
10  * LICENCE: This program is free software: you can redistribute it and/or modify
11  * it under the terms of the GNU Affero General Public License as published by
12  * the Free Software Foundation, either version 3 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU Affero General Public License for more details.
19  *
20  * You should have received a copy of the GNU Affero General Public License
21  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
22  *
23  * @category  Database
24  * @package   StatusNet
25  * @author    Evan Prodromou <evan@status.net>
26  * @copyright 2009 StatusNet, Inc.
27  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
28  * @link      http://status.net/
29  */
30
31 if (!defined('STATUSNET')) {
32     exit(1);
33 }
34
35 /**
36  * Class representing the database schema
37  *
38  * A class representing the database schema. Can be used to
39  * manipulate the schema -- especially for plugins and upgrade
40  * utilities.
41  *
42  * @category Database
43  * @package  StatusNet
44  * @author   Evan Prodromou <evan@status.net>
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 //             var_dump($row);
84             $cd = new ColumnDef();
85
86             $cd->name = $row['field'];
87
88             $packed = $row['type'];
89
90             if (preg_match('/^(\w+)\((\d+)\)$/', $packed, $match)) {
91                 $cd->type = $match[1];
92                 $cd->size = $match[2];
93             } else {
94                 $cd->type = $packed;
95             }
96
97             $cd->nullable = ($row['null'] == 'YES') ? true : false;
98             $cd->key      = $row['Key'];
99             $cd->default  = $row['default'];
100             $cd->extra    = $row['Extra'];
101
102             $td->columns[] = $cd;
103         }
104         return $td;
105     }
106
107     /**
108      * Gets a ColumnDef object for a single column.
109      *
110      * Throws an exception if the table is not found.
111      *
112      * @param string $table  name of the table
113      * @param string $column name of the column
114      *
115      * @return ColumnDef definition of the column or null
116      *                   if not found.
117      */
118
119     public function getColumnDef($table, $column)
120     {
121         $td = $this->getTableDef($table);
122
123         foreach ($td->columns as $cd) {
124             if ($cd->name == $column) {
125                 return $cd;
126             }
127         }
128
129         return null;
130     }
131
132     /**
133      * Creates a table with the given names and columns.
134      *
135      * @param string $name    Name of the table
136      * @param array  $columns Array of ColumnDef objects
137      *                        for new table.
138      *
139      * @return boolean success flag
140      */
141
142     public function createTable($name, $columns)
143     {
144         $uniques = array();
145         $primary = array();
146         $indices = 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
160             switch ($cd->key) {
161             case 'UNI':
162                 $uniques[] = $cd->name;
163                 break;
164             case 'PRI':
165                 $primary[] = $cd->name;
166                 break;
167             case 'MUL':
168                 $indices[] = $cd->name;
169                 break;
170             }
171         }
172
173         if (count($primary) > 0) { // it really should be...
174             $sql .= ",\n primary key (" . implode(',', $primary) . ")";
175         }
176
177
178
179         foreach ($indices as $i) {
180             $sql .= ",\nindex {$name}_{$i}_idx ($i)";
181         }
182
183         $sql .= "); ";
184
185
186         foreach ($uniques as $u) {
187             $sql .= "\n CREATE index {$name}_{$u}_idx ON {$name} ($u); ";
188         }
189         $res = $this->conn->query($sql);
190
191         if (PEAR::isError($res)) {
192             throw new Exception($res->getMessage());
193         }
194
195         return true;
196     }
197
198     /**
199      * Drops a table from the schema
200      *
201      * Throws an exception if the table is not found.
202      *
203      * @param string $name Name of the table to drop
204      *
205      * @return boolean success flag
206      */
207
208     public function dropTable($name)
209     {
210         $res = $this->conn->query("DROP TABLE $name");
211
212         if (PEAR::isError($res)) {
213             throw new Exception($res->getMessage());
214         }
215
216         return true;
217     }
218
219     /**
220      * Translate the (mostly) mysql-ish column types into somethings more standard
221      * @param string column type
222      *
223      * @return string postgres happy column type
224      */
225     private function _columnTypeTranslation($type) {
226       $map = array(
227       'datetime' => 'timestamp'
228       );
229       if(!empty($map[$type])) {
230         return $map[$type];
231       }
232       return $type;
233     }
234
235     /**
236      * Adds an index to a table.
237      *
238      * If no name is provided, a name will be made up based
239      * on the table name and column names.
240      *
241      * Throws an exception on database error, esp. if the table
242      * does not exist.
243      *
244      * @param string $table       Name of the table
245      * @param array  $columnNames Name of columns to index
246      * @param string $name        (Optional) name of the index
247      *
248      * @return boolean success flag
249      */
250
251     public function createIndex($table, $columnNames, $name=null)
252     {
253         if (!is_array($columnNames)) {
254             $columnNames = array($columnNames);
255         }
256
257         if (empty($name)) {
258             $name = "$table_".implode("_", $columnNames)."_idx";
259         }
260
261         $res = $this->conn->query("ALTER TABLE $table ".
262                                    "ADD INDEX $name (".
263                                    implode(",", $columnNames).")");
264
265         if (PEAR::isError($res)) {
266             throw new Exception($res->getMessage());
267         }
268
269         return true;
270     }
271
272     /**
273      * Drops a named index from a table.
274      *
275      * @param string $table name of the table the index is on.
276      * @param string $name  name of the index
277      *
278      * @return boolean success flag
279      */
280
281     public function dropIndex($table, $name)
282     {
283         $res = $this->conn->query("ALTER TABLE $table DROP INDEX $name");
284
285         if (PEAR::isError($res)) {
286             throw new Exception($res->getMessage());
287         }
288
289         return true;
290     }
291
292     /**
293      * Adds a column to a table
294      *
295      * @param string    $table     name of the table
296      * @param ColumnDef $columndef Definition of the new
297      *                             column.
298      *
299      * @return boolean success flag
300      */
301
302     public function addColumn($table, $columndef)
303     {
304         $sql = "ALTER TABLE $table ADD COLUMN " . $this->_columnSql($columndef);
305
306         $res = $this->conn->query($sql);
307
308         if (PEAR::isError($res)) {
309             throw new Exception($res->getMessage());
310         }
311
312         return true;
313     }
314
315     /**
316      * Modifies a column in the schema.
317      *
318      * The name must match an existing column and table.
319      *
320      * @param string    $table     name of the table
321      * @param ColumnDef $columndef new definition of the column.
322      *
323      * @return boolean success flag
324      */
325
326     public function modifyColumn($table, $columndef)
327     {
328         $sql = "ALTER TABLE $table MODIFY COLUMN " .
329           $this->_columnSql($columndef);
330
331         $res = $this->conn->query($sql);
332
333         if (PEAR::isError($res)) {
334             throw new Exception($res->getMessage());
335         }
336
337         return true;
338     }
339
340     /**
341      * Drops a column from a table
342      *
343      * The name must match an existing column.
344      *
345      * @param string $table      name of the table
346      * @param string $columnName name of the column to drop
347      *
348      * @return boolean success flag
349      */
350
351     public function dropColumn($table, $columnName)
352     {
353         $sql = "ALTER TABLE $table DROP COLUMN $columnName";
354
355         $res = $this->conn->query($sql);
356
357         if (PEAR::isError($res)) {
358             throw new Exception($res->getMessage());
359         }
360
361         return true;
362     }
363
364     /**
365      * Ensures that a table exists with the given
366      * name and the given column definitions.
367      *
368      * If the table does not yet exist, it will
369      * create the table. If it does exist, it will
370      * alter the table to match the column definitions.
371      *
372      * @param string $tableName name of the table
373      * @param array  $columns   array of ColumnDef
374      *                          objects for the table
375      *
376      * @return boolean success flag
377      */
378
379     public function ensureTable($tableName, $columns)
380     {
381         // XXX: DB engine portability -> toilet
382
383         try {
384             $td = $this->getTableDef($tableName);
385             
386         } catch (Exception $e) {
387             if (preg_match('/no such table/', $e->getMessage())) {
388                 return $this->createTable($tableName, $columns);
389             } else {
390                 throw $e;
391             }
392         }
393
394         $cur = $this->_names($td->columns);
395         $new = $this->_names($columns);
396
397         $toadd  = array_diff($new, $cur);
398         $todrop = array_diff($cur, $new);
399         $same   = array_intersect($new, $cur);
400         $tomod  = array();
401
402         foreach ($same as $m) {
403             $curCol = $this->_byName($td->columns, $m);
404             $newCol = $this->_byName($columns, $m);
405
406             if (!$newCol->equals($curCol)) {
407                 $tomod[] = $newCol->name;
408             }
409         }
410
411         if (count($toadd) + count($todrop) + count($tomod) == 0) {
412             // nothing to do
413             return true;
414         }
415
416         // For efficiency, we want this all in one
417         // query, instead of using our methods.
418
419         $phrase = array();
420
421         foreach ($toadd as $columnName) {
422             $cd = $this->_byName($columns, $columnName);
423
424             $phrase[] = 'ADD COLUMN ' . $this->_columnSql($cd);
425         }
426
427         foreach ($todrop as $columnName) {
428             $phrase[] = 'DROP COLUMN ' . $columnName;
429         }
430
431         foreach ($tomod as $columnName) {
432             $cd = $this->_byName($columns, $columnName);
433
434             $phrase[] = 'MODIFY COLUMN ' . $this->_columnSql($cd);
435         }
436
437         $sql = 'ALTER TABLE ' . $tableName . ' ' . implode(', ', $phrase);
438
439         $res = $this->conn->query($sql);
440
441         if (PEAR::isError($res)) {
442             throw new Exception($res->getMessage());
443         }
444
445         return true;
446     }
447
448     /**
449      * Returns the array of names from an array of
450      * ColumnDef objects.
451      *
452      * @param array $cds array of ColumnDef objects
453      *
454      * @return array strings for name values
455      */
456
457     private function _names($cds)
458     {
459         $names = array();
460
461         foreach ($cds as $cd) {
462             $names[] = $cd->name;
463         }
464
465         return $names;
466     }
467
468     /**
469      * Get a ColumnDef from an array matching
470      * name.
471      *
472      * @param array  $cds  Array of ColumnDef objects
473      * @param string $name Name of the column
474      *
475      * @return ColumnDef matching item or null if no match.
476      */
477
478     private function _byName($cds, $name)
479     {
480         foreach ($cds as $cd) {
481             if ($cd->name == $name) {
482                 return $cd;
483             }
484         }
485
486         return null;
487     }
488
489     /**
490      * Return the proper SQL for creating or
491      * altering a column.
492      *
493      * Appropriate for use in CREATE TABLE or
494      * ALTER TABLE statements.
495      *
496      * @param ColumnDef $cd column to create
497      *
498      * @return string correct SQL for that column
499      */
500
501     private function _columnSql($cd)
502     {
503         $sql = "{$cd->name} ";
504         $type = $this->_columnTypeTranslation($cd->type);
505
506         if (!empty($cd->size)) {
507             $sql .= "{$type}({$cd->size}) ";
508         } else {
509             $sql .= "{$type} ";
510         }
511
512         if (!empty($cd->default)) {
513             $sql .= "default {$cd->default} ";
514         } else {
515             $sql .= ($cd->nullable) ? "null " : "not null ";
516         }
517         
518         if (!empty($cd->auto_increment)) {
519             $sql .= " auto_increment ";
520         }
521
522         if (!empty($cd->extra)) {
523             $sql .= "{$cd->extra} ";
524         }
525
526         return $sql;
527     }
528 }