MysqlBackupService.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2020 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. // +----------------------------------------------------------------------
  12. // | origin:tp5er\tp5-databackup
  13. // +----------------------------------------------------------------------
  14. namespace crmeb\services;
  15. use think\facade\Db;
  16. class MysqlBackupService
  17. {
  18. /**
  19. * 文件指针
  20. * @var resource
  21. */
  22. private $fp;
  23. /**
  24. * 备份文件信息 part - 卷号,name - 文件名
  25. * @var array
  26. */
  27. private $file;
  28. /**
  29. * 当前打开文件大小
  30. * @var integer
  31. */
  32. private $size = 0;
  33. /**
  34. * 数据库配置
  35. * @var integer
  36. */
  37. private $dbconfig = array();
  38. /**
  39. * 备份配置
  40. * @var integer
  41. */
  42. private $config = array(
  43. 'path' => './Data/',
  44. //数据库备份路径
  45. 'part' => 20971520,
  46. //数据库备份卷大小
  47. 'compress' => 0,
  48. //数据库备份文件是否启用压缩 0不压缩 1 压缩
  49. 'level' => 9,
  50. );
  51. /**
  52. * 数据库备份构造方法
  53. *
  54. * @param array $file 备份或还原的文件信息
  55. * @param array $config 备份配置信息
  56. */
  57. public function __construct($config = [])
  58. {
  59. $this->config['path'] = app()->getRootPath() . 'backup/';
  60. $this->config = array_merge($this->config, $config);
  61. //初始化文件名
  62. $this->setFile();
  63. //初始化数据库连接参数
  64. $this->setDbConn();
  65. //检查文件是否可写
  66. if (!$this->checkPath($this->config['path'])) {
  67. throw new \Exception("The current directory is not writable");
  68. }
  69. }
  70. /**
  71. * 设置脚本运行超时时间
  72. * 0表示不限制,支持连贯操作
  73. */
  74. public function setTimeout($time = null)
  75. {
  76. if (!is_null($time)) {
  77. set_time_limit($time) || ini_set("max_execution_time", $time);
  78. }
  79. return $this;
  80. }
  81. /**
  82. * 设置数据库连接必备参数
  83. *
  84. * @param array $dbconfig 数据库连接配置信息
  85. * @return $this
  86. */
  87. public function setDbConn($dbconfig = [])
  88. {
  89. if (empty($dbconfig)) {
  90. $this->dbconfig = config('database.connections.' . config('database.default'));
  91. //$this->dbconfig = Config::get('database');
  92. } else {
  93. $this->dbconfig = $dbconfig;
  94. }
  95. return $this;
  96. }
  97. /**
  98. * 设置备份文件名
  99. *
  100. * @param null $file
  101. * @return $this
  102. */
  103. public function setFile($file = null)
  104. {
  105. if (is_null($file)) {
  106. $this->file = ['name' => date('Ymd-His'), 'part' => 1];
  107. } else {
  108. if (!array_key_exists("name", $file) && !array_key_exists("part", $file)) {
  109. $this->file = $file['1'];
  110. } else {
  111. $this->file = $file;
  112. }
  113. }
  114. return $this;
  115. }
  116. //数据类连接
  117. public static function connect()
  118. {
  119. return Db::connect();
  120. }
  121. /**
  122. * 数据库表列表
  123. *
  124. * @param null $table
  125. * @param int $type
  126. * @return array
  127. * @throws \think\db\exception\BindParamException
  128. * @throws \think\exception\PDOException
  129. */
  130. public function dataList(?string $table = null, int $type = 1)
  131. {
  132. $db = self::connect();
  133. if (is_null($table)) {
  134. $list = $db->query("SHOW TABLE STATUS");
  135. } else {
  136. if ($type) {
  137. $list = $db->query("SHOW FULL COLUMNS FROM {$table}");
  138. } else {
  139. $list = $db->query("show columns from {$table}");
  140. }
  141. }
  142. return array_map('array_change_key_case', $list);
  143. //$list;
  144. }
  145. /**
  146. * 数据库备份文件列表
  147. *
  148. * @return array
  149. */
  150. public function fileList()
  151. {
  152. if (!is_dir($this->config['path'])) {
  153. mkdir($this->config['path'], 0755, true);
  154. }
  155. $path = realpath($this->config['path']);
  156. $flag = \FilesystemIterator::KEY_AS_FILENAME;
  157. $glob = new \FilesystemIterator($path, $flag);
  158. $list = array();
  159. foreach ($glob as $name => $file) {
  160. if (preg_match('/^\\d{8,8}-\\d{6,6}-\\d+\\.sql(?:\\.gz)?$/', $name)) {
  161. $info['filename'] = $name;
  162. $name = sscanf($name, '%4s%2s%2s-%2s%2s%2s-%d');
  163. $date = "{$name[0]}-{$name[1]}-{$name[2]}";
  164. $time = "{$name[3]}:{$name[4]}:{$name[5]}";
  165. $part = $name[6];
  166. if (isset($list["{$date} {$time}"])) {
  167. $info = $list["{$date} {$time}"];
  168. $info['part'] = max($info['part'], $part);
  169. $info['size'] = $info['size'] + $file->getSize();
  170. } else {
  171. $info['part'] = $part;
  172. $info['size'] = $file->getSize();
  173. }
  174. $extension = strtoupper(pathinfo($file->getFilename(), PATHINFO_EXTENSION));
  175. $info['compress'] = $extension === 'SQL' ? '-' : $extension;
  176. $info['time'] = strtotime("{$date} {$time}");
  177. $list["{$date} {$time}"] = $info;
  178. }
  179. }
  180. return $list;
  181. }
  182. /**
  183. * @param string $type
  184. * @param int $time
  185. * @return array|false|string
  186. * @throws \Exception
  187. */
  188. public function getFile($type = '', $time = 0)
  189. {
  190. //
  191. if (!is_numeric($time)) {
  192. throw new \Exception("{$time} Illegal data type");
  193. }
  194. switch ($type) {
  195. case 'time':
  196. $name = date('Ymd-His', $time) . '-*.sql*';
  197. $path = realpath($this->config['path']) . DIRECTORY_SEPARATOR . $name;
  198. return glob($path);
  199. break;
  200. case 'timeverif':
  201. $name = date('Ymd-His', $time) . '-*.sql*';
  202. $path = realpath($this->config['path']) . DIRECTORY_SEPARATOR . $name;
  203. $files = glob($path);
  204. $list = array();
  205. foreach ($files as $name) {
  206. $basename = basename($name);
  207. $match = sscanf($basename, '%4s%2s%2s-%2s%2s%2s-%d');
  208. $gz = preg_match('/^\\d{8,8}-\\d{6,6}-\\d+\\.sql.gz$/', $basename);
  209. $list[$match[6]] = array($match[6], $name, $gz);
  210. }
  211. $last = end($list);
  212. if (count($list) === $last[0]) {
  213. return $list;
  214. } else {
  215. throw new \Exception("File {$files['0']} may be damaged, please check again");
  216. }
  217. break;
  218. case 'pathname':
  219. return "{$this->config['path']}{$this->file['name']}-{$this->file['part']}.sql";
  220. break;
  221. case 'filename':
  222. return "{$this->file['name']}-{$this->file['part']}.sql";
  223. break;
  224. case 'filepath':
  225. return $this->config['path'];
  226. break;
  227. default:
  228. $arr = array('pathname' => "{$this->config['path']}{$this->file['name']}-{$this->file['part']}.sql", 'filename' => "{$this->file['name']}-{$this->file['part']}.sql", 'filepath' => $this->config['path'], 'file' => $this->file);
  229. return $arr;
  230. }
  231. }
  232. /**
  233. * 删除备份文件
  234. * @param $time
  235. * @return mixed
  236. * @throws \Exception
  237. */
  238. public function delFile($time)
  239. {
  240. if ($time) {
  241. $file = $this->getFile('time', $time);
  242. array_map("unlink", $this->getFile('time', $time));
  243. if (count($this->getFile('time', $time))) {
  244. throw new \Exception("File {$time} deleted failed");
  245. } else {
  246. return $time;
  247. }
  248. } else {
  249. throw new \Exception("{$time} Time parameter is incorrect");
  250. }
  251. }
  252. /**
  253. * 下载备份
  254. *
  255. * @param $time
  256. * @param int $part
  257. * @throws \Exception
  258. */
  259. public function downloadFile($time, $part = 0)
  260. {
  261. $file = $this->getFile('time', $time);
  262. $fileName = $file[$part];
  263. if (file_exists($fileName)) {
  264. ob_end_clean();
  265. header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
  266. header('Content-Description: File Transfer');
  267. header('Content-Type: application/octet-stream');
  268. header('Content-Length: ' . filesize($fileName));
  269. header('Content-Disposition: attachment; filename=' . basename($fileName));
  270. readfile($fileName);
  271. } else {
  272. throw new \Exception("{$time} File is abnormal");
  273. }
  274. }
  275. public function import($start)
  276. {
  277. //还原数据
  278. $db = self::connect();
  279. if ($this->config['compress']) {
  280. $gz = gzopen($this->file[1], 'r');
  281. $size = 0;
  282. } else {
  283. $size = filesize($this->file[1]);
  284. $gz = fopen($this->file[1], 'r');
  285. }
  286. $sql = '';
  287. if ($start) {
  288. $this->config['compress'] ? gzseek($gz, $start) : fseek($gz, $start);
  289. }
  290. for ($i = 0; $i < 1000; $i++) {
  291. $sql .= $this->config['compress'] ? gzgets($gz) : fgets($gz);
  292. if (preg_match('/.*;$/', trim($sql))) {
  293. if (false !== $db->execute($sql)) {
  294. $start += strlen($sql);
  295. } else {
  296. return false;
  297. }
  298. $sql = '';
  299. } elseif ($this->config['compress'] ? gzeof($gz) : feof($gz)) {
  300. return 0;
  301. }
  302. }
  303. return array($start, $size);
  304. }
  305. /**
  306. * 写入初始数据
  307. *
  308. * @return boolean true - 写入成功,false - 写入失败
  309. */
  310. public function Backup_Init()
  311. {
  312. $sql = "-- -----------------------------\n";
  313. $sql .= "-- Think MySQL Data Transfer \n";
  314. $sql .= "-- \n";
  315. $sql .= "-- Host : " . $this->dbconfig['hostname'] . "\n";
  316. $sql .= "-- Port : " . $this->dbconfig['hostport'] . "\n";
  317. $sql .= "-- Database : " . $this->dbconfig['database'] . "\n";
  318. $sql .= "-- \n";
  319. $sql .= "-- Part : #{$this->file['part']}\n";
  320. $sql .= "-- Date : " . date("Y-m-d H:i:s") . "\n";
  321. $sql .= "-- -----------------------------\n\n";
  322. $sql .= "SET FOREIGN_KEY_CHECKS = 0;\n\n";
  323. return $this->write($sql);
  324. }
  325. /**
  326. * 备份表结构
  327. *
  328. * @param string $table
  329. * @param int $start
  330. * @return bool|int
  331. * @throws \think\db\exception\BindParamException
  332. * @throws \think\exception\PDOException
  333. */
  334. public function backup(string $table, int $start)
  335. {
  336. $db = self::connect();
  337. // 备份表结构
  338. if (0 == $start) {
  339. $result = $db->query("SHOW CREATE TABLE `{$table}`");
  340. $sql = "\n";
  341. $sql .= "-- -----------------------------\n";
  342. $sql .= "-- Table structure for `{$table}`\n";
  343. $sql .= "-- -----------------------------\n";
  344. $sql .= "DROP TABLE IF EXISTS `{$table}`;\n";
  345. $sql .= trim($result[0]['Create Table']) . ";\n\n";
  346. if (false === $this->write($sql)) {
  347. return false;
  348. }
  349. }
  350. //数据总数
  351. $result = $db->query("SELECT COUNT(*) AS count FROM `{$table}`");
  352. $count = $result['0']['count'];
  353. //备份表数据
  354. if ($count) {
  355. //写入数据注释
  356. if (0 == $start) {
  357. $sql = "-- -----------------------------\n";
  358. $sql .= "-- Records of `{$table}`\n";
  359. $sql .= "-- -----------------------------\n";
  360. $this->write($sql);
  361. }
  362. //备份数据记录
  363. $result = $db->query("SELECT * FROM `{$table}` LIMIT :MIN, 1000", ['MIN' => intval($start)]);
  364. foreach ($result as $row) {
  365. $row = array_map('addslashes', $row);
  366. $sql = "INSERT INTO `{$table}` VALUES ('" . str_replace(array("\r", "\n"), array('\\r', '\\n'), implode("', '", $row)) . "');\n";
  367. if (false === $this->write($sql)) {
  368. return false;
  369. }
  370. }
  371. //还有更多数据
  372. if ($count > $start + 1000) {
  373. //return array($start + 1000, $count);
  374. return $this->backup($table, $start + 1000);
  375. }
  376. }
  377. //备份下一表
  378. return 0;
  379. }
  380. /**
  381. * 优化表
  382. *
  383. * @param array|string $tables
  384. * @throws \think\db\exception\BindParamException
  385. * @throws \think\exception\PDOException
  386. */
  387. public function optimize($tables)
  388. {
  389. if ($tables) {
  390. $db = self::connect();
  391. if (is_array($tables)) {
  392. $tables = implode('`,`', $tables);
  393. $list = $db->query("OPTIMIZE TABLE `{$tables}`");
  394. } else {
  395. $list = $db->query("OPTIMIZE TABLE `{$tables}`");
  396. }
  397. if (!$list) {
  398. throw new \Exception("data sheet'{$tables}'Repair mistakes please try again!");
  399. }
  400. } else {
  401. throw new \Exception("Please specify the table to be repaired!");
  402. }
  403. }
  404. /**
  405. * 修复表
  406. *
  407. * @param string|null $tables
  408. * @return array
  409. * @throws \think\db\exception\BindParamException
  410. * @throws \think\exception\PDOException
  411. */
  412. public function repair(?string $tables = null)
  413. {
  414. if ($tables) {
  415. $db = self::connect();
  416. if (is_array($tables)) {
  417. $tables = implode('`,`', $tables);
  418. $list = $db->query("REPAIR TABLE `{$tables}`");
  419. } else {
  420. $list = $db->query("REPAIR TABLE `{$tables}`");
  421. }
  422. if ($list) {
  423. return $list;
  424. } else {
  425. throw new \Exception("data sheet'{$tables}'Repair mistakes please try again!");
  426. }
  427. } else {
  428. throw new \Exception("Please specify the table to be repaired!");
  429. }
  430. }
  431. /**
  432. * 写入SQL语句
  433. *
  434. * @param string $sql 要写入的SQL语句
  435. * @return boolean true - 写入成功,false - 写入失败!
  436. */
  437. private function write(string $sql)
  438. {
  439. $size = strlen($sql);
  440. //由于压缩原因,无法计算出压缩后的长度,这里假设压缩率为50%,
  441. //一般情况压缩率都会高于50%;
  442. $size = $this->config['compress'] ? $size / 2 : $size;
  443. $this->open($size);
  444. return $this->config['compress'] ? @gzwrite($this->fp, $sql) : @fwrite($this->fp, $sql);
  445. }
  446. /**
  447. * 打开一个卷,用于写入数据
  448. *
  449. * @param integer $size 写入数据的大小
  450. */
  451. private function open(int $size)
  452. {
  453. if ($this->fp) {
  454. $this->size += $size;
  455. if ($this->size > $this->config['part']) {
  456. $this->config['compress'] ? @gzclose($this->fp) : @fclose($this->fp);
  457. $this->fp = null;
  458. $this->file['part']++;
  459. session('backup_file', $this->file);
  460. $this->Backup_Init();
  461. }
  462. } else {
  463. $backuppath = $this->config['path'];
  464. $filename = "{$backuppath}{$this->file['name']}-{$this->file['part']}.sql";
  465. if ($this->config['compress']) {
  466. $filename = "{$filename}.gz";
  467. $this->fp = @gzopen($filename, "a{$this->config['level']}");
  468. } else {
  469. $this->fp = @fopen($filename, 'a');
  470. }
  471. $this->size = filesize($filename) + $size;
  472. }
  473. }
  474. /**
  475. * 检查目录是否可写
  476. *
  477. * @param string $path
  478. * @return bool
  479. */
  480. protected function checkPath(string $path)
  481. {
  482. if (is_dir($path)) {
  483. return true;
  484. }
  485. if (mkdir($path, 0755, true)) {
  486. return true;
  487. } else {
  488. return false;
  489. }
  490. }
  491. /**
  492. * 析构方法,用于关闭文件资源
  493. */
  494. public function __destruct()
  495. {
  496. $this->config['compress'] ? @gzclose($this->fp) : @fclose($this->fp);
  497. }
  498. }