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