mysql.php 17 KB

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