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