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