mysql.php 17 KB

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