mysqlschema.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  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. * Database schema for MariaDB
  18. *
  19. * @category Database
  20. * @package GNUsocial
  21. * @author Evan Prodromou <evan@status.net>
  22. * @copyright 2019 Free Software Foundation, Inc http://www.fsf.org
  23. * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
  24. */
  25. defined('GNUSOCIAL') || die();
  26. /**
  27. * Class representing the database schema for MariaDB
  28. *
  29. * A class representing the database schema. Can be used to
  30. * manipulate the schema -- especially for plugins and upgrade
  31. * utilities.
  32. *
  33. * @copyright 2019 Free Software Foundation, Inc http://www.fsf.org
  34. * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
  35. */
  36. class MysqlSchema extends Schema
  37. {
  38. public static $_single = null;
  39. /**
  40. * Main public entry point. Use this to get
  41. * the singleton object.
  42. *
  43. * @param object|null $conn
  44. * @param string|null dummy param
  45. * @return Schema the (single) Schema object
  46. */
  47. public static function get($conn = null, $_ = 'mysql')
  48. {
  49. if (empty(self::$_single)) {
  50. self::$_single = new Schema($conn, 'mysql');
  51. }
  52. return self::$_single;
  53. }
  54. /**
  55. * Returns a TableDef object for the table
  56. * in the schema with the given name.
  57. *
  58. * Throws an exception if the table is not found.
  59. *
  60. * @param string $table Name of the table to get
  61. *
  62. * @return array of tabledef for that table.
  63. * @throws PEAR_Exception
  64. * @throws SchemaTableMissingException
  65. */
  66. public function getTableDef($table)
  67. {
  68. $def = [];
  69. $hasKeys = false;
  70. // Pull column data from INFORMATION_SCHEMA
  71. $columns = $this->fetchMetaInfo($table, 'COLUMNS', 'ORDINAL_POSITION');
  72. if (count($columns) == 0) {
  73. throw new SchemaTableMissingException("No such table: $table");
  74. }
  75. foreach ($columns as $row) {
  76. $name = $row['COLUMN_NAME'];
  77. $field = [];
  78. $type = $field['type'] = $row['DATA_TYPE'];
  79. switch ($type) {
  80. case 'char':
  81. case 'varchar':
  82. if (!is_null($row['CHARACTER_MAXIMUM_LENGTH'])) {
  83. $field['length'] = (int) $row['CHARACTER_MAXIMUM_LENGTH'];
  84. }
  85. break;
  86. case 'decimal':
  87. // Other int types may report these values, but they're irrelevant.
  88. // Just ignore them!
  89. if (!is_null($row['NUMERIC_PRECISION'])) {
  90. $field['precision'] = (int) $row['NUMERIC_PRECISION'];
  91. }
  92. if (!is_null($row['NUMERIC_SCALE'])) {
  93. $field['scale'] = (int) $row['NUMERIC_SCALE'];
  94. }
  95. break;
  96. case 'enum':
  97. $enum = preg_replace("/^enum\('(.+)'\)$/", '\1', $row['COLUMN_TYPE']);
  98. $field['enum'] = explode("','", $enum);
  99. break;
  100. }
  101. if ($row['IS_NULLABLE'] == 'NO') {
  102. $field['not null'] = true;
  103. }
  104. $col_default = $row['COLUMN_DEFAULT'];
  105. if (!is_null($col_default) && $col_default !== 'NULL') {
  106. if ($this->isNumericType($field)) {
  107. $field['default'] = (int) $col_default;
  108. } elseif ($col_default === 'CURRENT_TIMESTAMP'
  109. || $col_default === 'current_timestamp()') {
  110. // A hack for "datetime" fields
  111. // Skip "timestamp" as they get a CURRENT_TIMESTAMP default implicitly
  112. if ($type !== 'timestamp') {
  113. $field['default'] = 'CURRENT_TIMESTAMP';
  114. }
  115. } else {
  116. $match = "/^'(.*)'$/";
  117. if (preg_match($match, $col_default)) {
  118. $field['default'] = preg_replace($match, '\1', $col_default);
  119. } else {
  120. $field['default'] = $col_default;
  121. }
  122. }
  123. }
  124. if ($row['COLUMN_KEY'] !== null) {
  125. // We'll need to look up key info...
  126. $hasKeys = true;
  127. }
  128. if ($row['COLUMN_COMMENT'] !== null && $row['COLUMN_COMMENT'] != '') {
  129. $field['description'] = $row['COLUMN_COMMENT'];
  130. }
  131. $extra = $row['EXTRA'];
  132. if ($extra) {
  133. if (preg_match('/(^|\s)auto_increment(\s|$)/i', $extra)) {
  134. $field['auto_increment'] = true;
  135. }
  136. }
  137. if (!empty($row['COLLATION_NAME'])) {
  138. $field['collate'] = $row['COLLATION_NAME'];
  139. }
  140. $def['fields'][$name] = $field;
  141. }
  142. if ($hasKeys) {
  143. $key_info = $this->fetchKeyInfo($table);
  144. foreach ($key_info as $row) {
  145. $key_name = $row['key_name'];
  146. $cols = $row['cols'];
  147. switch ($row['key_type']) {
  148. case 'PRIMARY':
  149. $def['primary key'] = $cols;
  150. break;
  151. case 'UNIQUE':
  152. $def['unique keys'][$key_name] = $cols;
  153. break;
  154. case 'FULLTEXT':
  155. $def['fulltext indexes'][$key_name] = $cols;
  156. break;
  157. default:
  158. $def['indexes'][$key_name] = $cols;
  159. }
  160. }
  161. }
  162. $foreign_key_info = $this->fetchForeignKeyInfo($table);
  163. foreach ($foreign_key_info as $row) {
  164. $key_name = $row['key_name'];
  165. $cols = $row['cols'];
  166. $ref_table = $row['ref_table'];
  167. $def['foreign keys'][$key_name] = [$ref_table, $cols];
  168. }
  169. return $def;
  170. }
  171. /**
  172. * Pull the given table properties from INFORMATION_SCHEMA.
  173. * Most of the good stuff is MySQL extensions.
  174. *
  175. * @param $table
  176. * @param $props
  177. * @return array
  178. * @throws PEAR_Exception
  179. * @throws SchemaTableMissingException
  180. */
  181. public function getTableProperties($table, $props)
  182. {
  183. $data = $this->fetchMetaInfo($table, 'TABLES');
  184. if ($data) {
  185. return $data[0];
  186. } else {
  187. throw new SchemaTableMissingException("No such table: $table");
  188. }
  189. }
  190. /**
  191. * Pull some INFORMATION.SCHEMA data for the given table.
  192. *
  193. * @param string $table
  194. * @param $infoTable
  195. * @param null $orderBy
  196. * @return array of arrays
  197. * @throws PEAR_Exception
  198. */
  199. public function fetchMetaInfo($table, $infoTable, $orderBy = null)
  200. {
  201. $schema = $this->conn->dsn['database'];
  202. return $this->fetchQueryData(sprintf(
  203. <<<'END'
  204. SELECT * FROM INFORMATION_SCHEMA.%1$s
  205. WHERE TABLE_SCHEMA = '%2$s' AND TABLE_NAME = '%3$s'%4$s;
  206. END,
  207. $this->quoteIdentifier($infoTable),
  208. $schema,
  209. $table,
  210. ($orderBy ? " ORDER BY {$orderBy}" : '')
  211. ));
  212. }
  213. /**
  214. * Pull index and keys information for the given table.
  215. *
  216. * @param string $table
  217. * @return array of arrays
  218. * @throws PEAR_Exception
  219. */
  220. private function fetchKeyInfo(string $table): array
  221. {
  222. $schema = $this->conn->dsn['database'];
  223. $data = $this->fetchQueryData(
  224. <<<EOT
  225. SELECT INDEX_NAME AS `key_name`,
  226. CASE
  227. WHEN INDEX_NAME = 'PRIMARY' THEN 'PRIMARY'
  228. WHEN NON_UNIQUE IS NOT TRUE THEN 'UNIQUE'
  229. ELSE INDEX_TYPE
  230. END AS `key_type`,
  231. COLUMN_NAME AS `col`,
  232. SUB_PART AS `col_length`
  233. FROM INFORMATION_SCHEMA.STATISTICS
  234. WHERE TABLE_SCHEMA = '{$schema}' AND TABLE_NAME = '{$table}'
  235. ORDER BY `key_name`, `key_type`, SEQ_IN_INDEX;
  236. EOT
  237. );
  238. $rows = [];
  239. foreach ($data as $row) {
  240. $name = $row['key_name'];
  241. if (!is_null($row['col_length'])) {
  242. $row['col'] = [$row['col'], (int) $row['col_length']];
  243. }
  244. unset($row['col_length']);
  245. if (!array_key_exists($name, $rows)) {
  246. $row['cols'] = [$row['col']];
  247. unset($row['col']);
  248. $rows[$name] = $row;
  249. } else {
  250. $rows[$name]['cols'][] = $row['col'];
  251. }
  252. }
  253. return array_values($rows);
  254. }
  255. /**
  256. * Pull foreign key information for the given table.
  257. *
  258. * @param string $table
  259. * @return array array of arrays
  260. * @throws PEAR_Exception
  261. */
  262. private function fetchForeignKeyInfo(string $table): array
  263. {
  264. $schema = $this->conn->dsn['database'];
  265. $data = $this->fetchQueryData(
  266. <<<END
  267. SELECT CONSTRAINT_NAME AS `key_name`,
  268. COLUMN_NAME AS `col`,
  269. REFERENCED_TABLE_NAME AS `ref_table`,
  270. REFERENCED_COLUMN_NAME AS `ref_col`
  271. FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
  272. WHERE TABLE_SCHEMA = '{$schema}'
  273. AND TABLE_NAME = '{$table}'
  274. AND REFERENCED_TABLE_SCHEMA = '{$schema}'
  275. ORDER BY `key_name`, ORDINAL_POSITION;
  276. END
  277. );
  278. $rows = [];
  279. foreach ($data as $row) {
  280. $name = $row['key_name'];
  281. if (!array_key_exists($name, $rows)) {
  282. $row['cols'] = [$row['col'] => $row['ref_col']];
  283. unset($row['col']);
  284. unset($row['ref_col']);
  285. $rows[$name] = $row;
  286. } else {
  287. $rows[$name]['cols'][$row['col']] = $row['ref_col'];
  288. }
  289. }
  290. return array_values($rows);
  291. }
  292. /**
  293. * Append an SQL statement with an index definition for a full-text search
  294. * index over one or more columns on a table.
  295. *
  296. * @param array $statements
  297. * @param string $table
  298. * @param string $name
  299. * @param array $def
  300. */
  301. public function appendCreateFulltextIndex(array &$statements, $table, $name, array $def)
  302. {
  303. $statements[] = "CREATE FULLTEXT INDEX $name ON $table " . $this->buildIndexList($def);
  304. }
  305. /**
  306. * Append an SQL statement with an index definition for an advisory
  307. * index over one or more columns on a table.
  308. *
  309. * @param array $statements
  310. * @param string $table
  311. * @param string $name
  312. * @param array $def
  313. */
  314. public function appendCreateIndex(array &$statements, $table, $name, array $def)
  315. {
  316. $statements[] = "ALTER TABLE {$this->quoteIdentifier($table)} "
  317. . "ADD INDEX {$name} {$this->buildIndexList($def)}";
  318. }
  319. /**
  320. * Close out a 'create table' SQL statement.
  321. *
  322. * @param string $name
  323. * @param array $def
  324. * @return string;
  325. *
  326. */
  327. public function endCreateTable($name, array $def)
  328. {
  329. $engine = $this->preferredEngine($def);
  330. return ") ENGINE=$engine CHARACTER SET utf8mb4 COLLATE utf8mb4_bin";
  331. }
  332. public function preferredEngine($def)
  333. {
  334. return 'InnoDB';
  335. }
  336. /**
  337. * Append phrase(s) to an array of partial ALTER TABLE chunks in order
  338. * to alter the given column from its old state to a new one.
  339. *
  340. * @param array $phrase
  341. * @param string $columnName
  342. * @param array $old previous column definition as found in DB
  343. * @param array $cd current column definition
  344. */
  345. public function appendAlterModifyColumn(
  346. array &$phrase,
  347. string $columnName,
  348. array $old,
  349. array $cd
  350. ): void {
  351. $phrase[] = 'MODIFY COLUMN ' . $this->quoteIdentifier($columnName)
  352. . ' ' . $this->columnSql($columnName, $cd);
  353. }
  354. /**
  355. * MySQL doesn't take 'DROP CONSTRAINT', need to treat primary keys as
  356. * if they were indexes here, but can use 'PRIMARY KEY' special name.
  357. *
  358. * @param array $phrase
  359. */
  360. public function appendAlterDropPrimary(array &$phrase, string $tableName)
  361. {
  362. $phrase[] = 'DROP PRIMARY KEY';
  363. }
  364. /**
  365. * MySQL doesn't take 'DROP CONSTRAINT', need to treat unique keys as
  366. * if they were indexes here.
  367. *
  368. * @param array $phrase
  369. * @param string $keyName MySQL
  370. */
  371. public function appendAlterDropUnique(array &$phrase, $keyName)
  372. {
  373. $phrase[] = 'DROP INDEX ' . $keyName;
  374. }
  375. public function appendAlterDropForeign(array &$phrase, $keyName)
  376. {
  377. $phrase[] = 'DROP FOREIGN KEY ' . $keyName;
  378. }
  379. /**
  380. * Throw some table metadata onto the ALTER TABLE if we have a mismatch
  381. * in expected type, collation.
  382. * @param array $phrase
  383. * @param $tableName
  384. * @param array $def
  385. * @throws Exception
  386. */
  387. public function appendAlterExtras(array &$phrase, $tableName, array $def)
  388. {
  389. // Check for table properties: make sure we're using a sane
  390. // engine type and collation.
  391. // @fixme make the default engine configurable?
  392. $oldProps = $this->getTableProperties($tableName, ['ENGINE', 'TABLE_COLLATION']);
  393. $engine = $this->preferredEngine($def);
  394. if (strtolower($oldProps['ENGINE']) != strtolower($engine)) {
  395. $phrase[] = "ENGINE=$engine";
  396. }
  397. if (strtolower($oldProps['TABLE_COLLATION']) != 'utf8mb4_bin') {
  398. $phrase[] = 'CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_bin';
  399. $phrase[] = 'DEFAULT CHARACTER SET = utf8mb4';
  400. $phrase[] = 'DEFAULT COLLATE = utf8mb4_bin';
  401. }
  402. }
  403. /**
  404. * Append an SQL statement to drop an index from a table.
  405. * Note that in MariaDB index names are relation-specific.
  406. *
  407. * @param array $statements
  408. * @param string $table
  409. * @param string $name
  410. */
  411. public function appendDropIndex(array &$statements, $table, $name)
  412. {
  413. $statements[] = "ALTER TABLE {$this->quoteIdentifier($table)} "
  414. . "DROP INDEX {$name}";
  415. }
  416. private function isNumericType(array $cd): bool
  417. {
  418. $ints = array_map(
  419. function ($s) {
  420. return $s . 'int';
  421. },
  422. ['tiny', 'small', 'medium', 'big']
  423. );
  424. $ints = array_merge($ints, ['int', 'numeric', 'serial']);
  425. return in_array(strtolower($cd['type']), $ints);
  426. }
  427. /**
  428. * Return the proper SQL for creating or
  429. * altering a column.
  430. *
  431. * Appropriate for use in CREATE TABLE or
  432. * ALTER TABLE statements.
  433. *
  434. * @param string $name column name to create
  435. * @param array $cd column to create
  436. *
  437. * @return string correct SQL for that column
  438. */
  439. public function columnSql(string $name, array $cd)
  440. {
  441. $line = [];
  442. $line[] = parent::columnSql($name, $cd);
  443. // This'll have been added from our transform of "serial" type
  444. if (!empty($cd['auto_increment'])) {
  445. $line[] = 'AUTO_INCREMENT';
  446. }
  447. if (!empty($cd['description'])) {
  448. $line[] = 'COMMENT';
  449. $line[] = $this->quoteValue($cd['description']);
  450. }
  451. return implode(' ', $line);
  452. }
  453. public function mapType($column)
  454. {
  455. $map = [
  456. 'integer' => 'int',
  457. 'numeric' => 'decimal',
  458. 'blob' => 'longblob',
  459. ];
  460. $type = $column['type'];
  461. if (array_key_exists($type, $map)) {
  462. $type = $map[$type];
  463. }
  464. $size = $column['size'] ?? null;
  465. switch ($type) {
  466. case 'int':
  467. if (in_array($size, ['tiny', 'small', 'medium', 'big'])) {
  468. $type = $size . $type;
  469. }
  470. break;
  471. case 'float':
  472. if ($size === 'big') {
  473. $type = 'double';
  474. }
  475. break;
  476. case 'text':
  477. if (in_array($size, ['tiny', 'medium', 'long'])) {
  478. $type = $size . $type;
  479. }
  480. break;
  481. }
  482. return $type;
  483. }
  484. /**
  485. * Collation in MariaDB format from our format
  486. *
  487. * @param string $collate
  488. * @return string
  489. */
  490. protected function collationToMySQL(string $collate): string
  491. {
  492. if (!in_array($collate, [
  493. 'utf8_bin',
  494. 'utf8_general_cs',
  495. 'utf8_general_ci',
  496. ])) {
  497. common_log(
  498. LOG_ERR,
  499. 'Collation not supported: "' . $collate . '"'
  500. );
  501. $collate = 'utf8_bin';
  502. }
  503. if (substr($collate, 0, 13) === 'utf8_general_') {
  504. $collate = 'utf8mb4_unicode_' . substr($collate, 13);
  505. } elseif (substr($collate, 0, 5) === 'utf8_') {
  506. $collate = 'utf8mb4_' . substr($collate, 5);
  507. }
  508. return $collate;
  509. }
  510. public function typeAndSize(string $name, array $column)
  511. {
  512. if ($column['type'] === 'enum') {
  513. $vals = [];
  514. foreach ($column['enum'] as &$val) {
  515. $vals[] = "'{$val}'";
  516. }
  517. return 'enum(' . implode(',', $vals) . ')';
  518. } elseif ($this->isStringType($column)) {
  519. $col = parent::typeAndSize($name, $column);
  520. if (!empty($column['collate'])) {
  521. $col .= ' COLLATE ' . $column['collate'];
  522. }
  523. return $col;
  524. } else {
  525. return parent::typeAndSize($name, $column);
  526. }
  527. }
  528. /**
  529. * Filter the given table definition array to match features available
  530. * in this database.
  531. *
  532. * This lets us strip out unsupported things like comments, foreign keys,
  533. * or type variants that we wouldn't get back from getTableDef().
  534. *
  535. * @param string $tableName
  536. * @param array $tableDef
  537. * @return array
  538. */
  539. public function filterDef(string $tableName, array $tableDef)
  540. {
  541. $tableDef = parent::filterDef($tableName, $tableDef);
  542. foreach ($tableDef['fields'] as $name => &$col) {
  543. switch ($col['type']) {
  544. case 'serial':
  545. $col['type'] = 'int';
  546. $col['auto_increment'] = true;
  547. break;
  548. case 'bool':
  549. $col['type'] = 'int';
  550. $col['size'] = 'tiny';
  551. $col['default'] = (int) $col['default'];
  552. break;
  553. }
  554. if (!empty($col['collate'])) {
  555. $col['collate'] = $this->collationToMySQL($col['collate']);
  556. }
  557. $col['type'] = $this->mapType($col);
  558. unset($col['size']);
  559. }
  560. return $tableDef;
  561. }
  562. }