Mysql.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  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->nameCheck($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 nameCheck(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 tName(string $name): string
  76. {
  77. if ('::' === \substr($name, 0, 2)) {
  78. $name = $this->dbPrefix . \substr($name, 2);
  79. }
  80. $this->nameCheck($name);
  81. return $name;
  82. }
  83. /**
  84. * Операции над полями индексов: проверка, замена
  85. */
  86. protected function replIdxs(array $arr): string
  87. {
  88. foreach ($arr as &$value) {
  89. if (\preg_match('%^(.*)\s*(\(\d+\))$%', $value, $matches)) {
  90. $this->nameCheck($matches[1]);
  91. $value = "`{$matches[1]}`{$matches[2]}";
  92. } else {
  93. $this->nameCheck($value);
  94. $value = "`{$value}`";
  95. }
  96. }
  97. unset($value);
  98. return \implode(',', $arr);
  99. }
  100. /**
  101. * Замена типа поля в соответствии с dbTypeRepl
  102. */
  103. protected function replType(string $type): string
  104. {
  105. return \preg_replace(\array_keys($this->dbTypeRepl), \array_values($this->dbTypeRepl), $type);
  106. }
  107. /**
  108. * Конвертирует данные в строку для DEFAULT
  109. */
  110. protected function convToStr(/* mixed */ $data): string
  111. {
  112. if (\is_string($data)) {
  113. return $this->db->quote($data);
  114. } elseif (\is_numeric($data)) {
  115. return (string) $data;
  116. } elseif (\is_bool($data)) {
  117. return $data ? 'true' : 'false';
  118. } else {
  119. throw new PDOException('Invalid data type for DEFAULT.');
  120. }
  121. }
  122. /**
  123. * Формирует строку для одного поля таблицы
  124. */
  125. protected function buildColumn(string $name, array $data): string
  126. {
  127. $this->nameCheck($name);
  128. // имя и тип
  129. $query = '`' . $name . '` ' . $this->replType($data[0]);
  130. // сравнение
  131. if (\preg_match('%^(?:CHAR|VARCHAR|TINYTEXT|TEXT|MEDIUMTEXT|LONGTEXT|ENUM|SET)\b%i', $data[0])) {
  132. $query .= ' CHARACTER SET utf8mb4 COLLATE utf8mb4_';
  133. if (
  134. isset($data[3])
  135. && \is_string($data[3])
  136. ) {
  137. $this->nameCheck($data[3]);
  138. $query .= $data[3];
  139. } else {
  140. $query .= 'unicode_ci';
  141. }
  142. }
  143. // не NULL
  144. if (empty($data[1])) {
  145. $query .= ' NOT NULL';
  146. }
  147. // значение по умолчанию
  148. if (isset($data[2])) {
  149. $query .= ' DEFAULT ' . $this->convToStr($data[2]);
  150. }
  151. return $query;
  152. }
  153. /**
  154. * Проверяет наличие таблицы в базе
  155. */
  156. public function tableExists(string $table): bool
  157. {
  158. $vars = [
  159. ':tname' => $this->tName($table),
  160. ];
  161. $query = 'SELECT 1
  162. FROM INFORMATION_SCHEMA.TABLES
  163. WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?s:tname';
  164. $stmt = $this->db->query($query, $vars);
  165. $result = $stmt->fetch();
  166. $stmt->closeCursor();
  167. return ! empty($result);
  168. }
  169. /**
  170. * Проверяет наличие поля в таблице
  171. */
  172. public function fieldExists(string $table, string $field): bool
  173. {
  174. $vars = [
  175. ':tname' => $this->tName($table),
  176. ':fname' => $field,
  177. ];
  178. $query = 'SELECT 1
  179. FROM INFORMATION_SCHEMA.COLUMNS
  180. WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?s:tname AND COLUMN_NAME = ?s:fname';
  181. $stmt = $this->db->query($query, $vars);
  182. $result = $stmt->fetch();
  183. $stmt->closeCursor();
  184. return ! empty($result);
  185. }
  186. /**
  187. * Проверяет наличие индекса в таблице
  188. */
  189. public function indexExists(string $table, string $index): bool
  190. {
  191. $table = $this->tName($table);
  192. $vars = [
  193. ':tname' => $table,
  194. ':index' => 'PRIMARY' == $index ? $index : $table . '_' . $index,
  195. ];
  196. $query = 'SELECT 1
  197. FROM INFORMATION_SCHEMA.STATISTICS
  198. WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?s:tname AND INDEX_NAME = ?s:index';
  199. $stmt = $this->db->query($query, $vars);
  200. $result = $stmt->fetch();
  201. $stmt->closeCursor();
  202. return ! empty($result);
  203. }
  204. /**
  205. * Создает таблицу
  206. */
  207. public function createTable(string $table, array $schema): bool
  208. {
  209. $table = $this->tName($table);
  210. $query = "CREATE TABLE IF NOT EXISTS `{$table}` (";
  211. foreach ($schema['FIELDS'] as $field => $data) {
  212. $query .= $this->buildColumn($field, $data) . ', ';
  213. }
  214. if (isset($schema['PRIMARY KEY'])) {
  215. $query .= 'PRIMARY KEY (' . $this->replIdxs($schema['PRIMARY KEY']) . '), ';
  216. }
  217. if (isset($schema['UNIQUE KEYS'])) {
  218. foreach ($schema['UNIQUE KEYS'] as $key => $fields) {
  219. $this->nameCheck($key);
  220. $query .= "UNIQUE `{$table}_{$key}` (" . $this->replIdxs($fields) . '), ';
  221. }
  222. }
  223. if (isset($schema['INDEXES'])) {
  224. foreach ($schema['INDEXES'] as $index => $fields) {
  225. $this->nameCheck($index);
  226. $query .= "INDEX `{$table}_{$index}` (" . $this->replIdxs($fields) . '), ';
  227. }
  228. }
  229. if (isset($schema['ENGINE'])) {
  230. $engine = $schema['ENGINE'];
  231. } else {
  232. // при отсутствии типа таблицы он определяется на основании типов других таблиц в базе
  233. $prefix = \str_replace('_', '\\_', $this->dbPrefix);
  234. $stmt = $this->db->query("SHOW TABLE STATUS LIKE '{$prefix}%'");
  235. $engine = [];
  236. while ($row = $stmt->fetch()) {
  237. if (isset($engine[$row['Engine']])) {
  238. ++$engine[$row['Engine']];
  239. } else {
  240. $engine[$row['Engine']] = 1;
  241. }
  242. }
  243. // в базе нет таблиц
  244. if (empty($engine)) {
  245. $engine = 'MyISAM';
  246. } else {
  247. \arsort($engine);
  248. // берем тип наиболее часто встречаемый у имеющихся таблиц
  249. $engine = \array_keys($engine);
  250. $engine = \array_shift($engine);
  251. }
  252. }
  253. $this->nameCheck($engine);
  254. $query = \rtrim($query, ', ') . ") ENGINE={$engine} CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci";
  255. return false !== $this->db->exec($query);
  256. }
  257. /**
  258. * Удаляет таблицу
  259. */
  260. public function dropTable(string $table): bool
  261. {
  262. $table = $this->tName($table);
  263. return false !== $this->db->exec("DROP TABLE IF EXISTS `{$table}`");
  264. }
  265. /**
  266. * Переименовывает таблицу
  267. */
  268. public function renameTable(string $old, string $new): bool
  269. {
  270. $old = $this->tName($old);
  271. $new = $this->tName($new);
  272. if (
  273. $this->tableExists($new)
  274. && ! $this->tableExists($old)
  275. ) {
  276. return true;
  277. }
  278. return false !== $this->db->exec("ALTER TABLE `{$old}` RENAME TO `{$new}`");
  279. }
  280. /**
  281. * Добавляет поле в таблицу
  282. */
  283. public function addField(string $table, string $field, string $type, bool $allowNull, /* mixed */ $default = null, string $collate = null, string $after = null): bool
  284. {
  285. $table = $this->tName($table);
  286. if ($this->fieldExists($table, $field)) {
  287. return true;
  288. }
  289. $query = "ALTER TABLE `{$table}` ADD " . $this->buildColumn($field, [$type, $allowNull, $default, $collate]);
  290. if (null !== $after) {
  291. $this->nameCheck($after);
  292. $query .= " AFTER `{$after}`";
  293. }
  294. return false !== $this->db->exec($query);
  295. }
  296. /**
  297. * Модифицирует поле в таблице
  298. */
  299. public function alterField(string $table, string $field, string $type, bool $allowNull, /* mixed */ $default = null, string $collate = null, string $after = null): bool
  300. {
  301. $table = $this->tName($table);
  302. $query = "ALTER TABLE `{$table}` MODIFY " . $this->buildColumn($field, [$type, $allowNull, $default, $collate]);
  303. if (null !== $after) {
  304. $this->nameCheck($after);
  305. $query .= " AFTER `{$after}`";
  306. }
  307. return false !== $this->db->exec($query);
  308. }
  309. /**
  310. * Удаляет поле из таблицы
  311. */
  312. public function dropField(string $table, string $field): bool
  313. {
  314. $table = $this->tName($table);
  315. $this->nameCheck($field);
  316. if (! $this->fieldExists($table, $field)) {
  317. return true;
  318. }
  319. return false !== $this->db->exec("ALTER TABLE `{$table}` DROP COLUMN `{$field}`");
  320. }
  321. /**
  322. * Переименование поля в таблице
  323. */
  324. public function renameField(string $table, string $old, string $new): bool
  325. {
  326. $table = $this->tName($table);
  327. $this->nameCheck($old);
  328. if (
  329. $this->fieldExists($table, $new)
  330. && ! $this->fieldExists($table, $old)
  331. ) {
  332. return true;
  333. }
  334. $vars = [
  335. ':tname' => $table,
  336. ':fname' => $old,
  337. ];
  338. $query = 'SELECT COLUMN_DEFAULT, IS_NULLABLE, COLUMN_TYPE, COLLATION_NAME
  339. FROM INFORMATION_SCHEMA.COLUMNS
  340. WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?s:tname AND COLUMN_NAME = ?s:fname';
  341. $stmt = $this->db->query($query, $vars);
  342. $result = $stmt->fetch();
  343. $stmt->closeCursor();
  344. $type = $result['COLUMN_TYPE'];
  345. $allowNull = 'YES' == $result['IS_NULLABLE'];
  346. $default = $result['COLUMN_DEFAULT'];
  347. $collate = \str_replace('utf8mb4_', '', $result['COLLATION_NAME'], $count);
  348. if (1 !== $count) {
  349. throw new PDOException("Table - '{$table}', column - '{$old}', collate - '{$result['COLLATION_NAME']}'");
  350. }
  351. $query = "ALTER TABLE `{$table}` CHANGE COLUMN `{$old}` " . $this->buildColumn($new, [$type, $allowNull, $default, $collate]);
  352. return false !== $this->db->exec($query);
  353. }
  354. /**
  355. * Добавляет индекс в таблицу
  356. */
  357. public function addIndex(string $table, string $index, array $fields, bool $unique = false): bool
  358. {
  359. $table = $this->tName($table);
  360. if ($this->indexExists($table, $index)) {
  361. return true;
  362. }
  363. $query = "ALTER TABLE `{$table}` ADD ";
  364. if ('PRIMARY' == $index) {
  365. $query .= 'PRIMARY KEY';
  366. } else {
  367. $this->nameCheck($index);
  368. $type = $unique ? 'UNIQUE' : 'INDEX';
  369. $query .= "{$type} `{$table}_{$index}`";
  370. }
  371. $query .= ' (' . $this->replIdxs($fields) . ')';
  372. return false !== $this->db->exec($query);
  373. }
  374. /**
  375. * Удаляет индекс из таблицы
  376. */
  377. public function dropIndex(string $table, string $index): bool
  378. {
  379. $table = $this->tName($table);
  380. if (! $this->indexExists($table, $index)) {
  381. return true;
  382. }
  383. $query = "ALTER TABLE `{$table}` DROP ";
  384. if ('PRIMARY' == $index) {
  385. $query .= "PRIMARY KEY";
  386. } else {
  387. $this->nameCheck($index);
  388. $query .= "INDEX `{$table}_{$index}`";
  389. }
  390. return false !== $this->db->exec($query);
  391. }
  392. /**
  393. * Очищает таблицу
  394. */
  395. public function truncateTable(string $table): bool
  396. {
  397. $table = $this->tName($table);
  398. return false !== $this->db->exec("TRUNCATE TABLE `{$table}`");
  399. }
  400. /**
  401. * Возвращает статистику
  402. */
  403. public function statistics(): array
  404. {
  405. $prefix = \str_replace('_', '\\_', $this->dbPrefix);
  406. $stmt = $this->db->query("SHOW TABLE STATUS LIKE '{$prefix}%'");
  407. $records = $size = 0;
  408. $engine = [];
  409. while ($row = $stmt->fetch()) {
  410. $records += $row['Rows'];
  411. $size += $row['Data_length'] + $row['Index_length'];
  412. if (isset($engine[$row['Engine']])) {
  413. ++$engine[$row['Engine']];
  414. } else {
  415. $engine[$row['Engine']] = 1;
  416. }
  417. }
  418. \arsort($engine);
  419. $tmp = [];
  420. foreach ($engine as $key => $val) {
  421. $tmp[] = "{$key}({$val})";
  422. }
  423. $other = [];
  424. $stmt = $this->db->query("SHOW VARIABLES LIKE 'character\\_set\\_%'");
  425. while ($row = $stmt->fetch(PDO::FETCH_NUM)) {
  426. $other[$row[0]] = $row[1];
  427. }
  428. return [
  429. 'db' => 'MySQL (PDO) v.' . $this->db->getAttribute(PDO::ATTR_SERVER_VERSION),
  430. 'tables' => \implode(', ', $tmp),
  431. 'records' => $records,
  432. 'size' => $size,
  433. 'server info' => $this->db->getAttribute(PDO::ATTR_SERVER_INFO),
  434. ] + $other;
  435. }
  436. /**
  437. * Формирует карту базы данных
  438. */
  439. public function getMap(): array
  440. {
  441. $vars = [
  442. ':tname' => \str_replace('_', '\\_', $this->dbPrefix) . '%',
  443. ];
  444. $query = 'SELECT TABLE_NAME, COLUMN_NAME, DATA_TYPE
  445. FROM INFORMATION_SCHEMA.COLUMNS
  446. WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME LIKE ?s:tname
  447. ORDER BY TABLE_NAME';
  448. $stmt = $this->db->query($query, $vars);
  449. $result = [];
  450. $table = null;
  451. $prfLen = \strlen($this->dbPrefix);
  452. while ($row = $stmt->fetch()) {
  453. if ($table !== $row['TABLE_NAME']) {
  454. $table = $row['TABLE_NAME'];
  455. $tableNoPref = \substr($table, $prfLen);
  456. $result[$tableNoPref] = [];
  457. }
  458. $type = \strtolower($row['DATA_TYPE']);
  459. $result[$tableNoPref][$row['COLUMN_NAME']] = $this->types[$type] ?? 's';
  460. }
  461. return $result;
  462. }
  463. }