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