]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/mysqlschema.php
[CORE] Bump Database requirement to MariaDB 10.3+
[quix0rs-gnu-social.git] / lib / mysqlschema.php
1 <?php
2 // This file is part of GNU social - https://www.gnu.org/software/social
3 //
4 // GNU social is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU Affero General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // GNU social is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 // GNU Affero General Public License for more details.
13 //
14 // You should have received a copy of the GNU Affero General Public License
15 // along with GNU social.  If not, see <http://www.gnu.org/licenses/>.
16
17 /**
18  * Database schema for MariaDB
19  *
20  * @category Database
21  * @package  GNUsocial
22  * @author   Evan Prodromou <evan@status.net>
23  * @copyright 2019 Free Software Foundation, Inc http://www.fsf.org
24  * @license   https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
25  */
26
27 defined('GNUSOCIAL') || die();
28
29 /**
30  * Class representing the database schema for MariaDB
31  *
32  * A class representing the database schema. Can be used to
33  * manipulate the schema -- especially for plugins and upgrade
34  * utilities.
35  *
36  * @copyright 2019 Free Software Foundation, Inc http://www.fsf.org
37  * @license   https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
38  */
39 class MysqlSchema extends Schema
40 {
41     static $_single = null;
42     protected $conn = null;
43
44     /**
45      * Main public entry point. Use this to get
46      * the singleton object.
47      *
48      * @param null $conn
49      * @return Schema the (single) Schema object
50      */
51
52     static function get($conn = null)
53     {
54         if (empty(self::$_single)) {
55             self::$_single = new Schema($conn);
56         }
57         return self::$_single;
58     }
59
60     /**
61      * Returns a TableDef object for the table
62      * in the schema with the given name.
63      *
64      * Throws an exception if the table is not found.
65      *
66      * @param string $table Name of the table to get
67      *
68      * @return array of tabledef for that table.
69      * @throws PEAR_Exception
70      * @throws SchemaTableMissingException
71      */
72
73     public function getTableDef($table)
74     {
75         $def = [];
76         $hasKeys = false;
77
78         // Pull column data from INFORMATION_SCHEMA
79         $columns = $this->fetchMetaInfo($table, 'COLUMNS', 'ORDINAL_POSITION');
80         if (count($columns) == 0) {
81             throw new SchemaTableMissingException("No such table: $table");
82         }
83
84         foreach ($columns as $row) {
85
86             $name = $row['COLUMN_NAME'];
87             $field = [];
88
89             // warning -- 'unsigned' attr on numbers isn't given in DATA_TYPE and friends.
90             // It is stuck in on COLUMN_TYPE though (eg 'bigint(20) unsigned')
91             $field['type'] = $type = $row['DATA_TYPE'];
92
93             if ($type == 'char' || $type == 'varchar') {
94                 if ($row['CHARACTER_MAXIMUM_LENGTH'] !== null) {
95                     $field['length'] = intval($row['CHARACTER_MAXIMUM_LENGTH']);
96                 }
97             }
98             if ($type == 'decimal') {
99                 // Other int types may report these values, but they're irrelevant.
100                 // Just ignore them!
101                 if ($row['NUMERIC_PRECISION'] !== null) {
102                     $field['precision'] = intval($row['NUMERIC_PRECISION']);
103                 }
104                 if ($row['NUMERIC_SCALE'] !== null) {
105                     $field['scale'] = intval($row['NUMERIC_SCALE']);
106                 }
107             }
108             if ($row['IS_NULLABLE'] == 'NO') {
109                 $field['not null'] = true;
110             }
111             if ($row['COLUMN_DEFAULT'] !== null) {
112                 // Hack for timestamp cols
113                 if ($type == 'timestamp' && $row['COLUMN_DEFAULT'] == 'CURRENT_TIMESTAMP') {
114                     // skip because timestamp is numerical, but it accepts datetime strings as well
115                 } else {
116                     $field['default'] = $row['COLUMN_DEFAULT'];
117                     if ($this->isNumericType($type)) {
118                         $field['default'] = intval($field['default']);
119                     }
120                 }
121             }
122             if ($row['COLUMN_KEY'] !== null) {
123                 // We'll need to look up key info...
124                 $hasKeys = true;
125             }
126             if ($row['COLUMN_COMMENT'] !== null && $row['COLUMN_COMMENT'] != '') {
127                 $field['description'] = $row['COLUMN_COMMENT'];
128             }
129
130             $extra = $row['EXTRA'];
131             if ($extra) {
132                 if (preg_match('/(^|\s)auto_increment(\s|$)/i', $extra)) {
133                     $field['auto_increment'] = true;
134                 }
135                 // $row['EXTRA'] may contain 'on update CURRENT_TIMESTAMP'
136                 // ^ ...... how to specify?
137             }
138
139             /* @fixme check against defaults?
140             if ($row['CHARACTER_SET_NAME'] !== null) {
141                 $def['charset'] = $row['CHARACTER_SET_NAME'];
142                 $def['collate'] = $row['COLLATION_NAME'];
143             }*/
144
145             $def['fields'][$name] = $field;
146         }
147
148         if ($hasKeys) {
149             // INFORMATION_SCHEMA's CONSTRAINTS and KEY_COLUMN_USAGE tables give
150             // good info on primary and unique keys but don't list ANY info on
151             // multi-value keys, which is lame-o. Sigh.
152             //
153             // Let's go old school and use SHOW INDEX :D
154             //
155             $keyInfo = $this->fetchIndexInfo($table);
156             $keys = [];
157             $keyTypes = [];
158             foreach ($keyInfo as $row) {
159                 $name = $row['Key_name'];
160                 $column = $row['Column_name'];
161
162                 if (!isset($keys[$name])) {
163                     $keys[$name] = [];
164                 }
165                 $keys[$name][] = $column;
166
167                 if ($name == 'PRIMARY') {
168                     $type = 'primary key';
169                 } else if ($row['Non_unique'] == 0) {
170                     $type = 'unique keys';
171                 } else if ($row['Index_type'] == 'FULLTEXT') {
172                     $type = 'fulltext indexes';
173                 } else {
174                     $type = 'indexes';
175                 }
176                 $keyTypes[$name] = $type;
177             }
178
179             foreach ($keyTypes as $name => $type) {
180                 if ($type == 'primary key') {
181                     // there can be only one
182                     $def[$type] = $keys[$name];
183                 } else {
184                     $def[$type][$name] = $keys[$name];
185                 }
186             }
187         }
188         return $def;
189     }
190
191     /**
192      * Pull the given table properties from INFORMATION_SCHEMA.
193      * Most of the good stuff is MySQL extensions.
194      *
195      * @param $table
196      * @param $props
197      * @return array
198      * @throws PEAR_Exception
199      * @throws SchemaTableMissingException
200      */
201
202     function getTableProperties($table, $props)
203     {
204         $data = $this->fetchMetaInfo($table, 'TABLES');
205         if ($data) {
206             return $data[0];
207         } else {
208             throw new SchemaTableMissingException("No such table: $table");
209         }
210     }
211
212     /**
213      * Pull some INFORMATION.SCHEMA data for the given table.
214      *
215      * @param string $table
216      * @param $infoTable
217      * @param null $orderBy
218      * @return array of arrays
219      * @throws PEAR_Exception
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      * @throws PEAR_Exception
239      */
240     function fetchIndexInfo($table)
241     {
242         $query = "SHOW INDEX FROM `%s`";
243         $sql = sprintf($query, $table);
244         return $this->fetchQueryData($sql);
245     }
246
247     /**
248      * Append an SQL statement with an index definition for a full-text search
249      * index over one or more columns on a table.
250      *
251      * @param array $statements
252      * @param string $table
253      * @param string $name
254      * @param array $def
255      */
256     function appendCreateFulltextIndex(array &$statements, $table, $name, array $def)
257     {
258         $statements[] = "CREATE FULLTEXT INDEX $name ON $table " . $this->buildIndexList($def);
259     }
260
261     /**
262      * Close out a 'create table' SQL statement.
263      *
264      * @param string $name
265      * @param array $def
266      * @return string;
267      *
268      */
269     function endCreateTable($name, array $def)
270     {
271         $engine = $this->preferredEngine($def);
272         return ") ENGINE=$engine CHARACTER SET utf8mb4 COLLATE utf8mb4_bin";
273     }
274
275     function preferredEngine($def)
276     {
277         /* MyISAM is no longer required for fulltext indexes, fortunately
278         if (!empty($def['fulltext indexes'])) {
279             return 'MyISAM';
280         }
281         */
282         return 'InnoDB';
283     }
284
285     /**
286      * Get the unique index key name for a given column on this table
287      * @param $tableName
288      * @param $columnName
289      * @return string
290      */
291     function _uniqueKey($tableName, $columnName)
292     {
293         return $this->_key($tableName, $columnName);
294     }
295
296     /**
297      * Get the index key name for a given column on this table
298      * @param $tableName
299      * @param $columnName
300      * @return string
301      */
302     function _key($tableName, $columnName)
303     {
304         return "{$tableName}_{$columnName}_idx";
305     }
306
307     /**
308      * MySQL doesn't take 'DROP CONSTRAINT', need to treat primary keys as
309      * if they were indexes here, but can use 'PRIMARY KEY' special name.
310      *
311      * @param array $phrase
312      */
313     function appendAlterDropPrimary(array &$phrase)
314     {
315         $phrase[] = 'DROP PRIMARY KEY';
316     }
317
318     /**
319      * MySQL doesn't take 'DROP CONSTRAINT', need to treat unique keys as
320      * if they were indexes here.
321      *
322      * @param array $phrase
323      * @param string $keyName MySQL
324      */
325     function appendAlterDropUnique(array &$phrase, $keyName)
326     {
327         $phrase[] = 'DROP INDEX ' . $keyName;
328     }
329
330     /**
331      * Throw some table metadata onto the ALTER TABLE if we have a mismatch
332      * in expected type, collation.
333      * @param array $phrase
334      * @param $tableName
335      * @param array $def
336      * @throws Exception
337      */
338     function appendAlterExtras(array &$phrase, $tableName, array $def)
339     {
340         // Check for table properties: make sure we're using a sane
341         // engine type and charset/collation.
342         // @fixme make the default engine configurable?
343         $oldProps = $this->getTableProperties($tableName, ['ENGINE', 'TABLE_COLLATION']);
344         $engine = $this->preferredEngine($def);
345         if (strtolower($oldProps['ENGINE']) != strtolower($engine)) {
346             $phrase[] = "ENGINE=$engine";
347         }
348         if (strtolower($oldProps['TABLE_COLLATION']) != 'utf8mb4_bin') {
349             $phrase[] = 'CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_bin';
350             $phrase[] = 'DEFAULT CHARACTER SET = utf8mb4';
351             $phrase[] = 'DEFAULT COLLATE = utf8mb4_bin';
352         }
353     }
354
355     /**
356      * Is this column a string type?
357      * @param array $cd
358      * @return bool
359      */
360     private function _isString(array $cd)
361     {
362         $strings = ['char', 'varchar', 'text'];
363         return in_array(strtolower($cd['type']), $strings);
364     }
365
366     /**
367      * Return the proper SQL for creating or
368      * altering a column.
369      *
370      * Appropriate for use in CREATE TABLE or
371      * ALTER TABLE statements.
372      *
373      * @param array $cd column to create
374      *
375      * @return string correct SQL for that column
376      */
377
378     function columnSql(array $cd)
379     {
380         $line = [];
381         $line[] = parent::columnSql($cd);
382
383         // This'll have been added from our transform of 'serial' type
384         if (!empty($cd['auto_increment'])) {
385             $line[] = 'auto_increment';
386         }
387
388         if (!empty($cd['description'])) {
389             $line[] = 'comment';
390             $line[] = $this->quoteValue($cd['description']);
391         }
392
393         return implode(' ', $line);
394     }
395
396     function mapType($column)
397     {
398         $map = [
399             'serial' => 'int',
400             'integer' => 'int',
401             'numeric' => 'decimal'
402         ];
403
404         $type = $column['type'];
405         if (isset($map[$type])) {
406             $type = $map[$type];
407         }
408
409         if (!empty($column['size'])) {
410             $size = $column['size'];
411             if ($type == 'int' &&
412                 in_array($size, ['tiny', 'small', 'medium', 'big'])) {
413                 $type = $size . $type;
414             } else if (in_array($type, ['blob', 'text']) &&
415                 in_array($size, ['tiny', 'medium', 'long'])) {
416                 $type = $size . $type;
417             }
418         }
419
420         return $type;
421     }
422
423     function typeAndSize($column)
424     {
425         if ($column['type'] == 'enum') {
426             $vals = array_map([$this, 'quote'], $column['enum']);
427             return 'enum(' . implode(',', $vals) . ')';
428         } else if ($this->_isString($column)) {
429             $col = parent::typeAndSize($column);
430             if (!empty($column['charset'])) {
431                 $col .= ' CHARSET ' . $column['charset'];
432             }
433             if (!empty($column['collate'])) {
434                 $col .= ' COLLATE ' . $column['collate'];
435             }
436             return $col;
437         } else {
438             return parent::typeAndSize($column);
439         }
440     }
441
442     /**
443      * Filter the given table definition array to match features available
444      * in this database.
445      *
446      * This lets us strip out unsupported things like comments, foreign keys,
447      * or type variants that we wouldn't get back from getTableDef().
448      *
449      * @param array $tableDef
450      * @return array
451      */
452     function filterDef(array $tableDef)
453     {
454         $version = $this->conn->getVersion();
455         foreach ($tableDef['fields'] as $name => &$col) {
456             if ($col['type'] == 'serial') {
457                 $col['type'] = 'int';
458                 $col['auto_increment'] = true;
459             }
460
461             $col['type'] = $this->mapType($col);
462             unset($col['size']);
463         }
464         if (!common_config('db', 'mysql_foreign_keys')) {
465             unset($tableDef['foreign keys']);
466         }
467         return $tableDef;
468     }
469 }