mysql.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  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. // сравнение
  215. if (isset($data[3]) && is_string($data[3])) {
  216. $this->testStr($data[3]);
  217. $query .= " CHARACTER SET {$charSet} COLLATE {$charSet}_{$data[3]}";
  218. }
  219. // не NULL
  220. if (empty($data[1])) {
  221. $query .= ' NOT NULL';
  222. }
  223. // значение по умолчанию
  224. if (isset($data[2])) {
  225. $query .= ' DEFAULT ' . $this->convToStr($data[2]);
  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. $prefix = str_replace('_', '\\_', $this->dbPrefix);
  249. $stmt = $this->db->query("SHOW TABLE STATUS LIKE '{$prefix}%'");
  250. $engine = [];
  251. while ($row = $stmt->fetch()) {
  252. if (isset($engine[$row['Engine']])) {
  253. ++$engine[$row['Engine']];
  254. } else {
  255. $engine[$row['Engine']] = 1;
  256. }
  257. }
  258. // в базе нет таблиц
  259. if (empty($engine)) {
  260. $engine = 'MyISAM';
  261. } else {
  262. arsort($engine);
  263. // берем тип наиболее часто встречаемый у имеющихся таблиц
  264. $engine = array_keys($engine);
  265. $engine = array_shift($engine);
  266. }
  267. }
  268. $this->testStr($engine);
  269. $query = rtrim($query, ', ') . ") ENGINE={$engine} CHARACTER SET {$charSet}";
  270. return $this->db->exec($query) !== false;
  271. }
  272. /**
  273. * Удаляет таблицу
  274. *
  275. * @param string $table
  276. * @param bool $noPrefix
  277. *
  278. * @return bool
  279. */
  280. public function dropTable($table, $noPrefix = false)
  281. {
  282. $table = ($noPrefix ? '' : $this->dbPrefix) . $table;
  283. $this->testStr($table);
  284. return $this->db->exec("DROP TABLE IF EXISTS `{$table}`") !== false;
  285. }
  286. /**
  287. * Переименовывает таблицу
  288. *
  289. * @param string $old
  290. * @param string $new
  291. * @param bool $noPrefix
  292. *
  293. * @return bool
  294. */
  295. public function renameTable($old, $new, $noPrefix = false)
  296. {
  297. if ($this->tableExists($new, $noPrefix) && ! $this->tableExists($old, $noPrefix)) {
  298. return true;
  299. }
  300. $old = ($noPrefix ? '' : $this->dbPrefix) . $old;
  301. $this->testStr($old);
  302. $new = ($noPrefix ? '' : $this->dbPrefix) . $new;
  303. $this->testStr($new);
  304. return $this->db->exec("ALTER TABLE `{$old}` RENAME TO `{$new}`") !== false;
  305. }
  306. /**
  307. * Добавляет поле в таблицу
  308. *
  309. * @param string $table
  310. * @param string $field
  311. * @param bool $allowNull
  312. * @param mixed $default
  313. * @param string $after
  314. * @param bool $noPrefix
  315. *
  316. * @return bool
  317. */
  318. public function addField($table, $field, $type, $allowNull, $default = null, $after = null, $noPrefix = false)
  319. {
  320. if ($this->fieldExists($table, $field, $noPrefix)) {
  321. return true;
  322. }
  323. $table = ($noPrefix ? '' : $this->dbPrefix) . $table;
  324. $this->testStr($table);
  325. $this->testStr($field);
  326. $query = "ALTER TABLE `{$table}` ADD `{$field}` " . $this->replType($type);
  327. if ($allowNull) {
  328. $query .= ' NOT NULL';
  329. }
  330. if (null !== $default) {
  331. $query .= ' DEFAULT ' . $this->convToStr($default);
  332. }
  333. if (null !== $after) {
  334. $this->testStr($after);
  335. $query .= " AFTER `{$after}`";
  336. }
  337. return $this->db->exec($query) !== false;
  338. }
  339. /**
  340. * Модифицирует поле в таблице
  341. *
  342. * @param string $table
  343. * @param string $field
  344. * @param bool $allowNull
  345. * @param mixed $default
  346. * @param string $after
  347. * @param bool $noPrefix
  348. *
  349. * @return bool
  350. */
  351. public function alterField($table, $field, $type, $allowNull, $default = null, $after = null, $noPrefix = false)
  352. {
  353. $table = ($noPrefix ? '' : $this->dbPrefix) . $table;
  354. $this->testStr($table);
  355. $this->testStr($field);
  356. $query = "ALTER TABLE `{$table}` MODIFY `{$field}` " . $this->replType($type);
  357. if ($allowNull) {
  358. $query .= ' NOT NULL';
  359. }
  360. if (null !== $default) {
  361. $query .= ' DEFAULT ' . $this->convToStr($default);
  362. }
  363. if (null !== $after) {
  364. $this->testStr($after);
  365. $query .= " AFTER `{$after}`";
  366. }
  367. return $this->db->exec($query) !== false;
  368. }
  369. /**
  370. * Удаляет поле из таблицы
  371. *
  372. * @param string $table
  373. * @param string $field
  374. * @param bool $noPrefix
  375. *
  376. * @return bool
  377. */
  378. public function dropField($table, $field, $noPrefix = false)
  379. {
  380. if (! $this->fieldExists($table, $field, $noPrefix)) {
  381. return true;
  382. }
  383. $table = ($noPrefix ? '' : $this->dbPrefix) . $table;
  384. $this->testStr($table);
  385. $this->testStr($field);
  386. return $this->db->exec("ALTER TABLE `{$table}` DROP COLUMN `{$field}`") !== false;
  387. }
  388. /**
  389. * Добавляет индекс в таблицу
  390. *
  391. * @param string $table
  392. * @param string $index
  393. * @param array $fields
  394. * @param bool $unique
  395. * @param bool $noPrefix
  396. *
  397. * @return bool
  398. */
  399. public function addIndex($table, $index, array $fields, $unique = false, $noPrefix = false)
  400. {
  401. if ($this->indexExists($table, $index, $noPrefix)) {
  402. return true;
  403. }
  404. $table = ($noPrefix ? '' : $this->dbPrefix) . $table;
  405. $this->testStr($table);
  406. $query = "ALTER TABLE `{$table}` ADD ";
  407. if ($index == 'PRIMARY') {
  408. $query .= 'PRIMARY KEY';
  409. } else {
  410. $index = $table . '_' . $index;
  411. $this->testStr($index);
  412. if ($unique) {
  413. $query .= "UNIQUE `{$index}`";
  414. } else {
  415. $query .= "INDEX `{$index}`";
  416. }
  417. }
  418. $query .= ' (' . $this->replIdxs($fields) . ')';
  419. return $this->db->exec($query) !== false;
  420. }
  421. /**
  422. * Удаляет индекс из таблицы
  423. *
  424. * @param string $table
  425. * @param string $index
  426. * @param bool $noPrefix
  427. *
  428. * @return bool
  429. */
  430. public function dropIndex($table, $index, $noPrefix = false)
  431. {
  432. if (! $this->indexExists($table, $index, $noPrefix)) {
  433. return true;
  434. }
  435. $table = ($noPrefix ? '' : $this->dbPrefix) . $table;
  436. $this->testStr($table);
  437. $query = "ALTER TABLE `{$table}` ";
  438. if ($index == 'PRIMARY') {
  439. $query .= "DROP PRIMARY KEY";
  440. } else {
  441. $index = $table . '_' . $index;
  442. $this->testStr($index);
  443. $query .= "DROP INDEX `{$index}`";
  444. }
  445. return $this->db->exec($query) !== false;
  446. }
  447. /**
  448. * Очищает таблицу
  449. *
  450. * @param string $table
  451. * @param bool $noPrefix
  452. *
  453. * @return bool
  454. */
  455. public function truncateTable($table, $noPrefix = false)
  456. {
  457. $table = ($noPrefix ? '' : $this->dbPrefix) . $table;
  458. $this->testStr($table);
  459. return $this->db->exec("TRUNCATE TABLE `{$table}`") !== false;
  460. }
  461. /**
  462. * Статистика
  463. *
  464. * @return array|string
  465. */
  466. public function statistics()
  467. {
  468. $this->testStr($this->dbPrefix);
  469. $prefix = str_replace('_', '\\_', $this->dbPrefix);
  470. $stmt = $this->db->query("SHOW TABLE STATUS LIKE '{$prefix}%'");
  471. $records = $size = 0;
  472. $engine = [];
  473. while ($row = $stmt->fetch()) {
  474. $records += $row['Rows'];
  475. $size += $row['Data_length'] + $row['Index_length'];
  476. if (isset($engine[$row['Engine']])) {
  477. ++$engine[$row['Engine']];
  478. } else {
  479. $engine[$row['Engine']] = 1;
  480. }
  481. }
  482. arsort($engine);
  483. $tmp = [];
  484. foreach ($engine as $key => $val) {
  485. $tmp[] = "{$key}({$val})";
  486. }
  487. $other = [];
  488. $stmt = $this->db->query("SHOW VARIABLES LIKE 'character\_set\_%'");
  489. while ($row = $stmt->fetch(\PDO::FETCH_NUM)) {
  490. $other[$row[0]] = $row[1];
  491. }
  492. return [
  493. 'db' => 'MySQL (PDO) ' . $this->db->getAttribute(\PDO::ATTR_SERVER_VERSION) . ' : ' . implode(', ', $tmp),
  494. 'records' => $records,
  495. 'size' => $size,
  496. 'server info' => $this->db->getAttribute(\PDO::ATTR_SERVER_INFO),
  497. ] + $other;
  498. }
  499. }