]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/mysqlschema.php
Finish patching up the index fetching in new schema stuff for mysql
[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 $table Name of the table to get
76      *
77      * @return TableDef tabledef for that table.
78      * @throws SchemaTableMissingException
79      */
80
81     public function getTableDef($table)
82     {
83         $def = array();
84         $hasKeys = false;
85
86         // Pull column data from INFORMATION_SCHEMA
87         $columns = $this->fetchMetaInfo($table, 'COLUMNS', 'ORDINAL_POSITION');
88         if (count($columns) == 0) {
89             throw new SchemaTableMissingException("No such table: $table");
90         }
91
92         foreach ($columns as $row) {
93
94             $name = $row['COLUMN_NAME'];
95             $field = array();
96
97             if ($row['DATA_TYPE'] !== null) {
98                 $field['type'] = $row['DATA_TYPE'];
99             }
100             if ($row['CHARACTER_MAXIMUM_LENGTH'] !== null) {
101                 $field['length'] = intval($row['CHARACTER_MAXIMUM_LENGTH']);
102             }
103             if ($row['NUMERIC_PRECISION'] !== null) {
104                 $field['precision'] = intval($row['NUMERIC_PRECISION']);
105             }
106             if ($row['NUMERIC_SCALE'] !== null) {
107                 $field['scale'] = intval($row['NUMERIC_SCALE']);
108             }
109             if ($row['IS_NULLABLE'] == 'NO') {
110                 $field['not null'] = true;
111             }
112             if ($row['COLUMN_DEFAULT'] !== null) {
113                 $field['default'] = $row['COLUMN_DEFAULT'];
114             }
115             if ($row['COLUMN_KEY'] !== null) {
116                 // We'll need to look up key info...
117                 $hasKeys = true;
118             }
119             if ($row['COLUMN_COMMENT'] !== null) {
120                 $field['description'] = $row['COLUMN_COMMENT'];
121             }
122
123             // $row['EXTRA'] may contain 'autoincrement'
124             // ^ type=serial?
125             // $row['EXTRA'] may contain 'on update CURRENT_TIMESTAMP'
126             // ^ ...... how to specify?
127             // these seem to be the only values in curent use
128             
129             if ($row['CHARACTER_SET_NAME'] !== null) {
130                 // @fixme check against defaults?
131                 //$def['charset'] = $row['CHARACTER_SET_NAME'];
132                 //$def['collate']  = $row['COLLATION_NAME'];
133             }
134
135             $def['fields'][$name] = $field;
136         }
137
138         if ($hasKeys) {
139             // INFORMATION_SCHEMA's CONSTRAINTS and KEY_COLUMN_USAGE tables give
140             // good info on primary and unique keys but don't list ANY info on
141             // multi-value keys, which is lame-o. Sigh.
142             //
143             // Let's go old school and use SHOW INDEX :D
144             //
145             $keyInfo = $this->fetchIndexInfo($table);
146             $keys = array();
147             foreach ($keyInfo as $row) {
148                 $name = $row['Key_name'];
149                 $column = $row['Column_name'];
150
151                 if (!isset($keys[$name])) {
152                     $keys[$name] = array();
153                 }
154                 $keys[$name][] = $column;
155
156                 if ($name == 'PRIMARY') {
157                     $type = 'primary key';
158                 } else if ($row['Non_unique'] == 0) {
159                     $type = 'unique keys';
160                 } else if ($row['Index_type'] == 'FULLTEXT') {
161                     $type = 'fulltext indexes';
162                 } else {
163                     $type = 'indexes';
164                 }
165                 $keyTypes[$name] = $type;
166             }
167
168             foreach ($keyTypes as $name => $type) {
169                 if ($type == 'primary key') {
170                     // there can be only one
171                     $def[$type] = $keys[$name];
172                 } else {
173                     $def[$type][$name] = $keys[$name];
174                 }
175             }
176         }
177         return $def;
178     }
179
180     /**
181      * Pull the given table properties from INFORMATION_SCHEMA.
182      * Most of the good stuff is MySQL extensions.
183      *
184      * @return array
185      * @throws Exception if table info can't be looked up
186      */
187
188     function getTableProperties($table, $props)
189     {
190         $data = $this->fetchMetaInfo($table, 'TABLES');
191         if ($data) {
192             return $data[0];
193         } else {
194             throw new SchemaTableMissingException("No such table: $table");
195         }
196     }
197
198     /**
199      * Pull some INFORMATION.SCHEMA data for the given table.
200      *
201      * @param string $table
202      * @return array of arrays
203      */
204     function fetchMetaInfo($table, $infoTable, $orderBy=null)
205     {
206         $query = "SELECT * FROM INFORMATION_SCHEMA.%s " .
207                  "WHERE TABLE_SCHEMA='%s' AND TABLE_NAME='%s'";
208         $schema = $this->conn->dsn['database'];
209         $sql = sprintf($query, $infoTable, $schema, $table);
210         if ($orderBy) {
211             $sql .= ' ORDER BY ' . $orderBy;
212         }
213         return $this->fetchQueryData($sql);
214     }
215
216     /**
217      * Pull 'SHOW INDEX' data for the given table.
218      *
219      * @param string $table
220      * @return array of arrays
221      */
222     function fetchIndexInfo($table)
223     {
224         $query = "SHOW INDEX FROM `%s`";
225         $sql = sprintf($query, $table);
226         return $this->fetchQueryData($sql);
227     }
228
229     /**
230      * Pull info from the query into a fun-fun array of dooooom
231      *
232      * @param string $sql
233      * @return array of arrays
234      */
235     protected function fetchQueryData($sql)
236     {
237         $res = $this->conn->query($sql);
238         if (PEAR::isError($res)) {
239             throw new Exception($res->getMessage());
240         }
241
242         $out = array();
243         $row = array();
244         while ($res->fetchInto($row, DB_FETCHMODE_ASSOC)) {
245             $out[] = $row;
246         }
247         $res->free();
248
249         return $out;
250     }
251
252     /**
253      * Creates a table with the given names and columns.
254      *
255      * @param string $name    Name of the table
256      * @param array  $columns Array of ColumnDef objects
257      *                        for new table.
258      *
259      * @return boolean success flag
260      */
261
262     public function createTable($name, $columns)
263     {
264         $uniques = array();
265         $primary = array();
266         $indices = array();
267
268         $sql = "CREATE TABLE $name (\n";
269
270         for ($i = 0; $i < count($columns); $i++) {
271
272             $cd =& $columns[$i];
273
274             if ($i > 0) {
275                 $sql .= ",\n";
276             }
277
278             $sql .= $this->_columnSql($cd);
279         }
280
281         $idx = $this->_indexList($columns);
282
283         if ($idx['primary']) {
284             $sql .= ",\nconstraint primary key (" . implode(',', $idx['primary']) . ")";
285         }
286
287         foreach ($idx['uniques'] as $u) {
288             $key = $this->_uniqueKey($name, $u);
289             $sql .= ",\nunique index $key ($u)";
290         }
291
292         foreach ($idx['indices'] as $i) {
293             $key = $this->_key($name, $i);
294             $sql .= ",\nindex $key ($i)";
295         }
296
297         $sql .= ") ENGINE=InnoDB CHARACTER SET utf8 COLLATE utf8_bin; ";
298
299         $res = $this->conn->query($sql);
300
301         if (PEAR::isError($res)) {
302             throw new Exception($res->getMessage());
303         }
304
305         return true;
306     }
307
308     /**
309      * Look over a list of column definitions and list up which
310      * indices will be present
311      */
312     private function _indexList(array $columns)
313     {
314         $list = array('uniques' => array(),
315                       'primary' => array(),
316                       'indices' => array());
317         foreach ($columns as $cd) {
318             switch ($cd->key) {
319             case 'UNI':
320                 $list['uniques'][] = $cd->name;
321                 break;
322             case 'PRI':
323                 $list['primary'][] = $cd->name;
324                 break;
325             case 'MUL':
326                 $list['indices'][] = $cd->name;
327                 break;
328             }
329         }
330         return $list;
331     }
332
333     /**
334      * Get the unique index key name for a given column on this table
335      */
336     function _uniqueKey($tableName, $columnName)
337     {
338         return $this->_key($tableName, $columnName);
339     }
340
341     /**
342      * Get the index key name for a given column on this table
343      */
344     function _key($tableName, $columnName)
345     {
346         return "{$tableName}_{$columnName}_idx";
347     }
348
349     /**
350      * Ensures that a table exists with the given
351      * name and the given column definitions.
352      *
353      * If the table does not yet exist, it will
354      * create the table. If it does exist, it will
355      * alter the table to match the column definitions.
356      *
357      * @param string $tableName name of the table
358      * @param array  $columns   array of ColumnDef
359      *                          objects for the table
360      *
361      * @return boolean success flag
362      */
363
364     public function ensureTable($tableName, $columns)
365     {
366         // XXX: DB engine portability -> toilet
367
368         try {
369             $td = $this->getTableDef($tableName);
370         } catch (SchemaTableMissingException $e) {
371             return $this->createTable($tableName, $columns);
372         }
373
374         $cur = $this->_names($td->columns);
375         $new = $this->_names($columns);
376
377         $dropIndex  = array();
378         $toadd      = array_diff($new, $cur);
379         $todrop     = array_diff($cur, $new);
380         $same       = array_intersect($new, $cur);
381         $tomod      = array();
382         $addIndex   = array();
383         $tableProps = array();
384
385         foreach ($same as $m) {
386             $curCol = $this->_byName($td->columns, $m);
387             $newCol = $this->_byName($columns, $m);
388
389             if (!$newCol->equals($curCol)) {
390                 $tomod[] = $newCol->name;
391                 continue;
392             }
393
394             // Earlier versions may have accidentally left tables at default
395             // charsets which might be latin1 or other freakish things.
396             if ($this->_isString($curCol)) {
397                 if ($curCol->charset != 'utf8') {
398                     $tomod[] = $newCol->name;
399                     continue;
400                 }
401             }
402         }
403
404         // Find any indices we have to change...
405         $curIdx = $this->_indexList($td->columns);
406         $newIdx = $this->_indexList($columns);
407
408         if ($curIdx['primary'] != $newIdx['primary']) {
409             if ($curIdx['primary']) {
410                 $dropIndex[] = 'drop primary key';
411             }
412             if ($newIdx['primary']) {
413                 $keys = implode(',', $newIdx['primary']);
414                 $addIndex[] = "add constraint primary key ($keys)";
415             }
416         }
417
418         $dropUnique = array_diff($curIdx['uniques'], $newIdx['uniques']);
419         $addUnique = array_diff($newIdx['uniques'], $curIdx['uniques']);
420         foreach ($dropUnique as $columnName) {
421             $dropIndex[] = 'drop key ' . $this->_uniqueKey($tableName, $columnName);
422         }
423         foreach ($addUnique as $columnName) {
424             $addIndex[] = 'add constraint unique key ' . $this->_uniqueKey($tableName, $columnName) . " ($columnName)";;
425         }
426
427         $dropMultiple = array_diff($curIdx['indices'], $newIdx['indices']);
428         $addMultiple = array_diff($newIdx['indices'], $curIdx['indices']);
429         foreach ($dropMultiple as $columnName) {
430             $dropIndex[] = 'drop key ' . $this->_key($tableName, $columnName);
431         }
432         foreach ($addMultiple as $columnName) {
433             $addIndex[] = 'add key ' . $this->_key($tableName, $columnName) . " ($columnName)";
434         }
435
436         // Check for table properties: make sure we're using a sane
437         // engine type and charset/collation.
438         // @fixme make the default engine configurable?
439         $oldProps = $this->getTableProperties($tableName, array('ENGINE', 'TABLE_COLLATION'));
440         if (strtolower($oldProps['ENGINE']) != 'innodb') {
441             $tableProps['ENGINE'] = 'InnoDB';
442         }
443         if (strtolower($oldProps['TABLE_COLLATION']) != 'utf8_bin') {
444             $tableProps['DEFAULT CHARSET'] = 'utf8';
445             $tableProps['COLLATE'] = 'utf8_bin';
446         }
447
448         if (count($dropIndex) + count($toadd) + count($todrop) + count($tomod) + count($addIndex) + count($tableProps) == 0) {
449             // nothing to do
450             return true;
451         }
452
453         // For efficiency, we want this all in one
454         // query, instead of using our methods.
455
456         $phrase = array();
457
458         foreach ($dropIndex as $indexSql) {
459             $phrase[] = $indexSql;
460         }
461
462         foreach ($toadd as $columnName) {
463             $cd = $this->_byName($columns, $columnName);
464
465             $phrase[] = 'ADD COLUMN ' . $this->_columnSql($cd);
466         }
467
468         foreach ($todrop as $columnName) {
469             $phrase[] = 'DROP COLUMN ' . $columnName;
470         }
471
472         foreach ($tomod as $columnName) {
473             $cd = $this->_byName($columns, $columnName);
474
475             $phrase[] = 'MODIFY COLUMN ' . $this->_columnSql($cd);
476         }
477
478         foreach ($addIndex as $indexSql) {
479             $phrase[] = $indexSql;
480         }
481
482         foreach ($tableProps as $key => $val) {
483             $phrase[] = "$key=$val";
484         }
485
486         $sql = 'ALTER TABLE ' . $tableName . ' ' . implode(', ', $phrase);
487
488         common_log(LOG_DEBUG, __METHOD__ . ': ' . $sql);
489         $res = $this->conn->query($sql);
490
491         if (PEAR::isError($res)) {
492             throw new Exception($res->getMessage());
493         }
494
495         return true;
496     }
497
498     /**
499      * Is this column a string type?
500      */
501     private function _isString(array $cd)
502     {
503         $strings = array('char', 'varchar', 'text');
504         return in_array(strtolower($cd['type']), $strings);
505     }
506
507     /**
508      * Return the proper SQL for creating or
509      * altering a column.
510      *
511      * Appropriate for use in CREATE TABLE or
512      * ALTER TABLE statements.
513      *
514      * @param ColumnDef $cd column to create
515      *
516      * @return string correct SQL for that column
517      */
518
519     function columnSql(array $cd)
520     {
521         $line = array();
522         $line[] = parent::_columnSql($cd);
523
524         if ($cd['type'] == 'serial') {
525             $line[] = 'auto_increment';
526         }
527
528         if (!empty($cd['extra'])) {
529             $line[] = $cd['extra']; // hisss boooo
530         }
531
532         if (!empty($cd['description'])) {
533             $line[] = 'comment';
534             $line[] = $this->quote($cd['description']);
535         }
536
537         return implode(' ', $line);
538     }
539
540     function mapType($column)
541     {
542         $map = array('serial' => 'int',
543                      'integer' => 'int',
544                      'numeric' => 'decimal');
545         
546         $type = $column['type'];
547         if (isset($map[$type])) {
548             $type = $map[$type];
549         }
550
551         if (!empty($column['size'])) {
552             $size = $column['size'];
553             if ($type == 'int' &&
554                        in_array($size, array('tiny', 'small', 'medium', 'big'))) {
555                 $type = $size . $type;
556             } else if (in_array($type, array('blob', 'text')) &&
557                        in_array($size, array('tiny', 'medium', 'long'))) {
558                 $type = $size . $type;
559             }
560         }
561
562         return $type;
563     }
564
565     function typeAndSize($column)
566     {
567         if ($column['type'] == 'enum') {
568             $vals = array_map(array($this, 'quote'), $column['enum']);
569             return 'enum(' . implode(',', $vals) . ')';
570         } else if ($this->_isString($column)) {
571             return parent::typeAndSize($column) . ' CHARSET utf8';
572         } else {
573             return parent::typeAndSize($column);
574         }
575     }
576 }