]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/mysqlschema.php
Merge remote branch 'chat-interface-plugins/msn-plugin' into 1.0.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     /**
55      * Main public entry point. Use this to get
56      * the singleton object.
57      *
58      * @return Schema the (single) Schema object
59      */
60
61     static function get()
62     {
63         if (empty(self::$_single)) {
64             self::$_single = new Schema();
65         }
66         return self::$_single;
67     }
68
69     /**
70      * Returns a TableDef object for the table
71      * in the schema with the given name.
72      *
73      * Throws an exception if the table is not found.
74      *
75      * @param string $name Name of the table to get
76      *
77      * @return TableDef tabledef for that table.
78      * @throws SchemaTableMissingException
79      */
80
81     public function getTableDef($name)
82     {
83         $query = "SELECT * FROM INFORMATION_SCHEMA.COLUMNS " .
84                  "WHERE TABLE_SCHEMA='%s' AND TABLE_NAME='%s'";
85         $schema = $this->conn->dsn['database'];
86         $sql = sprintf($query, $schema, $name);
87         $res = $this->conn->query($sql);
88
89         if (PEAR::isError($res)) {
90             throw new Exception($res->getMessage());
91         }
92         if ($res->numRows() == 0) {
93             $res->free();
94             throw new SchemaTableMissingException("No such table: $name");
95         }
96
97         $td = new TableDef();
98
99         $td->name    = $name;
100         $td->columns = array();
101
102         $row = array();
103
104         while ($res->fetchInto($row, DB_FETCHMODE_ASSOC)) {
105
106             $cd = new ColumnDef();
107
108             $cd->name = $row['COLUMN_NAME'];
109
110             $packed = $row['COLUMN_TYPE'];
111
112             if (preg_match('/^(\w+)\((\d+)\)$/', $packed, $match)) {
113                 $cd->type = $match[1];
114                 $cd->size = $match[2];
115             } else {
116                 $cd->type = $packed;
117             }
118
119             $cd->nullable = ($row['IS_NULLABLE'] == 'YES') ? true : false;
120             $cd->key      = $row['COLUMN_KEY'];
121             $cd->default  = $row['COLUMN_DEFAULT'];
122             $cd->extra    = $row['EXTRA'];
123
124             // Autoincrement is stuck into the extra column.
125             // Pull it out so we don't accidentally mod it every time...
126             $extra = preg_replace('/(^|\s)auto_increment(\s|$)/i', '$1$2', $cd->extra);
127             if ($extra != $cd->extra) {
128                 $cd->extra = trim($extra);
129                 $cd->auto_increment = true;
130             }
131
132             // mysql extensions -- not (yet) used by base class
133             $cd->charset  = $row['CHARACTER_SET_NAME'];
134             $cd->collate  = $row['COLLATION_NAME'];
135
136             $td->columns[] = $cd;
137         }
138         $res->free();
139
140         return $td;
141     }
142
143     /**
144      * Pull the given table properties from INFORMATION_SCHEMA.
145      * Most of the good stuff is MySQL extensions.
146      *
147      * @return array
148      * @throws Exception if table info can't be looked up
149      */
150
151     function getTableProperties($table, $props)
152     {
153         $query = "SELECT %s FROM INFORMATION_SCHEMA.TABLES " .
154                  "WHERE TABLE_SCHEMA='%s' AND TABLE_NAME='%s'";
155         $schema = $this->conn->dsn['database'];
156         $sql = sprintf($query, implode(',', $props), $schema, $table);
157         $res = $this->conn->query($sql);
158
159         $row = array();
160         $ok = $res->fetchInto($row, DB_FETCHMODE_ASSOC);
161         $res->free();
162         
163         if ($ok) {
164             return $row;
165         } else {
166             throw new SchemaTableMissingException("No such table: $table");
167         }
168     }
169
170     /**
171      * Gets a ColumnDef object for a single column.
172      *
173      * Throws an exception if the table is not found.
174      *
175      * @param string $table  name of the table
176      * @param string $column name of the column
177      *
178      * @return ColumnDef definition of the column or null
179      *                   if not found.
180      */
181
182     public function getColumnDef($table, $column)
183     {
184         $td = $this->getTableDef($table);
185
186         foreach ($td->columns as $cd) {
187             if ($cd->name == $column) {
188                 return $cd;
189             }
190         }
191
192         return null;
193     }
194
195     /**
196      * Creates a table with the given names and columns.
197      *
198      * @param string $name    Name of the table
199      * @param array  $columns Array of ColumnDef objects
200      *                        for new table.
201      *
202      * @return boolean success flag
203      */
204
205     public function createTable($name, $columns)
206     {
207         $uniques = array();
208         $primary = array();
209         $indices = array();
210
211         $sql = "CREATE TABLE $name (\n";
212
213         for ($i = 0; $i < count($columns); $i++) {
214
215             $cd =& $columns[$i];
216
217             if ($i > 0) {
218                 $sql .= ",\n";
219             }
220
221             $sql .= $this->_columnSql($cd);
222         }
223
224         $idx = $this->_indexList($columns);
225
226         if ($idx['primary']) {
227             $sql .= ",\nconstraint primary key (" . implode(',', $idx['primary']) . ")";
228         }
229
230         foreach ($idx['uniques'] as $u) {
231             $key = $this->_uniqueKey($name, $u);
232             $sql .= ",\nunique index $key ($u)";
233         }
234
235         foreach ($idx['indices'] as $i) {
236             $key = $this->_key($name, $i);
237             $sql .= ",\nindex $key ($i)";
238         }
239
240         $sql .= ") ENGINE=InnoDB CHARACTER SET utf8 COLLATE utf8_bin; ";
241
242         $res = $this->conn->query($sql);
243
244         if (PEAR::isError($res)) {
245             throw new Exception($res->getMessage());
246         }
247
248         return true;
249     }
250
251     /**
252      * Look over a list of column definitions and list up which
253      * indices will be present
254      */
255     private function _indexList(array $columns)
256     {
257         $list = array('uniques' => array(),
258                       'primary' => array(),
259                       'indices' => array());
260         foreach ($columns as $cd) {
261             switch ($cd->key) {
262             case 'UNI':
263                 $list['uniques'][] = $cd->name;
264                 break;
265             case 'PRI':
266                 $list['primary'][] = $cd->name;
267                 break;
268             case 'MUL':
269                 $list['indices'][] = $cd->name;
270                 break;
271             }
272         }
273         return $list;
274     }
275
276     /**
277      * Get the unique index key name for a given column on this table
278      */
279     function _uniqueKey($tableName, $columnName)
280     {
281         return $this->_key($tableName, $columnName);
282     }
283
284     /**
285      * Get the index key name for a given column on this table
286      */
287     function _key($tableName, $columnName)
288     {
289         return "{$tableName}_{$columnName}_idx";
290     }
291
292     /**
293      * Drops a table from the schema
294      *
295      * Throws an exception if the table is not found.
296      *
297      * @param string $name Name of the table to drop
298      *
299      * @return boolean success flag
300      */
301
302     public function dropTable($name)
303     {
304         $res = $this->conn->query("DROP TABLE $name");
305
306         if (PEAR::isError($res)) {
307             throw new Exception($res->getMessage());
308         }
309
310         return true;
311     }
312
313     /**
314      * Adds an index to a table.
315      *
316      * If no name is provided, a name will be made up based
317      * on the table name and column names.
318      *
319      * Throws an exception on database error, esp. if the table
320      * does not exist.
321      *
322      * @param string $table       Name of the table
323      * @param array  $columnNames Name of columns to index
324      * @param string $name        (Optional) name of the index
325      *
326      * @return boolean success flag
327      */
328
329     public function createIndex($table, $columnNames, $name=null)
330     {
331         if (!is_array($columnNames)) {
332             $columnNames = array($columnNames);
333         }
334
335         if (empty($name)) {
336             $name = "{$table}_".implode("_", $columnNames)."_idx";
337         }
338
339         $res = $this->conn->query("ALTER TABLE $table ".
340                                    "ADD INDEX $name (".
341                                    implode(",", $columnNames).")");
342
343         if (PEAR::isError($res)) {
344             throw new Exception($res->getMessage());
345         }
346
347         return true;
348     }
349
350     /**
351      * Drops a named index from a table.
352      *
353      * @param string $table name of the table the index is on.
354      * @param string $name  name of the index
355      *
356      * @return boolean success flag
357      */
358
359     public function dropIndex($table, $name)
360     {
361         $res = $this->conn->query("ALTER TABLE $table DROP INDEX $name");
362
363         if (PEAR::isError($res)) {
364             throw new Exception($res->getMessage());
365         }
366
367         return true;
368     }
369
370     /**
371      * Adds a column to a table
372      *
373      * @param string    $table     name of the table
374      * @param ColumnDef $columndef Definition of the new
375      *                             column.
376      *
377      * @return boolean success flag
378      */
379
380     public function addColumn($table, $columndef)
381     {
382         $sql = "ALTER TABLE $table ADD COLUMN " . $this->_columnSql($columndef);
383
384         $res = $this->conn->query($sql);
385
386         if (PEAR::isError($res)) {
387             throw new Exception($res->getMessage());
388         }
389
390         return true;
391     }
392
393     /**
394      * Modifies a column in the schema.
395      *
396      * The name must match an existing column and table.
397      *
398      * @param string    $table     name of the table
399      * @param ColumnDef $columndef new definition of the column.
400      *
401      * @return boolean success flag
402      */
403
404     public function modifyColumn($table, $columndef)
405     {
406         $sql = "ALTER TABLE $table MODIFY COLUMN " .
407           $this->_columnSql($columndef);
408
409         $res = $this->conn->query($sql);
410
411         if (PEAR::isError($res)) {
412             throw new Exception($res->getMessage());
413         }
414
415         return true;
416     }
417
418     /**
419      * Drops a column from a table
420      *
421      * The name must match an existing column.
422      *
423      * @param string $table      name of the table
424      * @param string $columnName name of the column to drop
425      *
426      * @return boolean success flag
427      */
428
429     public function dropColumn($table, $columnName)
430     {
431         $sql = "ALTER TABLE $table DROP COLUMN $columnName";
432
433         $res = $this->conn->query($sql);
434
435         if (PEAR::isError($res)) {
436             throw new Exception($res->getMessage());
437         }
438
439         return true;
440     }
441
442     /**
443      * Ensures that a table exists with the given
444      * name and the given column definitions.
445      *
446      * If the table does not yet exist, it will
447      * create the table. If it does exist, it will
448      * alter the table to match the column definitions.
449      *
450      * @param string $tableName name of the table
451      * @param array  $columns   array of ColumnDef
452      *                          objects for the table
453      *
454      * @return boolean success flag
455      */
456
457     public function ensureTable($tableName, $columns)
458     {
459         // XXX: DB engine portability -> toilet
460
461         try {
462             $td = $this->getTableDef($tableName);
463         } catch (SchemaTableMissingException $e) {
464             return $this->createTable($tableName, $columns);
465         }
466
467         $cur = $this->_names($td->columns);
468         $new = $this->_names($columns);
469
470         $dropIndex  = array();
471         $toadd      = array_diff($new, $cur);
472         $todrop     = array_diff($cur, $new);
473         $same       = array_intersect($new, $cur);
474         $tomod      = array();
475         $addIndex   = array();
476         $tableProps = array();
477
478         foreach ($same as $m) {
479             $curCol = $this->_byName($td->columns, $m);
480             $newCol = $this->_byName($columns, $m);
481
482             if (!$newCol->equals($curCol)) {
483                 $tomod[] = $newCol->name;
484                 continue;
485             }
486
487             // Earlier versions may have accidentally left tables at default
488             // charsets which might be latin1 or other freakish things.
489             if ($this->_isString($curCol)) {
490                 if ($curCol->charset != 'utf8') {
491                     $tomod[] = $newCol->name;
492                     continue;
493                 }
494             }
495         }
496
497         // Find any indices we have to change...
498         $curIdx = $this->_indexList($td->columns);
499         $newIdx = $this->_indexList($columns);
500
501         if ($curIdx['primary'] != $newIdx['primary']) {
502             if ($curIdx['primary']) {
503                 $dropIndex[] = 'drop primary key';
504             }
505             if ($newIdx['primary']) {
506                 $keys = implode(',', $newIdx['primary']);
507                 $addIndex[] = "add constraint primary key ($keys)";
508             }
509         }
510
511         $dropUnique = array_diff($curIdx['uniques'], $newIdx['uniques']);
512         $addUnique = array_diff($newIdx['uniques'], $curIdx['uniques']);
513         foreach ($dropUnique as $columnName) {
514             $dropIndex[] = 'drop key ' . $this->_uniqueKey($tableName, $columnName);
515         }
516         foreach ($addUnique as $columnName) {
517             $addIndex[] = 'add constraint unique key ' . $this->_uniqueKey($tableName, $columnName) . " ($columnName)";;
518         }
519
520         $dropMultiple = array_diff($curIdx['indices'], $newIdx['indices']);
521         $addMultiple = array_diff($newIdx['indices'], $curIdx['indices']);
522         foreach ($dropMultiple as $columnName) {
523             $dropIndex[] = 'drop key ' . $this->_key($tableName, $columnName);
524         }
525         foreach ($addMultiple as $columnName) {
526             $addIndex[] = 'add key ' . $this->_key($tableName, $columnName) . " ($columnName)";
527         }
528
529         // Check for table properties: make sure we're using a sane
530         // engine type and charset/collation.
531         // @fixme make the default engine configurable?
532         $oldProps = $this->getTableProperties($tableName, array('ENGINE', 'TABLE_COLLATION'));
533         if (strtolower($oldProps['ENGINE']) != 'innodb') {
534             $tableProps['ENGINE'] = 'InnoDB';
535         }
536         if (strtolower($oldProps['TABLE_COLLATION']) != 'utf8_bin') {
537             $tableProps['DEFAULT CHARSET'] = 'utf8';
538             $tableProps['COLLATE'] = 'utf8_bin';
539         }
540
541         if (count($dropIndex) + count($toadd) + count($todrop) + count($tomod) + count($addIndex) + count($tableProps) == 0) {
542             // nothing to do
543             return true;
544         }
545
546         // For efficiency, we want this all in one
547         // query, instead of using our methods.
548
549         $phrase = array();
550
551         foreach ($dropIndex as $indexSql) {
552             $phrase[] = $indexSql;
553         }
554
555         foreach ($toadd as $columnName) {
556             $cd = $this->_byName($columns, $columnName);
557
558             $phrase[] = 'ADD COLUMN ' . $this->_columnSql($cd);
559         }
560
561         foreach ($todrop as $columnName) {
562             $phrase[] = 'DROP COLUMN ' . $columnName;
563         }
564
565         foreach ($tomod as $columnName) {
566             $cd = $this->_byName($columns, $columnName);
567
568             $phrase[] = 'MODIFY COLUMN ' . $this->_columnSql($cd);
569         }
570
571         foreach ($addIndex as $indexSql) {
572             $phrase[] = $indexSql;
573         }
574
575         foreach ($tableProps as $key => $val) {
576             $phrase[] = "$key=$val";
577         }
578
579         $sql = 'ALTER TABLE ' . $tableName . ' ' . implode(', ', $phrase);
580
581         common_log(LOG_DEBUG, __METHOD__ . ': ' . $sql);
582         $res = $this->conn->query($sql);
583
584         if (PEAR::isError($res)) {
585             throw new Exception($res->getMessage());
586         }
587
588         return true;
589     }
590
591     /**
592      * Returns the array of names from an array of
593      * ColumnDef objects.
594      *
595      * @param array $cds array of ColumnDef objects
596      *
597      * @return array strings for name values
598      */
599
600     private function _names($cds)
601     {
602         $names = array();
603
604         foreach ($cds as $cd) {
605             $names[] = $cd->name;
606         }
607
608         return $names;
609     }
610
611     /**
612      * Get a ColumnDef from an array matching
613      * name.
614      *
615      * @param array  $cds  Array of ColumnDef objects
616      * @param string $name Name of the column
617      *
618      * @return ColumnDef matching item or null if no match.
619      */
620
621     private function _byName($cds, $name)
622     {
623         foreach ($cds as $cd) {
624             if ($cd->name == $name) {
625                 return $cd;
626             }
627         }
628
629         return null;
630     }
631
632     /**
633      * Return the proper SQL for creating or
634      * altering a column.
635      *
636      * Appropriate for use in CREATE TABLE or
637      * ALTER TABLE statements.
638      *
639      * @param ColumnDef $cd column to create
640      *
641      * @return string correct SQL for that column
642      */
643
644     private function _columnSql($cd)
645     {
646         $sql = "{$cd->name} ";
647
648         if (!empty($cd->size)) {
649             $sql .= "{$cd->type}({$cd->size}) ";
650         } else {
651             $sql .= "{$cd->type} ";
652         }
653
654         if ($this->_isString($cd)) {
655             $sql .= " CHARACTER SET utf8 ";
656         }
657
658         if (!empty($cd->default)) {
659             $sql .= "default {$cd->default} ";
660         } else {
661             $sql .= ($cd->nullable) ? "null " : "not null ";
662         }
663         
664         if (!empty($cd->auto_increment)) {
665             $sql .= " auto_increment ";
666         }
667
668         if (!empty($cd->extra)) {
669             $sql .= "{$cd->extra} ";
670         }
671
672         return $sql;
673     }
674
675     /**
676      * Is this column a string type?
677      */
678     private function _isString(ColumnDef $cd)
679     {
680         $strings = array('char', 'varchar', 'text');
681         return in_array(strtolower($cd->type), $strings);
682     }
683 }