mysql.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  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 string
  21. */
  22. protected $dbCharSet;
  23. /**
  24. * Массив замены типов полей таблицы
  25. * @var array
  26. */
  27. protected $dbTypeRepl = [
  28. '%^SERIAL$%i' => 'INT(10) UNSIGNED AUTO_INCREMENT',
  29. ];
  30. /**
  31. * Конструктор
  32. *
  33. * @param DB $db
  34. * @param string $prefix
  35. */
  36. public function __construct(DB $db, $prefix)
  37. {
  38. $this->db = $db;
  39. $this->dbPrefix = $prefix;
  40. }
  41. /**
  42. * Перехват неизвестных методов
  43. *
  44. * @param string $name
  45. * @param array $args
  46. *
  47. * @throws PDOException
  48. */
  49. public function __call($name, array $args)
  50. {
  51. throw new PDOException("Method '{$name}' not found in DB driver.");
  52. }
  53. /**
  54. * Проверяет строку на допустимые символы
  55. *
  56. * @param string $str
  57. *
  58. * @throws PDOException
  59. */
  60. protected function testStr($str)
  61. {
  62. if (! is_string($str) || preg_match('%[^a-zA-Z0-9_]%', $str)) {
  63. throw new PDOException("Name '{$str}' have bad characters.");
  64. }
  65. }
  66. /**
  67. * Операции над полями индексов: проверка, замена
  68. *
  69. * @param array $arr
  70. *
  71. * @return string
  72. */
  73. protected function replIdxs(array $arr)
  74. {
  75. foreach ($arr as &$value) {
  76. if (preg_match('%^(.*)\s*(\(\d+\))$%', $value, $matches)) {
  77. $this->testStr($matches[1]);
  78. $value = "`{$matches[1]}`{$matches[2]}";
  79. } else {
  80. $this->testStr($value);
  81. $value = "`{$value}`";
  82. }
  83. unset($value);
  84. }
  85. return implode(',', $arr);
  86. }
  87. /**
  88. * Замена типа поля в соответствии с dbTypeRepl
  89. *
  90. * @param string $type
  91. *
  92. * @return string
  93. */
  94. protected function replType($type)
  95. {
  96. return preg_replace(array_keys($this->dbTypeRepl), array_values($this->dbTypeRepl), $type);
  97. }
  98. /**
  99. * Конвертирует данные в строку для DEFAULT
  100. *
  101. * @param mixed $data
  102. *
  103. * @throws PDOException
  104. *
  105. * @return string
  106. */
  107. protected function convToStr($data) {
  108. if (is_string($data)) {
  109. return $this->db->quote($data);
  110. } elseif (is_numeric($data)) {
  111. return (string) $data;
  112. } elseif (is_bool($data)) {
  113. return $data ? 'true' : 'false';
  114. } else {
  115. throw new PDOException('Invalid data type for DEFAULT.');
  116. }
  117. }
  118. /**
  119. * Вовзращает набор символов БД
  120. *
  121. * @return string
  122. */
  123. protected function getCharSet()
  124. {
  125. if (! $this->dbCharSet) {
  126. $stmt = $this->db->query("SHOW VARIABLES LIKE 'character\_set\_database'");
  127. $this->dbCharSet = $stmt->fetchColumn(1);
  128. $stmt->closeCursor();
  129. }
  130. return $this->dbCharSet;
  131. }
  132. /**
  133. * Проверяет наличие таблицы в базе
  134. *
  135. * @param string $table
  136. * @param bool $noPrefix
  137. *
  138. * @return bool
  139. */
  140. public function tableExists($table, $noPrefix = false)
  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($table, $field, $noPrefix = false)
  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($table, $index, $noPrefix = false)
  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($table, array $schema, $noPrefix = false)
  205. {
  206. $table = ($noPrefix ? '' : $this->dbPrefix) . $table;
  207. $this->testStr($table);
  208. $charSet = $this->getCharSet();
  209. $query = "CREATE TABLE IF NOT EXISTS `{$table}` (";
  210. foreach ($schema['FIELDS'] as $field => $data) {
  211. $this->testStr($field);
  212. // имя и тип
  213. $query .= "`{$field}` " . $this->replType($data[0]);
  214. // не NULL
  215. if (empty($data[1])) {
  216. $query .= ' NOT NULL';
  217. }
  218. // значение по умолчанию
  219. if (isset($data[2])) {
  220. $query .= ' DEFAULT ' . $this->convToStr($data[2]);
  221. }
  222. // сравнение
  223. if (isset($data[3]) && is_string($data[3])) {
  224. $this->testStr($data[3]);
  225. $query .= " CHARACTER SET {$charSet} COLLATE {$charSet}_{$data[3]}";
  226. }
  227. $query .= ', ';
  228. }
  229. if (isset($schema['PRIMARY KEY'])) {
  230. $query .= 'PRIMARY KEY (' . $this->replIdxs($schema['PRIMARY KEY']) . '), ';
  231. }
  232. if (isset($schema['UNIQUE KEYS'])) {
  233. foreach ($schema['UNIQUE KEYS'] as $key => $fields) {
  234. $this->testStr($key);
  235. $query .= "UNIQUE `{$table}_{$key}` (" . $this->replIdxs($fields) . '), ';
  236. }
  237. }
  238. if (isset($schema['INDEXES'])) {
  239. foreach ($schema['INDEXES'] as $index => $fields) {
  240. $this->testStr($index);
  241. $query .= "INDEX `{$table}_{$index}` (" . $this->replIdxs($fields) . '), ';
  242. }
  243. }
  244. if (isset($schema['ENGINE'])) {
  245. $engine = $schema['ENGINE'];
  246. } else {
  247. // при отсутствии типа таблицы он определяется на основании типов других таблиц в базе
  248. $stmt = $this->db->query("SHOW TABLE STATUS LIKE '{$this->dbPrefix}%'");
  249. $engine = [];
  250. while ($row = $stmt->fetch()) {
  251. if (isset($engine[$row['Engine']])) {
  252. ++$engine[$row['Engine']];
  253. } else {
  254. $engine[$row['Engine']] = 1;
  255. }
  256. }
  257. // в базе нет таблиц
  258. if (empty($engine)) {
  259. $engine = 'MyISAM';
  260. } else {
  261. arsort($engine);
  262. // берем тип наиболее часто встречаемый у имеющихся таблиц
  263. $engine = array_shift(array_keys($engine));
  264. }
  265. }
  266. $this->testStr($engine);
  267. $query = rtrim($query, ', ') . ") ENGINE = {$engine} CHARACTER SET {$charSet}";
  268. return $this->db->exec($query) !== false;
  269. }
  270. /**
  271. * Удаляет таблицу
  272. *
  273. * @param string $table
  274. * @param bool $noPrefix
  275. *
  276. * @return bool
  277. */
  278. public function dropTable($table, $noPrefix = false)
  279. {
  280. $table = ($noPrefix ? '' : $this->dbPrefix) . $table;
  281. $this->testStr($table);
  282. return $this->db->exec("DROP TABLE IF EXISTS `{$table}`") !== false;
  283. }
  284. /**
  285. * Переименовывает таблицу
  286. *
  287. * @param string $old
  288. * @param string $new
  289. * @param bool $noPrefix
  290. *
  291. * @return bool
  292. */
  293. public function renameTable($old, $new, $noPrefix = false)
  294. {
  295. if ($this->tableExists($new, $noPrefix) && ! $this->tableExists($old, $noPrefix)) {
  296. return true;
  297. }
  298. $old = ($noPrefix ? '' : $this->dbPrefix) . $old;
  299. $this->testStr($old);
  300. $new = ($noPrefix ? '' : $this->dbPrefix) . $new;
  301. $this->testStr($new);
  302. return $this->db->exec("ALTER TABLE `{$old}` RENAME TO `{$new}`") !== false;
  303. }
  304. /**
  305. * Добавляет поле в таблицу
  306. *
  307. * @param string $table
  308. * @param string $field
  309. * @param bool $allowNull
  310. * @param mixed $default
  311. * @param string $after
  312. * @param bool $noPrefix
  313. *
  314. * @return bool
  315. */
  316. public function addField($table, $field, $type, $allowNull, $default = null, $after = null, $noPrefix = false)
  317. {
  318. if ($this->fieldExists($table, $field, $noPrefix)) {
  319. return true;
  320. }
  321. $table = ($noPrefix ? '' : $this->dbPrefix) . $table;
  322. $this->testStr($table);
  323. $this->testStr($field);
  324. $query = "ALTER TABLE `{$table}` ADD `{$field}` " . $this->replType($type);
  325. if ($allowNull) {
  326. $query .= ' NOT NULL';
  327. }
  328. if (null !== $default) {
  329. $query .= ' DEFAULT ' . $this->convToStr($default);
  330. }
  331. if (null !== $after) {
  332. $this->testStr($after);
  333. $query .= " AFTER `{$after}`";
  334. }
  335. return $this->db->exec($query) !== false;
  336. }
  337. /**
  338. * Модифицирует поле в таблице
  339. *
  340. * @param string $table
  341. * @param string $field
  342. * @param bool $allowNull
  343. * @param mixed $default
  344. * @param string $after
  345. * @param bool $noPrefix
  346. *
  347. * @return bool
  348. */
  349. public function alterField($table, $field, $type, $allowNull, $default = null, $after = null, $noPrefix = false)
  350. {
  351. $table = ($noPrefix ? '' : $this->dbPrefix) . $table;
  352. $this->testStr($table);
  353. $this->testStr($field);
  354. $query = "ALTER TABLE `{$table}` MODIFY `{$field}` " . $this->replType($type);
  355. if ($allowNull) {
  356. $query .= ' NOT NULL';
  357. }
  358. if (null !== $default) {
  359. $query .= ' DEFAULT ' . $this->convToStr($default);
  360. }
  361. if (null !== $after) {
  362. $this->testStr($after);
  363. $query .= " AFTER `{$after}`";
  364. }
  365. return $this->db->exec($query) !== false;
  366. }
  367. /**
  368. * Удаляет поле из таблицы
  369. *
  370. * @param string $table
  371. * @param string $field
  372. * @param bool $noPrefix
  373. *
  374. * @return bool
  375. */
  376. public function dropField($table, $field, $noPrefix = false)
  377. {
  378. if (! $this->fieldExists($table, $field, $noPrefix)) {
  379. return true;
  380. }
  381. $table = ($noPrefix ? '' : $this->dbPrefix) . $table;
  382. $this->testStr($table);
  383. $this->testStr($field);
  384. return $this->db->exec("ALTER TABLE `{$table}` DROP COLUMN `{$field}`") !== false;
  385. }
  386. /**
  387. * Добавляет индекс в таблицу
  388. *
  389. * @param string $table
  390. * @param string $index
  391. * @param array $fields
  392. * @param bool $unique
  393. * @param bool $noPrefix
  394. *
  395. * @return bool
  396. */
  397. public function addIndex($table, $index, array $fields, $unique = false, $noPrefix = false)
  398. {
  399. if ($this->indexExists($table, $index, $noPrefix)) {
  400. return true;
  401. }
  402. $table = ($noPrefix ? '' : $this->dbPrefix) . $table;
  403. $this->testStr($table);
  404. $query = "ALTER TABLE `{$table}` ADD ";
  405. if ($index == 'PRIMARY') {
  406. $query .= 'PRIMARY KEY';
  407. } else {
  408. $index = $table . '_' . $index;
  409. $this->testStr($index);
  410. if ($unique) {
  411. $query .= "UNIQUE `{$index}`";
  412. } else {
  413. $query .= "INDEX `{$index}`";
  414. }
  415. }
  416. $query .= ' (' . $this->replIdxs($fields) . ')';
  417. return $this->db->exec($query) !== false;
  418. }
  419. /**
  420. * Удаляет индекс из таблицы
  421. *
  422. * @param string $table
  423. * @param string $index
  424. * @param bool $noPrefix
  425. *
  426. * @return bool
  427. */
  428. public function dropIndex($table, $index, $noPrefix = false)
  429. {
  430. if (! $this->indexExists($table, $index, $noPrefix)) {
  431. return true;
  432. }
  433. $table = ($noPrefix ? '' : $this->dbPrefix) . $table;
  434. $this->testStr($table);
  435. $query = "ALTER TABLE `{$table}` ";
  436. if ($index == 'PRIMARY') {
  437. $query .= "DROP PRIMARY KEY";
  438. } else {
  439. $index = $table . '_' . $index;
  440. $this->testStr($index);
  441. $query .= "DROP INDEX `{$index}`";
  442. }
  443. return $this->db->exec($query) !== false;
  444. }
  445. /**
  446. * Очищает таблицу
  447. *
  448. * @param string $table
  449. * @param bool $noPrefix
  450. *
  451. * @return bool
  452. */
  453. public function truncateTable($table, $noPrefix = false)
  454. {
  455. $table = ($noPrefix ? '' : $this->dbPrefix) . $table;
  456. $this->testStr($table);
  457. return $this->db->exec("TRUNCATE TABLE `{$table}`") !== false;
  458. }
  459. /**
  460. * Статистика
  461. *
  462. * @return array|string
  463. */
  464. public function statistics()
  465. {
  466. $this->testStr($this->dbPrefix);
  467. $stmt = $this->db->query("SHOW TABLE STATUS LIKE '{$this->dbPrefix}%'");
  468. $records = $size = 0;
  469. $engine = [];
  470. while ($row = $stmt->fetch()) {
  471. $records += $row['Rows'];
  472. $size += $row['Data_length'] + $row['Index_length'];
  473. if (isset($engine[$row['Engine']])) {
  474. ++$engine[$row['Engine']];
  475. } else {
  476. $engine[$row['Engine']] = 1;
  477. }
  478. }
  479. arsort($engine);
  480. $tmp = [];
  481. foreach ($engine as $key => $val) {
  482. $tmp[] = "{$key}({$val})";
  483. }
  484. $other = [];
  485. $stmt = $this->db->query("SHOW VARIABLES LIKE 'character\_set\_%'");
  486. while ($row = $stmt->fetch(\PDO::FETCH_NUM)) {
  487. $other[$row[0]] = $row[1];
  488. }
  489. return [
  490. 'db' => 'MySQL (PDO) ' . $this->db->getAttribute(\PDO::ATTR_SERVER_VERSION) . ' : ' . implode(', ', $tmp),
  491. 'records' => $records,
  492. 'size' => $size,
  493. 'server info' => $this->db->getAttribute(\PDO::ATTR_SERVER_INFO),
  494. ] + $other;
  495. }
  496. }