DbBackup.php 16 KB

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