mysql.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  1. <?php
  2. /**
  3. * This file is part of the ForkBB <https://github.com/forkbb>.
  4. *
  5. * @copyright (c) Visman <mio.visman@yandex.ru, https://github.com/MioVisman>
  6. * @license The MIT License (MIT)
  7. */
  8. declare(strict_types=1);
  9. namespace ForkBB\Core\DB;
  10. use ForkBB\Core\DB;
  11. use PDO;
  12. use PDOStatement;
  13. use PDOException;
  14. class Mysql
  15. {
  16. /**
  17. * @var DB
  18. */
  19. protected $db;
  20. /**
  21. * Префикс для таблиц базы
  22. * @var string
  23. */
  24. protected $dbPrefix;
  25. /**
  26. * Массив замены типов полей таблицы
  27. * @var array
  28. */
  29. protected $dbTypeRepl = [
  30. '%^SERIAL$%i' => 'INT(10) UNSIGNED AUTO_INCREMENT',
  31. ];
  32. /**
  33. * Подстановка типов полей для карты БД
  34. * @var array
  35. */
  36. protected $types = [
  37. 'bool' => 'b',
  38. 'boolean' => 'b',
  39. 'tinyint' => 'i',
  40. 'smallint' => 'i',
  41. 'mediumint' => 'i',
  42. 'int' => 'i',
  43. 'integer' => 'i',
  44. 'bigint' => 'i',
  45. 'decimal' => 'i',
  46. 'dec' => 'i',
  47. 'float' => 'i',
  48. 'double' => 'i',
  49. ];
  50. public function __construct(DB $db, string $prefix)
  51. {
  52. $this->db = $db;
  53. $this->testStr($prefix);
  54. $this->dbPrefix = $prefix;
  55. }
  56. /**
  57. * Перехват неизвестных методов
  58. */
  59. public function __call(string $name, array $args)
  60. {
  61. throw new PDOException("Method '{$name}' not found in DB driver.");
  62. }
  63. /**
  64. * Проверяет строку на допустимые символы
  65. */
  66. protected function testStr(string $str): void
  67. {
  68. if (\preg_match('%[^a-zA-Z0-9_]%', $str)) {
  69. throw new PDOException("Name '{$str}' have bad characters.");
  70. }
  71. }
  72. /**
  73. * Операции над полями индексов: проверка, замена
  74. */
  75. protected function replIdxs(array $arr): string
  76. {
  77. foreach ($arr as &$value) {
  78. if (\preg_match('%^(.*)\s*(\(\d+\))$%', $value, $matches)) {
  79. $this->testStr($matches[1]);
  80. $value = "`{$matches[1]}`{$matches[2]}";
  81. } else {
  82. $this->testStr($value);
  83. $value = "`{$value}`";
  84. }
  85. unset($value);
  86. }
  87. return \implode(',', $arr);
  88. }
  89. /**
  90. * Замена типа поля в соответствии с dbTypeRepl
  91. */
  92. protected function replType(string $type): string
  93. {
  94. return \preg_replace(\array_keys($this->dbTypeRepl), \array_values($this->dbTypeRepl), $type);
  95. }
  96. /**
  97. * Конвертирует данные в строку для DEFAULT
  98. */
  99. protected function convToStr(/* mixed */ $data): string
  100. {
  101. if (\is_string($data)) {
  102. return $this->db->quote($data);
  103. } elseif (\is_numeric($data)) {
  104. return (string) $data;
  105. } elseif (\is_bool($data)) {
  106. return $data ? 'true' : 'false';
  107. } else {
  108. throw new PDOException('Invalid data type for DEFAULT.');
  109. }
  110. }
  111. /**
  112. * Проверяет наличие таблицы в базе
  113. */
  114. public function tableExists(string $table, bool $noPrefix = false): bool
  115. {
  116. $table = ($noPrefix ? '' : $this->dbPrefix) . $table;
  117. try {
  118. $vars = [
  119. ':table' => $table,
  120. ];
  121. $query = 'SELECT 1
  122. FROM INFORMATION_SCHEMA.TABLES
  123. WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?s:table';
  124. $stmt = $this->db->query($query, $vars);
  125. $result = $stmt->fetch();
  126. $stmt->closeCursor();
  127. } catch (PDOException $e) {
  128. return false;
  129. }
  130. return ! empty($result);
  131. }
  132. /**
  133. * Проверяет наличие поля в таблице
  134. */
  135. public function fieldExists(string $table, string $field, bool $noPrefix = false): bool
  136. {
  137. $table = ($noPrefix ? '' : $this->dbPrefix) . $table;
  138. try {
  139. $vars = [
  140. ':table' => $table,
  141. ':field' => $field,
  142. ];
  143. $query = 'SELECT 1
  144. FROM INFORMATION_SCHEMA.COLUMNS
  145. WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?s:table AND COLUMN_NAME = ?s:field';
  146. $stmt = $this->db->query($query, $vars);
  147. $result = $stmt->fetch();
  148. $stmt->closeCursor();
  149. } catch (PDOException $e) {
  150. return false;
  151. }
  152. return ! empty($result);
  153. }
  154. /**
  155. * Проверяет наличие индекса в таблице
  156. */
  157. public function indexExists(string $table, string $index, bool $noPrefix = false): bool
  158. {
  159. $table = ($noPrefix ? '' : $this->dbPrefix) . $table;
  160. $index = 'PRIMARY' == $index ? $index : $table . '_' . $index;
  161. try {
  162. $vars = [
  163. ':table' => $table,
  164. ':index' => $index,
  165. ];
  166. $query = 'SELECT 1
  167. FROM INFORMATION_SCHEMA.STATISTICS
  168. WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?s:table AND INDEX_NAME = ?s:index';
  169. $stmt = $this->db->query($query, $vars);
  170. $result = $stmt->fetch();
  171. $stmt->closeCursor();
  172. } catch (PDOException $e) {
  173. return false;
  174. }
  175. return ! empty($result);
  176. }
  177. /**
  178. * Создает таблицу
  179. */
  180. public function createTable(string $table, array $schema, bool $noPrefix = false): bool
  181. {
  182. $this->testStr($table);
  183. $table = ($noPrefix ? '' : $this->dbPrefix) . $table;
  184. $query = "CREATE TABLE IF NOT EXISTS `{$table}` (";
  185. foreach ($schema['FIELDS'] as $field => $data) {
  186. $this->testStr($field);
  187. // имя и тип
  188. $query .= "`{$field}` " . $this->replType($data[0]);
  189. // сравнение
  190. if (\preg_match('%^(?:CHAR|VARCHAR|TINYTEXT|TEXT|MEDIUMTEXT|LONGTEXT|ENUM|SET)%i', $data[0])) {
  191. $query .= ' CHARACTER SET utf8mb4 COLLATE utf8mb4_';
  192. if (
  193. isset($data[3])
  194. && \is_string($data[3])
  195. ) {
  196. $this->testStr($data[3]);
  197. $query .= $data[3];
  198. } else {
  199. $query .= 'unicode_ci';
  200. }
  201. }
  202. // не NULL
  203. if (empty($data[1])) {
  204. $query .= ' NOT NULL';
  205. }
  206. // значение по умолчанию
  207. if (isset($data[2])) {
  208. $query .= ' DEFAULT ' . $this->convToStr($data[2]);
  209. }
  210. $query .= ', ';
  211. }
  212. if (isset($schema['PRIMARY KEY'])) {
  213. $query .= 'PRIMARY KEY (' . $this->replIdxs($schema['PRIMARY KEY']) . '), ';
  214. }
  215. if (isset($schema['UNIQUE KEYS'])) {
  216. foreach ($schema['UNIQUE KEYS'] as $key => $fields) {
  217. $this->testStr($key);
  218. $query .= "UNIQUE `{$table}_{$key}` (" . $this->replIdxs($fields) . '), ';
  219. }
  220. }
  221. if (isset($schema['INDEXES'])) {
  222. foreach ($schema['INDEXES'] as $index => $fields) {
  223. $this->testStr($index);
  224. $query .= "INDEX `{$table}_{$index}` (" . $this->replIdxs($fields) . '), ';
  225. }
  226. }
  227. if (isset($schema['ENGINE'])) {
  228. $engine = $schema['ENGINE'];
  229. } else {
  230. // при отсутствии типа таблицы он определяется на основании типов других таблиц в базе
  231. $prefix = \str_replace('_', '\\_', $this->dbPrefix);
  232. $stmt = $this->db->query("SHOW TABLE STATUS LIKE '{$prefix}%'");
  233. $engine = [];
  234. while ($row = $stmt->fetch()) {
  235. if (isset($engine[$row['Engine']])) {
  236. ++$engine[$row['Engine']];
  237. } else {
  238. $engine[$row['Engine']] = 1;
  239. }
  240. }
  241. // в базе нет таблиц
  242. if (empty($engine)) {
  243. $engine = 'MyISAM';
  244. } else {
  245. \arsort($engine);
  246. // берем тип наиболее часто встречаемый у имеющихся таблиц
  247. $engine = \array_keys($engine);
  248. $engine = \array_shift($engine);
  249. }
  250. }
  251. $this->testStr($engine);
  252. $query = \rtrim($query, ', ') . ") ENGINE={$engine} CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci";
  253. return false !== $this->db->exec($query);
  254. }
  255. /**
  256. * Удаляет таблицу
  257. */
  258. public function dropTable(string $table, bool $noPrefix = false): bool
  259. {
  260. $this->testStr($table);
  261. $table = ($noPrefix ? '' : $this->dbPrefix) . $table;
  262. return false !== $this->db->exec("DROP TABLE IF EXISTS `{$table}`");
  263. }
  264. /**
  265. * Переименовывает таблицу
  266. */
  267. public function renameTable(string $old, string $new, bool $noPrefix = false): bool
  268. {
  269. $this->testStr($old);
  270. $this->testStr($new);
  271. if (
  272. $this->tableExists($new, $noPrefix)
  273. && ! $this->tableExists($old, $noPrefix)
  274. ) {
  275. return true;
  276. }
  277. $old = ($noPrefix ? '' : $this->dbPrefix) . $old;
  278. $new = ($noPrefix ? '' : $this->dbPrefix) . $new;
  279. return false !== $this->db->exec("ALTER TABLE `{$old}` RENAME TO `{$new}`");
  280. }
  281. /**
  282. * Добавляет поле в таблицу
  283. */
  284. public function addField(string $table, string $field, string $type, bool $allowNull, /* mixed */ $default = null, string $after = null, bool $noPrefix = false): bool
  285. {
  286. $this->testStr($table);
  287. $this->testStr($field);
  288. if ($this->fieldExists($table, $field, $noPrefix)) {
  289. return true;
  290. }
  291. $table = ($noPrefix ? '' : $this->dbPrefix) . $table;
  292. $query = "ALTER TABLE `{$table}` ADD `{$field}` " . $this->replType($type);
  293. if (! $allowNull) {
  294. $query .= ' NOT NULL';
  295. }
  296. if (null !== $default) {
  297. $query .= ' DEFAULT ' . $this->convToStr($default);
  298. }
  299. if (null !== $after) {
  300. $this->testStr($after);
  301. $query .= " AFTER `{$after}`";
  302. }
  303. return false !== $this->db->exec($query);
  304. }
  305. /**
  306. * Модифицирует поле в таблице
  307. */
  308. public function alterField(string $table, string $field, string $type, bool $allowNull, /* mixed */ $default = null, string $after = null, bool $noPrefix = false): bool
  309. {
  310. $this->testStr($table);
  311. $this->testStr($field);
  312. $table = ($noPrefix ? '' : $this->dbPrefix) . $table;
  313. $query = "ALTER TABLE `{$table}` MODIFY `{$field}` " . $this->replType($type);
  314. if (! $allowNull) {
  315. $query .= ' NOT NULL';
  316. }
  317. if (null !== $default) {
  318. $query .= ' DEFAULT ' . $this->convToStr($default);
  319. }
  320. if (null !== $after) {
  321. $this->testStr($after);
  322. $query .= " AFTER `{$after}`";
  323. }
  324. return false !== $this->db->exec($query);
  325. }
  326. /**
  327. * Удаляет поле из таблицы
  328. */
  329. public function dropField(string $table, string $field, bool $noPrefix = false): bool
  330. {
  331. $this->testStr($table);
  332. $this->testStr($field);
  333. if (! $this->fieldExists($table, $field, $noPrefix)) {
  334. return true;
  335. }
  336. $table = ($noPrefix ? '' : $this->dbPrefix) . $table;
  337. return false !== $this->db->exec("ALTER TABLE `{$table}` DROP COLUMN `{$field}`");
  338. }
  339. /**
  340. * Переименование поля в таблице
  341. */
  342. public function renameField(string $table, string $old, string $new, bool $noPrefix = false): bool
  343. {
  344. $this->testStr($table);
  345. $this->testStr($old);
  346. $this->testStr($new);
  347. if (
  348. ! $this->fieldExists($table, $old, $noPrefix)
  349. || $this->fieldExists($table, $new, $noPrefix)
  350. ) {
  351. return false;
  352. }
  353. $table = ($noPrefix ? '' : $this->dbPrefix) . $table;
  354. try {
  355. $vars = [
  356. ':table' => $table,
  357. ':field' => $old,
  358. ];
  359. $query = 'SELECT COLUMN_DEFAULT, IS_NULLABLE, COLUMN_TYPE
  360. FROM INFORMATION_SCHEMA.COLUMNS
  361. WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?s:table AND COLUMN_NAME = ?s:field';
  362. $stmt = $this->db->query($query, $vars);
  363. $result = $stmt->fetch();
  364. $stmt->closeCursor();
  365. $type = $result['COLUMN_TYPE'];
  366. $allowNull = 'YES' == $result['IS_NULLABLE'];
  367. $default = $result['COLUMN_DEFAULT'];
  368. } catch (PDOException $e) {
  369. return false;
  370. }
  371. $query = "ALTER TABLE `{$table}` CHANGE COLUMN `{$old}` `{$new}` " . $this->replType($type);
  372. if (! $allowNull) {
  373. $query .= ' NOT NULL';
  374. }
  375. if (null !== $default) {
  376. $query .= ' DEFAULT ' . $this->convToStr($default);
  377. }
  378. return false !== $this->db->exec($query);
  379. }
  380. /**
  381. * Добавляет индекс в таблицу
  382. */
  383. public function addIndex(string $table, string $index, array $fields, bool $unique = false, bool $noPrefix = false): bool
  384. {
  385. $this->testStr($table);
  386. if ($this->indexExists($table, $index, $noPrefix)) {
  387. return true;
  388. }
  389. $table = ($noPrefix ? '' : $this->dbPrefix) . $table;
  390. $query = "ALTER TABLE `{$table}` ADD ";
  391. if ('PRIMARY' == $index) {
  392. $query .= 'PRIMARY KEY';
  393. } else {
  394. $index = $table . '_' . $index;
  395. $this->testStr($index);
  396. if ($unique) {
  397. $query .= "UNIQUE `{$index}`";
  398. } else {
  399. $query .= "INDEX `{$index}`";
  400. }
  401. }
  402. $query .= ' (' . $this->replIdxs($fields) . ')';
  403. return false !== $this->db->exec($query);
  404. }
  405. /**
  406. * Удаляет индекс из таблицы
  407. */
  408. public function dropIndex(string $table, string $index, bool $noPrefix = false): bool
  409. {
  410. $this->testStr($table);
  411. if (! $this->indexExists($table, $index, $noPrefix)) {
  412. return true;
  413. }
  414. $table = ($noPrefix ? '' : $this->dbPrefix) . $table;
  415. $query = "ALTER TABLE `{$table}` ";
  416. if ('PRIMARY' == $index) {
  417. $query .= "DROP PRIMARY KEY";
  418. } else {
  419. $index = $table . '_' . $index;
  420. $this->testStr($index);
  421. $query .= "DROP INDEX `{$index}`";
  422. }
  423. return false !== $this->db->exec($query);
  424. }
  425. /**
  426. * Очищает таблицу
  427. */
  428. public function truncateTable(string $table, bool $noPrefix = false): bool
  429. {
  430. $this->testStr($table);
  431. $table = ($noPrefix ? '' : $this->dbPrefix) . $table;
  432. return false !== $this->db->exec("TRUNCATE TABLE `{$table}`");
  433. }
  434. /**
  435. * Возвращает статистику
  436. */
  437. public function statistics(): array
  438. {
  439. $prefix = str_replace('_', '\\_', $this->dbPrefix);
  440. $stmt = $this->db->query("SHOW TABLE STATUS LIKE '{$prefix}%'");
  441. $records = $size = 0;
  442. $engine = [];
  443. while ($row = $stmt->fetch()) {
  444. $records += $row['Rows'];
  445. $size += $row['Data_length'] + $row['Index_length'];
  446. if (isset($engine[$row['Engine']])) {
  447. ++$engine[$row['Engine']];
  448. } else {
  449. $engine[$row['Engine']] = 1;
  450. }
  451. }
  452. \arsort($engine);
  453. $tmp = [];
  454. foreach ($engine as $key => $val) {
  455. $tmp[] = "{$key}({$val})";
  456. }
  457. $other = [];
  458. $stmt = $this->db->query("SHOW VARIABLES LIKE 'character\\_set\\_%'");
  459. while ($row = $stmt->fetch(PDO::FETCH_NUM)) {
  460. $other[$row[0]] = $row[1];
  461. }
  462. return [
  463. 'db' => 'MySQL (PDO) ' . $this->db->getAttribute(PDO::ATTR_SERVER_VERSION) . ' : ' . implode(', ', $tmp),
  464. 'records' => $records,
  465. 'size' => $size,
  466. 'server info' => $this->db->getAttribute(PDO::ATTR_SERVER_INFO),
  467. ] + $other;
  468. }
  469. /**
  470. * Формирует карту базы данных
  471. */
  472. public function getMap(): array
  473. {
  474. $vars = [
  475. "{$this->dbPrefix}%",
  476. ];
  477. $query = 'SELECT TABLE_NAME, COLUMN_NAME, DATA_TYPE
  478. FROM INFORMATION_SCHEMA.COLUMNS
  479. WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME LIKE ?s';
  480. $stmt = $this->db->query($query, $vars);
  481. $result = [];
  482. $table = null;
  483. while ($row = $stmt->fetch()) {
  484. if ($table !== $row['TABLE_NAME']) {
  485. $table = $row['TABLE_NAME'];
  486. $tableNoPref = \substr($table, \strlen($this->dbPrefix));
  487. $result[$tableNoPref] = [];
  488. }
  489. $type = \strtolower($row['DATA_TYPE']);
  490. $result[$tableNoPref][$row['COLUMN_NAME']] = $this->types[$type] ?? 's';
  491. }
  492. return $result;
  493. }
  494. }