]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/schema.php
Merge commit 'mainline/0.9.x' into 0.9.x
[quix0rs-gnu-social.git] / lib / schema.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 Schema
49 {
50     static $_single = null;
51     protected $conn = null;
52
53     /**
54      * Constructor. Only run once for singleton object.
55      */
56
57     protected function __construct()
58     {
59         // XXX: there should be an easier way to do this.
60         $user = new User();
61
62         $this->conn = $user->getDatabaseConnection();
63
64         $user->free();
65
66         unset($user);
67     }
68
69     /**
70      * Main public entry point. Use this to get
71      * the singleton object.
72      *
73      * @return Schema the (single) Schema object
74      */
75
76     static function get()
77     {
78         if (empty(self::$_single)) {
79             self::$_single = new Schema();
80         }
81         return self::$_single;
82     }
83
84     /**
85      * Returns a TableDef object for the table
86      * in the schema with the given name.
87      *
88      * Throws an exception if the table is not found.
89      *
90      * @param string $name Name of the table to get
91      *
92      * @return TableDef tabledef for that table.
93      */
94
95     public function getTableDef($name)
96     {
97         if(common_config('db','type') == 'pgsql') {
98             $res = $this->conn->query("select column_default as default, is_nullable as Null, udt_name as Type, column_name AS Field from INFORMATION_SCHEMA.COLUMNS where table_name = '$name'");
99         }
100         else { 
101             $res = $this->conn->query('DESCRIBE ' . $name);
102         }
103
104         if (PEAR::isError($res)) {
105             throw new Exception($res->getMessage());
106         }
107
108         $td = new TableDef();
109
110         $td->name    = $name;
111         $td->columns = array();
112
113         $row = array();
114
115         while ($res->fetchInto($row, DB_FETCHMODE_ASSOC)) {
116             //lower case the keys, because the php postgres driver is case insentive for column names
117             foreach($row as $k=>$v) {
118                $row[strtolower($k)] = $row[$k];
119             }
120
121             $cd = new ColumnDef();
122
123             $cd->name = $row['field'];
124
125             $packed = $row['type'];
126
127             if (preg_match('/^(\w+)\((\d+)\)$/', $packed, $match)) {
128                 $cd->type = $match[1];
129                 $cd->size = $match[2];
130             } else {
131                 $cd->type = $packed;
132             }
133
134             $cd->nullable = ($row['null'] == 'YES') ? true : false;
135             $cd->key      = $row['Key'];
136             $cd->default  = $row['default'];
137             $cd->extra    = $row['Extra'];
138
139             $td->columns[] = $cd;
140         }
141
142         return $td;
143     }
144
145     /**
146      * Gets a ColumnDef object for a single column.
147      *
148      * Throws an exception if the table is not found.
149      *
150      * @param string $table  name of the table
151      * @param string $column name of the column
152      *
153      * @return ColumnDef definition of the column or null
154      *                   if not found.
155      */
156
157     public function getColumnDef($table, $column)
158     {
159         $td = $this->getTableDef($table);
160
161         foreach ($td->columns as $cd) {
162             if ($cd->name == $column) {
163                 return $cd;
164             }
165         }
166
167         return null;
168     }
169
170     /**
171      * Creates a table with the given names and columns.
172      *
173      * @param string $name    Name of the table
174      * @param array  $columns Array of ColumnDef objects
175      *                        for new table.
176      *
177      * @return boolean success flag
178      */
179
180     public function createTable($name, $columns)
181     {
182         $uniques = array();
183         $primary = array();
184         $indices = array();
185
186         $sql = "CREATE TABLE $name (\n";
187
188         for ($i = 0; $i < count($columns); $i++) {
189
190             $cd =& $columns[$i];
191
192             if ($i > 0) {
193                 $sql .= ",\n";
194             }
195
196             $sql .= $this->_columnSql($cd);
197
198             switch ($cd->key) {
199             case 'UNI':
200                 $uniques[] = $cd->name;
201                 break;
202             case 'PRI':
203                 $primary[] = $cd->name;
204                 break;
205             case 'MUL':
206                 $indices[] = $cd->name;
207                 break;
208             }
209         }
210
211         if (count($primary) > 0) { // it really should be...
212             $sql .= ",\nconstraint primary key (" . implode(',', $primary) . ")";
213         }
214
215         foreach ($uniques as $u) {
216             $sql .= ",\nunique index {$name}_{$u}_idx ($u)";
217         }
218
219         foreach ($indices as $i) {
220             $sql .= ",\nindex {$name}_{$i}_idx ($i)";
221         }
222
223         $sql .= "); ";
224
225         $res = $this->conn->query($sql);
226
227         if (PEAR::isError($res)) {
228             throw new Exception($res->getMessage());
229         }
230
231         return true;
232     }
233
234     /**
235      * Drops a table from the schema
236      *
237      * Throws an exception if the table is not found.
238      *
239      * @param string $name Name of the table to drop
240      *
241      * @return boolean success flag
242      */
243
244     public function dropTable($name)
245     {
246         $res = $this->conn->query("DROP TABLE $name");
247
248         if (PEAR::isError($res)) {
249             throw new Exception($res->getMessage());
250         }
251
252         return true;
253     }
254
255     /**
256      * Adds an index to a table.
257      *
258      * If no name is provided, a name will be made up based
259      * on the table name and column names.
260      *
261      * Throws an exception on database error, esp. if the table
262      * does not exist.
263      *
264      * @param string $table       Name of the table
265      * @param array  $columnNames Name of columns to index
266      * @param string $name        (Optional) name of the index
267      *
268      * @return boolean success flag
269      */
270
271     public function createIndex($table, $columnNames, $name=null)
272     {
273         if (!is_array($columnNames)) {
274             $columnNames = array($columnNames);
275         }
276
277         if (empty($name)) {
278             $name = "$table_".implode("_", $columnNames)."_idx";
279         }
280
281         $res = $this->conn->query("ALTER TABLE $table ".
282                                    "ADD INDEX $name (".
283                                    implode(",", $columnNames).")");
284
285         if (PEAR::isError($res)) {
286             throw new Exception($res->getMessage());
287         }
288
289         return true;
290     }
291
292     /**
293      * Drops a named index from a table.
294      *
295      * @param string $table name of the table the index is on.
296      * @param string $name  name of the index
297      *
298      * @return boolean success flag
299      */
300
301     public function dropIndex($table, $name)
302     {
303         $res = $this->conn->query("ALTER TABLE $table DROP INDEX $name");
304
305         if (PEAR::isError($res)) {
306             throw new Exception($res->getMessage());
307         }
308
309         return true;
310     }
311
312     /**
313      * Adds a column to a table
314      *
315      * @param string    $table     name of the table
316      * @param ColumnDef $columndef Definition of the new
317      *                             column.
318      *
319      * @return boolean success flag
320      */
321
322     public function addColumn($table, $columndef)
323     {
324         $sql = "ALTER TABLE $table ADD COLUMN " . $this->_columnSql($columndef);
325
326         $res = $this->conn->query($sql);
327
328         if (PEAR::isError($res)) {
329             throw new Exception($res->getMessage());
330         }
331
332         return true;
333     }
334
335     /**
336      * Modifies a column in the schema.
337      *
338      * The name must match an existing column and table.
339      *
340      * @param string    $table     name of the table
341      * @param ColumnDef $columndef new definition of the column.
342      *
343      * @return boolean success flag
344      */
345
346     public function modifyColumn($table, $columndef)
347     {
348         $sql = "ALTER TABLE $table MODIFY COLUMN " .
349           $this->_columnSql($columndef);
350
351         $res = $this->conn->query($sql);
352
353         if (PEAR::isError($res)) {
354             throw new Exception($res->getMessage());
355         }
356
357         return true;
358     }
359
360     /**
361      * Drops a column from a table
362      *
363      * The name must match an existing column.
364      *
365      * @param string $table      name of the table
366      * @param string $columnName name of the column to drop
367      *
368      * @return boolean success flag
369      */
370
371     public function dropColumn($table, $columnName)
372     {
373         $sql = "ALTER TABLE $table DROP COLUMN $columnName";
374
375         $res = $this->conn->query($sql);
376
377         if (PEAR::isError($res)) {
378             throw new Exception($res->getMessage());
379         }
380
381         return true;
382     }
383
384     /**
385      * Ensures that a table exists with the given
386      * name and the given column definitions.
387      *
388      * If the table does not yet exist, it will
389      * create the table. If it does exist, it will
390      * alter the table to match the column definitions.
391      *
392      * @param string $tableName name of the table
393      * @param array  $columns   array of ColumnDef
394      *                          objects for the table
395      *
396      * @return boolean success flag
397      */
398
399     public function ensureTable($tableName, $columns)
400     {
401         // XXX: DB engine portability -> toilet
402
403         try {
404             $td = $this->getTableDef($tableName);
405         } catch (Exception $e) {
406             if (preg_match('/no such table/', $e->getMessage())) {
407                 return $this->createTable($tableName, $columns);
408             } else {
409                 throw $e;
410             }
411         }
412
413         $cur = $this->_names($td->columns);
414         $new = $this->_names($columns);
415
416         $toadd  = array_diff($new, $cur);
417         $todrop = array_diff($cur, $new);
418         $same   = array_intersect($new, $cur);
419         $tomod  = array();
420
421         foreach ($same as $m) {
422             $curCol = $this->_byName($td->columns, $m);
423             $newCol = $this->_byName($columns, $m);
424
425             if (!$newCol->equals($curCol)) {
426                 $tomod[] = $newCol->name;
427             }
428         }
429
430         if (count($toadd) + count($todrop) + count($tomod) == 0) {
431             // nothing to do
432             return true;
433         }
434
435         // For efficiency, we want this all in one
436         // query, instead of using our methods.
437
438         $phrase = array();
439
440         foreach ($toadd as $columnName) {
441             $cd = $this->_byName($columns, $columnName);
442
443             $phrase[] = 'ADD COLUMN ' . $this->_columnSql($cd);
444         }
445
446         foreach ($todrop as $columnName) {
447             $phrase[] = 'DROP COLUMN ' . $columnName;
448         }
449
450         foreach ($tomod as $columnName) {
451             $cd = $this->_byName($columns, $columnName);
452
453             $phrase[] = 'MODIFY COLUMN ' . $this->_columnSql($cd);
454         }
455
456         $sql = 'ALTER TABLE ' . $tableName . ' ' . implode(', ', $phrase);
457
458         $res = $this->conn->query($sql);
459
460         if (PEAR::isError($res)) {
461             throw new Exception($res->getMessage());
462         }
463
464         return true;
465     }
466
467     /**
468      * Returns the array of names from an array of
469      * ColumnDef objects.
470      *
471      * @param array $cds array of ColumnDef objects
472      *
473      * @return array strings for name values
474      */
475
476     private function _names($cds)
477     {
478         $names = array();
479
480         foreach ($cds as $cd) {
481             $names[] = $cd->name;
482         }
483
484         return $names;
485     }
486
487     /**
488      * Get a ColumnDef from an array matching
489      * name.
490      *
491      * @param array  $cds  Array of ColumnDef objects
492      * @param string $name Name of the column
493      *
494      * @return ColumnDef matching item or null if no match.
495      */
496
497     private function _byName($cds, $name)
498     {
499         foreach ($cds as $cd) {
500             if ($cd->name == $name) {
501                 return $cd;
502             }
503         }
504
505         return null;
506     }
507
508     /**
509      * Return the proper SQL for creating or
510      * altering a column.
511      *
512      * Appropriate for use in CREATE TABLE or
513      * ALTER TABLE statements.
514      *
515      * @param ColumnDef $cd column to create
516      *
517      * @return string correct SQL for that column
518      */
519
520     private function _columnSql($cd)
521     {
522         $sql = "{$cd->name} ";
523
524         if (!empty($cd->size)) {
525             $sql .= "{$cd->type}({$cd->size}) ";
526         } else {
527             $sql .= "{$cd->type} ";
528         }
529
530         if (!empty($cd->default)) {
531             $sql .= "default {$cd->default} ";
532         } else {
533             $sql .= ($cd->nullable) ? "null " : "not null ";
534         }
535         
536         if (!empty($cd->auto_increment)) {
537             $sql .= " auto_increment ";
538         }
539
540         if (!empty($cd->extra)) {
541             $sql .= "{$cd->extra} ";
542         }
543
544         return $sql;
545     }
546 }