]> 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 $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         $schema = $this->conn->dsn['database'];
86         $sql = sprintf($query, $schema, $name);
87         $res = $this->conn->query($sql);
88
89         if (PEAR::isError($res)) {
90             throw new Exception($res->getMessage());
91         }
92         if ($res->numRows() == 0) {
93             $res->free();
94             throw new SchemaTableMissingException("No such table: $name");
95         }
96
97         $td = new TableDef();
98
99         $td->name    = $name;
100         $td->columns = array();
101
102         $row = array();
103
104         while ($res->fetchInto($row, DB_FETCHMODE_ASSOC)) {
105
106             $cd = new ColumnDef();
107
108             $cd->name = $row['COLUMN_NAME'];
109
110             $packed = $row['COLUMN_TYPE'];
111
112             if (preg_match('/^(\w+)\((\d+)\)$/', $packed, $match)) {
113                 $cd->type = $match[1];
114                 $cd->size = $match[2];
115             } else {
116                 $cd->type = $packed;
117             }
118
119             $cd->nullable = ($row['IS_NULLABLE'] == 'YES') ? true : false;
120             $cd->key      = $row['COLUMN_KEY'];
121             $cd->default  = $row['COLUMN_DEFAULT'];
122             $cd->extra    = $row['EXTRA'];
123
124             // Autoincrement is stuck into the extra column.
125             // Pull it out so we don't accidentally mod it every time...
126             $extra = preg_replace('/(^|\s)auto_increment(\s|$)/i', '$1$2', $cd->extra);
127             if ($extra != $cd->extra) {
128                 $cd->extra = trim($extra);
129                 $cd->auto_increment = true;
130             }
131
132             // mysql extensions -- not (yet) used by base class
133             $cd->charset  = $row['CHARACTER_SET_NAME'];
134             $cd->collate  = $row['COLLATION_NAME'];
135
136             $td->columns[] = $cd;
137         }
138         $res->free();
139
140         return $td;
141     }
142
143     /**
144      * Pull the given table properties from INFORMATION_SCHEMA.
145      * Most of the good stuff is MySQL extensions.
146      *
147      * @return array
148      * @throws Exception if table info can't be looked up
149      */
150
151     function getTableProperties($table, $props)
152     {
153         $query = "SELECT %s FROM INFORMATION_SCHEMA.TABLES " .
154                  "WHERE TABLE_SCHEMA='%s' AND TABLE_NAME='%s'";
155         $schema = $this->conn->dsn['database'];
156         $sql = sprintf($query, implode(',', $props), $schema, $table);
157         $res = $this->conn->query($sql);
158
159         $row = array();
160         $ok = $res->fetchInto($row, DB_FETCHMODE_ASSOC);
161         $res->free();
162         
163         if ($ok) {
164             return $row;
165         } else {
166             throw new SchemaTableMissingException("No such table: $table");
167         }
168     }
169
170     /**
171      * Creates a table with the given names and columns.
172      *
173      * @param string $name    Name of the table
174      * @param array  $columns Array of ColumnDef objects
175      *                        for new table.
176      *
177      * @return boolean success flag
178      */
179
180     public function createTable($name, $columns)
181     {
182         $uniques = array();
183         $primary = array();
184         $indices = array();
185
186         $sql = "CREATE TABLE $name (\n";
187
188         for ($i = 0; $i < count($columns); $i++) {
189
190             $cd =& $columns[$i];
191
192             if ($i > 0) {
193                 $sql .= ",\n";
194             }
195
196             $sql .= $this->_columnSql($cd);
197         }
198
199         $idx = $this->_indexList($columns);
200
201         if ($idx['primary']) {
202             $sql .= ",\nconstraint primary key (" . implode(',', $idx['primary']) . ")";
203         }
204
205         foreach ($idx['uniques'] as $u) {
206             $key = $this->_uniqueKey($name, $u);
207             $sql .= ",\nunique index $key ($u)";
208         }
209
210         foreach ($idx['indices'] as $i) {
211             $key = $this->_key($name, $i);
212             $sql .= ",\nindex $key ($i)";
213         }
214
215         $sql .= ") ENGINE=InnoDB CHARACTER SET utf8 COLLATE utf8_bin; ";
216
217         $res = $this->conn->query($sql);
218
219         if (PEAR::isError($res)) {
220             throw new Exception($res->getMessage());
221         }
222
223         return true;
224     }
225
226     /**
227      * Look over a list of column definitions and list up which
228      * indices will be present
229      */
230     private function _indexList(array $columns)
231     {
232         $list = array('uniques' => array(),
233                       'primary' => array(),
234                       'indices' => array());
235         foreach ($columns as $cd) {
236             switch ($cd->key) {
237             case 'UNI':
238                 $list['uniques'][] = $cd->name;
239                 break;
240             case 'PRI':
241                 $list['primary'][] = $cd->name;
242                 break;
243             case 'MUL':
244                 $list['indices'][] = $cd->name;
245                 break;
246             }
247         }
248         return $list;
249     }
250
251     /**
252      * Get the unique index key name for a given column on this table
253      */
254     function _uniqueKey($tableName, $columnName)
255     {
256         return $this->_key($tableName, $columnName);
257     }
258
259     /**
260      * Get the index key name for a given column on this table
261      */
262     function _key($tableName, $columnName)
263     {
264         return "{$tableName}_{$columnName}_idx";
265     }
266
267     /**
268      * Ensures that a table exists with the given
269      * name and the given column definitions.
270      *
271      * If the table does not yet exist, it will
272      * create the table. If it does exist, it will
273      * alter the table to match the column definitions.
274      *
275      * @param string $tableName name of the table
276      * @param array  $columns   array of ColumnDef
277      *                          objects for the table
278      *
279      * @return boolean success flag
280      */
281
282     public function ensureTable($tableName, $columns)
283     {
284         // XXX: DB engine portability -> toilet
285
286         try {
287             $td = $this->getTableDef($tableName);
288         } catch (SchemaTableMissingException $e) {
289             return $this->createTable($tableName, $columns);
290         }
291
292         $cur = $this->_names($td->columns);
293         $new = $this->_names($columns);
294
295         $dropIndex  = array();
296         $toadd      = array_diff($new, $cur);
297         $todrop     = array_diff($cur, $new);
298         $same       = array_intersect($new, $cur);
299         $tomod      = array();
300         $addIndex   = array();
301         $tableProps = array();
302
303         foreach ($same as $m) {
304             $curCol = $this->_byName($td->columns, $m);
305             $newCol = $this->_byName($columns, $m);
306
307             if (!$newCol->equals($curCol)) {
308                 $tomod[] = $newCol->name;
309                 continue;
310             }
311
312             // Earlier versions may have accidentally left tables at default
313             // charsets which might be latin1 or other freakish things.
314             if ($this->_isString($curCol)) {
315                 if ($curCol->charset != 'utf8') {
316                     $tomod[] = $newCol->name;
317                     continue;
318                 }
319             }
320         }
321
322         // Find any indices we have to change...
323         $curIdx = $this->_indexList($td->columns);
324         $newIdx = $this->_indexList($columns);
325
326         if ($curIdx['primary'] != $newIdx['primary']) {
327             if ($curIdx['primary']) {
328                 $dropIndex[] = 'drop primary key';
329             }
330             if ($newIdx['primary']) {
331                 $keys = implode(',', $newIdx['primary']);
332                 $addIndex[] = "add constraint primary key ($keys)";
333             }
334         }
335
336         $dropUnique = array_diff($curIdx['uniques'], $newIdx['uniques']);
337         $addUnique = array_diff($newIdx['uniques'], $curIdx['uniques']);
338         foreach ($dropUnique as $columnName) {
339             $dropIndex[] = 'drop key ' . $this->_uniqueKey($tableName, $columnName);
340         }
341         foreach ($addUnique as $columnName) {
342             $addIndex[] = 'add constraint unique key ' . $this->_uniqueKey($tableName, $columnName) . " ($columnName)";;
343         }
344
345         $dropMultiple = array_diff($curIdx['indices'], $newIdx['indices']);
346         $addMultiple = array_diff($newIdx['indices'], $curIdx['indices']);
347         foreach ($dropMultiple as $columnName) {
348             $dropIndex[] = 'drop key ' . $this->_key($tableName, $columnName);
349         }
350         foreach ($addMultiple as $columnName) {
351             $addIndex[] = 'add key ' . $this->_key($tableName, $columnName) . " ($columnName)";
352         }
353
354         // Check for table properties: make sure we're using a sane
355         // engine type and charset/collation.
356         // @fixme make the default engine configurable?
357         $oldProps = $this->getTableProperties($tableName, array('ENGINE', 'TABLE_COLLATION'));
358         if (strtolower($oldProps['ENGINE']) != 'innodb') {
359             $tableProps['ENGINE'] = 'InnoDB';
360         }
361         if (strtolower($oldProps['TABLE_COLLATION']) != 'utf8_bin') {
362             $tableProps['DEFAULT CHARSET'] = 'utf8';
363             $tableProps['COLLATE'] = 'utf8_bin';
364         }
365
366         if (count($dropIndex) + count($toadd) + count($todrop) + count($tomod) + count($addIndex) + count($tableProps) == 0) {
367             // nothing to do
368             return true;
369         }
370
371         // For efficiency, we want this all in one
372         // query, instead of using our methods.
373
374         $phrase = array();
375
376         foreach ($dropIndex as $indexSql) {
377             $phrase[] = $indexSql;
378         }
379
380         foreach ($toadd as $columnName) {
381             $cd = $this->_byName($columns, $columnName);
382
383             $phrase[] = 'ADD COLUMN ' . $this->_columnSql($cd);
384         }
385
386         foreach ($todrop as $columnName) {
387             $phrase[] = 'DROP COLUMN ' . $columnName;
388         }
389
390         foreach ($tomod as $columnName) {
391             $cd = $this->_byName($columns, $columnName);
392
393             $phrase[] = 'MODIFY COLUMN ' . $this->_columnSql($cd);
394         }
395
396         foreach ($addIndex as $indexSql) {
397             $phrase[] = $indexSql;
398         }
399
400         foreach ($tableProps as $key => $val) {
401             $phrase[] = "$key=$val";
402         }
403
404         $sql = 'ALTER TABLE ' . $tableName . ' ' . implode(', ', $phrase);
405
406         common_log(LOG_DEBUG, __METHOD__ . ': ' . $sql);
407         $res = $this->conn->query($sql);
408
409         if (PEAR::isError($res)) {
410             throw new Exception($res->getMessage());
411         }
412
413         return true;
414     }
415
416     /**
417      * Is this column a string type?
418      */
419     private function _isString(array $cd)
420     {
421         $strings = array('char', 'varchar', 'text');
422         return in_array(strtolower($cd['type']), $strings);
423     }
424
425     /**
426      * Return the proper SQL for creating or
427      * altering a column.
428      *
429      * Appropriate for use in CREATE TABLE or
430      * ALTER TABLE statements.
431      *
432      * @param ColumnDef $cd column to create
433      *
434      * @return string correct SQL for that column
435      */
436
437     function columnSql(array $cd)
438     {
439         $line = array();
440         $line[] = parent::_columnSql($cd);
441
442         if ($cd['type'] == 'serial') {
443             $line[] = 'auto_increment';
444         }
445
446         if (!empty($cd['extra'])) {
447             $line[] = $cd['extra']; // hisss boooo
448         }
449
450         if (!empty($cd['description'])) {
451             $line[] = 'comment';
452             $line[] = $this->quote($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 }