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