2 // This file is part of GNU social - https://www.gnu.org/software/social
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.
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.
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/>.
18 * Database schema for MariaDB
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
27 defined('GNUSOCIAL') || die();
30 * Class representing the database schema for MariaDB
32 * A class representing the database schema. Can be used to
33 * manipulate the schema -- especially for plugins and upgrade
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
39 class MysqlSchema extends Schema
41 static $_single = null;
42 protected $conn = null;
45 * Main public entry point. Use this to get
46 * the singleton object.
49 * @return Schema the (single) Schema object
52 static function get($conn = null)
54 if (empty(self::$_single)) {
55 self::$_single = new Schema($conn);
57 return self::$_single;
61 * Returns a TableDef object for the table
62 * in the schema with the given name.
64 * Throws an exception if the table is not found.
66 * @param string $table Name of the table to get
68 * @return array of tabledef for that table.
69 * @throws PEAR_Exception
70 * @throws SchemaTableMissingException
73 public function getTableDef($table)
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");
84 foreach ($columns as $row) {
86 $name = $row['COLUMN_NAME'];
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'];
93 if ($type == 'char' || $type == 'varchar') {
94 if ($row['CHARACTER_MAXIMUM_LENGTH'] !== null) {
95 $field['length'] = intval($row['CHARACTER_MAXIMUM_LENGTH']);
98 if ($type == 'decimal') {
99 // Other int types may report these values, but they're irrelevant.
101 if ($row['NUMERIC_PRECISION'] !== null) {
102 $field['precision'] = intval($row['NUMERIC_PRECISION']);
104 if ($row['NUMERIC_SCALE'] !== null) {
105 $field['scale'] = intval($row['NUMERIC_SCALE']);
108 if ($row['IS_NULLABLE'] == 'NO') {
109 $field['not null'] = true;
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
116 $field['default'] = $row['COLUMN_DEFAULT'];
117 if ($this->isNumericType($type)) {
118 $field['default'] = intval($field['default']);
122 if ($row['COLUMN_KEY'] !== null) {
123 // We'll need to look up key info...
126 if ($row['COLUMN_COMMENT'] !== null && $row['COLUMN_COMMENT'] != '') {
127 $field['description'] = $row['COLUMN_COMMENT'];
130 $extra = $row['EXTRA'];
132 if (preg_match('/(^|\s)auto_increment(\s|$)/i', $extra)) {
133 $field['auto_increment'] = true;
135 // $row['EXTRA'] may contain 'on update CURRENT_TIMESTAMP'
136 // ^ ...... how to specify?
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'];
145 $def['fields'][$name] = $field;
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.
153 // Let's go old school and use SHOW INDEX :D
155 $keyInfo = $this->fetchIndexInfo($table);
158 foreach ($keyInfo as $row) {
159 $name = $row['Key_name'];
160 $column = $row['Column_name'];
162 if (!isset($keys[$name])) {
165 $keys[$name][] = $column;
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';
176 $keyTypes[$name] = $type;
179 foreach ($keyTypes as $name => $type) {
180 if ($type == 'primary key') {
181 // there can be only one
182 $def[$type] = $keys[$name];
184 $def[$type][$name] = $keys[$name];
192 * Pull the given table properties from INFORMATION_SCHEMA.
193 * Most of the good stuff is MySQL extensions.
198 * @throws PEAR_Exception
199 * @throws SchemaTableMissingException
202 function getTableProperties($table, $props)
204 $data = $this->fetchMetaInfo($table, 'TABLES');
208 throw new SchemaTableMissingException("No such table: $table");
213 * Pull some INFORMATION.SCHEMA data for the given table.
215 * @param string $table
217 * @param null $orderBy
218 * @return array of arrays
219 * @throws PEAR_Exception
221 function fetchMetaInfo($table, $infoTable, $orderBy = null)
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);
228 $sql .= ' ORDER BY ' . $orderBy;
230 return $this->fetchQueryData($sql);
234 * Pull 'SHOW INDEX' data for the given table.
236 * @param string $table
237 * @return array of arrays
238 * @throws PEAR_Exception
240 function fetchIndexInfo($table)
242 $query = "SHOW INDEX FROM `%s`";
243 $sql = sprintf($query, $table);
244 return $this->fetchQueryData($sql);
248 * Append an SQL statement with an index definition for a full-text search
249 * index over one or more columns on a table.
251 * @param array $statements
252 * @param string $table
253 * @param string $name
256 function appendCreateFulltextIndex(array &$statements, $table, $name, array $def)
258 $statements[] = "CREATE FULLTEXT INDEX $name ON $table " . $this->buildIndexList($def);
262 * Close out a 'create table' SQL statement.
264 * @param string $name
269 function endCreateTable($name, array $def)
271 $engine = $this->preferredEngine($def);
272 return ") ENGINE=$engine CHARACTER SET utf8mb4 COLLATE utf8mb4_bin";
275 function preferredEngine($def)
277 /* MyISAM is no longer required for fulltext indexes, fortunately
278 if (!empty($def['fulltext indexes'])) {
286 * Get the unique index key name for a given column on this table
291 function _uniqueKey($tableName, $columnName)
293 return $this->_key($tableName, $columnName);
297 * Get the index key name for a given column on this table
302 function _key($tableName, $columnName)
304 return "{$tableName}_{$columnName}_idx";
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.
311 * @param array $phrase
313 function appendAlterDropPrimary(array &$phrase)
315 $phrase[] = 'DROP PRIMARY KEY';
319 * MySQL doesn't take 'DROP CONSTRAINT', need to treat unique keys as
320 * if they were indexes here.
322 * @param array $phrase
323 * @param string $keyName MySQL
325 function appendAlterDropUnique(array &$phrase, $keyName)
327 $phrase[] = 'DROP INDEX ' . $keyName;
331 * Throw some table metadata onto the ALTER TABLE if we have a mismatch
332 * in expected type, collation.
333 * @param array $phrase
338 function appendAlterExtras(array &$phrase, $tableName, array $def)
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";
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';
356 * Is this column a string type?
360 private function _isString(array $cd)
362 $strings = ['char', 'varchar', 'text'];
363 return in_array(strtolower($cd['type']), $strings);
367 * Return the proper SQL for creating or
370 * Appropriate for use in CREATE TABLE or
371 * ALTER TABLE statements.
373 * @param array $cd column to create
375 * @return string correct SQL for that column
378 function columnSql(array $cd)
381 $line[] = parent::columnSql($cd);
383 // This'll have been added from our transform of 'serial' type
384 if (!empty($cd['auto_increment'])) {
385 $line[] = 'auto_increment';
388 if (!empty($cd['description'])) {
390 $line[] = $this->quoteValue($cd['description']);
393 return implode(' ', $line);
396 function mapType($column)
401 'numeric' => 'decimal'
404 $type = $column['type'];
405 if (isset($map[$type])) {
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;
423 function typeAndSize($column)
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'];
433 if (!empty($column['collate'])) {
434 $col .= ' COLLATE ' . $column['collate'];
438 return parent::typeAndSize($column);
443 * Filter the given table definition array to match features available
446 * This lets us strip out unsupported things like comments, foreign keys,
447 * or type variants that we wouldn't get back from getTableDef().
449 * @param array $tableDef
452 function filterDef(array $tableDef)
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;
461 $col['type'] = $this->mapType($col);
464 if (!common_config('db', 'mysql_foreign_keys')) {
465 unset($tableDef['foreign keys']);