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