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