DbBackup.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  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. public function setSqlMode() {
  261. Db::query("SET sql_mode = '';");
  262. return true;
  263. }
  264. /**
  265. * 导入表
  266. *
  267. * @param $start
  268. * @param $time
  269. * @return array|false|int
  270. * @throws Exception
  271. */
  272. public function import($start, $time)
  273. {
  274. //还原数据
  275. $this->file = $this->getFile('time', $time);
  276. if ($this->config['compress']) {
  277. $gz = gzopen($this->file[0], 'r');
  278. $size = 0;
  279. } else {
  280. $size = filesize($this->file[0]);
  281. $gz = fopen($this->file[0], 'r');
  282. }
  283. $sql = '';
  284. if ($start) {
  285. $this->config['compress'] ? gzseek($gz, $start) : fseek($gz, $start);
  286. }
  287. for ($i = 0; $i < 1000; $i++) {
  288. $sql .= $this->config['compress'] ? gzgets($gz) : fgets($gz);
  289. if (preg_match('/.*;$/', trim($sql))) {
  290. if (false !== Db::query($sql)) {
  291. $start += strlen($sql);
  292. } else {
  293. return false;
  294. }
  295. $sql = '';
  296. } elseif ($this->config['compress'] ? gzeof($gz) : feof($gz)) {
  297. return 0;
  298. }
  299. }
  300. return array($start, $size);
  301. }
  302. /**
  303. * 写入初始数据
  304. *
  305. * @return boolean true - 写入成功,false - 写入失败
  306. */
  307. public function backupInit()
  308. {
  309. $sql = "-- -----------------------------\n";
  310. $sql .= "-- Think MySQL Data Transfer \n";
  311. $sql .= "-- \n";
  312. $sql .= "-- Host : ".$this->dbconfig['hostname']."\n";
  313. $sql .= "-- Port : ".$this->dbconfig['hostport']."\n";
  314. $sql .= "-- Database : ".$this->dbconfig['database']."\n";
  315. $sql .= "-- \n";
  316. $sql .= "-- Part : #{$this->file['part']}\n";
  317. $sql .= "-- Date : ".date("Y-m-d H:i:s")."\n";
  318. $sql .= "-- -----------------------------\n\n";
  319. $sql .= "SET FOREIGN_KEY_CHECKS = 0;\n\n";
  320. return $this->write($sql);
  321. }
  322. /**
  323. * 查询单条
  324. * @param $sql
  325. * @return array|mixed
  326. */
  327. public function selectOne($sql) {
  328. $result = Db::query($sql);
  329. return $result[0] ?? [];
  330. }
  331. /**
  332. * 备份表结构
  333. *
  334. * @param string $table 表名
  335. * @param integer $start 起始行数
  336. * @return boolean false - 备份失败
  337. */
  338. public function backup($table, $start = 0)
  339. {
  340. // 备份表结构
  341. if (0 == $start) {
  342. $result = $this->selectOne("SHOW CREATE TABLE `{$table}`");
  343. $sql = "\n";
  344. $sql .= "-- -----------------------------\n";
  345. $sql .= "-- Table structure for `{$table}`\n";
  346. $sql .= "-- -----------------------------\n";
  347. $sql .= "DROP TABLE IF EXISTS `{$table}`;\n";
  348. $sql .= trim($result['Create Table']).";\n\n";
  349. if (false === $this->write($sql)) {
  350. return false;
  351. }
  352. }
  353. //数据总数
  354. $result = $this->selectOne("SELECT COUNT(*) AS count FROM `{$table}`");
  355. $count = $result['count'];
  356. //备份表数据
  357. if ($count) {
  358. //写入数据注释
  359. if (0 == $start) {
  360. $sql = "-- -----------------------------\n";
  361. $sql .= "-- Records of `{$table}`\n";
  362. $sql .= "-- -----------------------------\n";
  363. $this->write($sql);
  364. }
  365. //备份数据记录
  366. $result = Db::query("SELECT * FROM `{$table}` LIMIT {$start}, 1000");
  367. $sql = "INSERT INTO `{$table}` VALUES\n";
  368. foreach ($result as $index => $row) {
  369. $row = array_map(function ($item){
  370. return is_string($item) ? addslashes($item) : $item;
  371. }, $row);
  372. $sql .= "('".str_replace(array("\r", "\n"), array('\\r', '\\n'),
  373. implode("', '", $row))."')";
  374. $sql .= $index < (count($result) - 1) ? ",\n" : ";\n";
  375. }
  376. if (false === $this->write($sql)) {
  377. return false;
  378. }
  379. //还有更多数据
  380. if ($count > $start + 1000) {
  381. return $this->backup($table, $start + 1000);
  382. }
  383. }
  384. //备份下一表
  385. return true;
  386. }
  387. /**
  388. * 优化表
  389. *
  390. * @param String $tables 表名
  391. * @return String $tables
  392. */
  393. public function optimize($tables = null)
  394. {
  395. if ($tables) {
  396. if (is_array($tables)) {
  397. $tables = implode('`,`', $tables);
  398. $list = db ::select("OPTIMIZE TABLE `{$tables}`");
  399. } else {
  400. $list = Db::query("OPTIMIZE TABLE `{$tables}`");
  401. }
  402. if ($list) {
  403. return $tables;
  404. } else {
  405. throw new \Exception("data sheet'{$tables}'Repair mistakes please try again!");
  406. }
  407. } else {
  408. throw new \Exception("Please specify the table to be repaired!");
  409. }
  410. }
  411. /**
  412. * 修复表
  413. *
  414. * @param String $tables 表名
  415. * @return String $tables
  416. */
  417. public function repair($tables = null)
  418. {
  419. if ($tables) {
  420. if (is_array($tables)) {
  421. $tables = implode('`,`', $tables);
  422. $list = Db::query("REPAIR TABLE `{$tables}`");
  423. } else {
  424. $list = Db::query("REPAIR TABLE `{$tables}`");
  425. }
  426. if ($list) {
  427. return $list;
  428. } else {
  429. throw new \Exception("data sheet'{$tables}'Repair mistakes please try again!");
  430. }
  431. } else {
  432. throw new \Exception("Please specify the table to be repaired!");
  433. }
  434. }
  435. /**
  436. * 写入SQL语句
  437. *
  438. * @param string $sql 要写入的SQL语句
  439. * @return boolean true - 写入成功,false - 写入失败!
  440. */
  441. private function write($sql)
  442. {
  443. $size = strlen($sql);
  444. //由于压缩原因,无法计算出压缩后的长度,这里假设压缩率为50%,
  445. //一般情况压缩率都会高于50%;
  446. $size = $this->config['compress'] ? $size / 2 : $size;
  447. $this->open($size);
  448. return $this->config['compress'] ? @gzwrite($this->fp, $sql) : @fwrite($this->fp, $sql);
  449. }
  450. /**
  451. * 打开一个卷,用于写入数据
  452. *
  453. * @param integer $size 写入数据的大小
  454. */
  455. private function open($size)
  456. {
  457. if ($this->fp) {
  458. $this->size += $size;
  459. if ($this->size > $this->config['part']) {
  460. $this->config['compress'] ? @gzclose($this->fp) : @fclose($this->fp);
  461. $this->fp = null;
  462. $this->file['part']++;
  463. session('backup_file', $this->file);
  464. $this->backupInit();
  465. }
  466. } else {
  467. $backuppath = $this->config['path'];
  468. $filename = "{$backuppath}{$this->file['name']}-{$this->file['part']}.sql";
  469. if ($this->config['compress']) {
  470. $filename = "{$filename}.gz";
  471. $this->fp = @gzopen($filename, "a{$this->config['level']}");
  472. } else {
  473. $this->fp = @fopen($filename, 'a');
  474. }
  475. $this->size = filesize($filename) + $size;
  476. }
  477. }
  478. /**
  479. * 检查目录是否可写
  480. *
  481. * @param string $path 目录
  482. * @return boolean
  483. */
  484. protected function checkPath($path)
  485. {
  486. if (is_dir($path)) {
  487. return true;
  488. }
  489. if (mkdir($path, 0755, true)) {
  490. return true;
  491. } else {
  492. return false;
  493. }
  494. }
  495. /**
  496. * 析构方法,用于关闭文件资源
  497. */
  498. public function __destruct()
  499. {
  500. if ($this->fp) {
  501. $this->config['compress'] ? @gzclose($this->fp) : @fclose($this->fp);
  502. }
  503. }
  504. }