mysql.php 18 KB

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