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