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