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