]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/mysqlschema.php
Merge branch 'testing' of git@gitorious.org:statusnet/mainline into 0.9.x
[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         common_log(LOG_INFO, $sql);
217         $res = $this->conn->query($sql);
218
219         if (PEAR::isError($res)) {
220             throw new Exception($res->getMessage());
221         }
222
223         return true;
224     }
225
226     /**
227      * Drops a table from the schema
228      *
229      * Throws an exception if the table is not found.
230      *
231      * @param string $name Name of the table to drop
232      *
233      * @return boolean success flag
234      */
235
236     public function dropTable($name)
237     {
238         $res = $this->conn->query("DROP TABLE $name");
239
240         if (PEAR::isError($res)) {
241             throw new Exception($res->getMessage());
242         }
243
244         return true;
245     }
246
247     /**
248      * Adds an index to a table.
249      *
250      * If no name is provided, a name will be made up based
251      * on the table name and column names.
252      *
253      * Throws an exception on database error, esp. if the table
254      * does not exist.
255      *
256      * @param string $table       Name of the table
257      * @param array  $columnNames Name of columns to index
258      * @param string $name        (Optional) name of the index
259      *
260      * @return boolean success flag
261      */
262
263     public function createIndex($table, $columnNames, $name=null)
264     {
265         if (!is_array($columnNames)) {
266             $columnNames = array($columnNames);
267         }
268
269         if (empty($name)) {
270             $name = "$table_".implode("_", $columnNames)."_idx";
271         }
272
273         $res = $this->conn->query("ALTER TABLE $table ".
274                                    "ADD INDEX $name (".
275                                    implode(",", $columnNames).")");
276
277         if (PEAR::isError($res)) {
278             throw new Exception($res->getMessage());
279         }
280
281         return true;
282     }
283
284     /**
285      * Drops a named index from a table.
286      *
287      * @param string $table name of the table the index is on.
288      * @param string $name  name of the index
289      *
290      * @return boolean success flag
291      */
292
293     public function dropIndex($table, $name)
294     {
295         $res = $this->conn->query("ALTER TABLE $table DROP INDEX $name");
296
297         if (PEAR::isError($res)) {
298             throw new Exception($res->getMessage());
299         }
300
301         return true;
302     }
303
304     /**
305      * Adds a column to a table
306      *
307      * @param string    $table     name of the table
308      * @param ColumnDef $columndef Definition of the new
309      *                             column.
310      *
311      * @return boolean success flag
312      */
313
314     public function addColumn($table, $columndef)
315     {
316         $sql = "ALTER TABLE $table ADD COLUMN " . $this->_columnSql($columndef);
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      * Modifies a column in the schema.
329      *
330      * The name must match an existing column and table.
331      *
332      * @param string    $table     name of the table
333      * @param ColumnDef $columndef new definition of the column.
334      *
335      * @return boolean success flag
336      */
337
338     public function modifyColumn($table, $columndef)
339     {
340         $sql = "ALTER TABLE $table MODIFY COLUMN " .
341           $this->_columnSql($columndef);
342
343         $res = $this->conn->query($sql);
344
345         if (PEAR::isError($res)) {
346             throw new Exception($res->getMessage());
347         }
348
349         return true;
350     }
351
352     /**
353      * Drops a column from a table
354      *
355      * The name must match an existing column.
356      *
357      * @param string $table      name of the table
358      * @param string $columnName name of the column to drop
359      *
360      * @return boolean success flag
361      */
362
363     public function dropColumn($table, $columnName)
364     {
365         $sql = "ALTER TABLE $table DROP COLUMN $columnName";
366
367         $res = $this->conn->query($sql);
368
369         if (PEAR::isError($res)) {
370             throw new Exception($res->getMessage());
371         }
372
373         return true;
374     }
375
376     /**
377      * Ensures that a table exists with the given
378      * name and the given column definitions.
379      *
380      * If the table does not yet exist, it will
381      * create the table. If it does exist, it will
382      * alter the table to match the column definitions.
383      *
384      * @param string $tableName name of the table
385      * @param array  $columns   array of ColumnDef
386      *                          objects for the table
387      *
388      * @return boolean success flag
389      */
390
391     public function ensureTable($tableName, $columns)
392     {
393         // XXX: DB engine portability -> toilet
394
395         try {
396             $td = $this->getTableDef($tableName);
397         } catch (Exception $e) {
398             if (preg_match('/no such table/', $e->getMessage())) {
399                 return $this->createTable($tableName, $columns);
400             } else {
401                 throw $e;
402             }
403         }
404
405         $cur = $this->_names($td->columns);
406         $new = $this->_names($columns);
407
408         $toadd  = array_diff($new, $cur);
409         $todrop = array_diff($cur, $new);
410         $same   = array_intersect($new, $cur);
411         $tomod  = array();
412
413         foreach ($same as $m) {
414             $curCol = $this->_byName($td->columns, $m);
415             $newCol = $this->_byName($columns, $m);
416
417             if (!$newCol->equals($curCol)) {
418                 $tomod[] = $newCol->name;
419             }
420         }
421
422         if (count($toadd) + count($todrop) + count($tomod) == 0) {
423             // nothing to do
424             return true;
425         }
426
427         // For efficiency, we want this all in one
428         // query, instead of using our methods.
429
430         $phrase = array();
431
432         foreach ($toadd as $columnName) {
433             $cd = $this->_byName($columns, $columnName);
434
435             $phrase[] = 'ADD COLUMN ' . $this->_columnSql($cd);
436         }
437
438         foreach ($todrop as $columnName) {
439             $phrase[] = 'DROP COLUMN ' . $columnName;
440         }
441
442         foreach ($tomod as $columnName) {
443             $cd = $this->_byName($columns, $columnName);
444
445             $phrase[] = 'MODIFY COLUMN ' . $this->_columnSql($cd);
446         }
447
448         $sql = 'ALTER TABLE ' . $tableName . ' ' . implode(', ', $phrase);
449
450         $res = $this->conn->query($sql);
451
452         if (PEAR::isError($res)) {
453             throw new Exception($res->getMessage());
454         }
455
456         return true;
457     }
458
459     /**
460      * Returns the array of names from an array of
461      * ColumnDef objects.
462      *
463      * @param array $cds array of ColumnDef objects
464      *
465      * @return array strings for name values
466      */
467
468     private function _names($cds)
469     {
470         $names = array();
471
472         foreach ($cds as $cd) {
473             $names[] = $cd->name;
474         }
475
476         return $names;
477     }
478
479     /**
480      * Get a ColumnDef from an array matching
481      * name.
482      *
483      * @param array  $cds  Array of ColumnDef objects
484      * @param string $name Name of the column
485      *
486      * @return ColumnDef matching item or null if no match.
487      */
488
489     private function _byName($cds, $name)
490     {
491         foreach ($cds as $cd) {
492             if ($cd->name == $name) {
493                 return $cd;
494             }
495         }
496
497         return null;
498     }
499
500     /**
501      * Return the proper SQL for creating or
502      * altering a column.
503      *
504      * Appropriate for use in CREATE TABLE or
505      * ALTER TABLE statements.
506      *
507      * @param ColumnDef $cd column to create
508      *
509      * @return string correct SQL for that column
510      */
511
512     private function _columnSql($cd)
513     {
514         $sql = "{$cd->name} ";
515
516         if (!empty($cd->size)) {
517             $sql .= "{$cd->type}({$cd->size}) ";
518         } else {
519             $sql .= "{$cd->type} ";
520         }
521
522         if (!empty($cd->default)) {
523             $sql .= "default {$cd->default} ";
524         } else {
525             $sql .= ($cd->nullable) ? "null " : "not null ";
526         }
527         
528         if (!empty($cd->auto_increment)) {
529             $sql .= " auto_increment ";
530         }
531
532         if (!empty($cd->extra)) {
533             $sql .= "{$cd->extra} ";
534         }
535
536         return $sql;
537     }
538 }