MysqlBackupService.php 16 KB

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