Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

MysqlBackupService.php 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  1. <?php
  2. namespace crmeb\services;
  3. use think\facade\Db;
  4. class MysqlBackupService
  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. 'path' => './Data/',
  32. //数据库备份路径
  33. 'part' => 20971520,
  34. //数据库备份卷大小
  35. 'compress' => 0,
  36. //数据库备份文件是否启用压缩 0不压缩 1 压缩
  37. 'level' => 9,
  38. );
  39. /**
  40. * 数据库备份构造方法
  41. *
  42. * @param array $file 备份或还原的文件信息
  43. * @param array $config 备份配置信息
  44. */
  45. public function __construct($config = [])
  46. {
  47. $this->config['path'] = app()->getRootPath() . 'backup/';
  48. $this->config = array_merge($this->config, $config);
  49. //初始化文件名
  50. $this->setFile();
  51. //初始化数据库连接参数
  52. $this->setDbConn();
  53. //检查文件是否可写
  54. if (!$this->checkPath($this->config['path'])) {
  55. throw new \Exception("The current directory is not writable");
  56. }
  57. }
  58. /**
  59. * 设置脚本运行超时时间
  60. * 0表示不限制,支持连贯操作
  61. */
  62. public function setTimeout($time = null)
  63. {
  64. if (!is_null($time)) {
  65. set_time_limit($time) || ini_set("max_execution_time", $time);
  66. }
  67. return $this;
  68. }
  69. /**
  70. * 设置数据库连接必备参数
  71. *
  72. * @param array $dbconfig 数据库连接配置信息
  73. * @return $this
  74. */
  75. public function setDbConn($dbconfig = [])
  76. {
  77. if (empty($dbconfig)) {
  78. $this->dbconfig = config('database.connections.' . config('database.default'));
  79. //$this->dbconfig = Config::get('database');
  80. } else {
  81. $this->dbconfig = $dbconfig;
  82. }
  83. return $this;
  84. }
  85. /**
  86. * 设置备份文件名
  87. *
  88. * @param null $file
  89. * @return $this
  90. */
  91. public function setFile($file = null)
  92. {
  93. if (is_null($file)) {
  94. $this->file = ['name' => date('Ymd-His'), 'part' => 1];
  95. } else {
  96. if (!array_key_exists("name", $file) && !array_key_exists("part", $file)) {
  97. $this->file = $file['1'];
  98. } else {
  99. $this->file = $file;
  100. }
  101. }
  102. return $this;
  103. }
  104. //数据类连接
  105. public static function connect()
  106. {
  107. return Db::connect();
  108. }
  109. /**
  110. * 数据库表列表
  111. *
  112. * @param null $table
  113. * @param int $type
  114. * @return array
  115. * @throws \think\db\exception\BindParamException
  116. * @throws \think\exception\PDOException
  117. */
  118. public function dataList(?string $table = null, int $type = 1)
  119. {
  120. $key = 'mysql_backup_' . $table . '_' . $type;
  121. $data = CacheService::get($key);
  122. if (!$data) {
  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. $data = array_map('array_change_key_case', $list);
  134. CacheService::set($key, $data, 7200);
  135. }
  136. return $data;
  137. }
  138. /**
  139. * 数据库备份文件列表
  140. *
  141. * @return array
  142. */
  143. public function fileList()
  144. {
  145. $list = [];
  146. if (!is_dir($this->config['path'])) {
  147. mkdir($this->config['path'], 0755, true);
  148. return $list;
  149. }
  150. $path = realpath($this->config['path']);
  151. $flag = \FilesystemIterator::KEY_AS_FILENAME;
  152. $glob = new \FilesystemIterator($path, $flag);
  153. foreach ($glob as $name => $file) {
  154. if (preg_match('/^\\d{8,8}-\\d{6,6}-\\d+\\.sql(?:\\.gz)?$/', $name)) {
  155. $info['filename'] = $name;
  156. $name = sscanf($name, '%4s%2s%2s-%2s%2s%2s-%d');
  157. $date = $name[0] . '-' . $name[1] . '-' . $name[2];
  158. $time = $name[3] . ':' . $name[4] . ':' . $name[5];
  159. $part = $name[6];
  160. if (isset($list[$date . $time])) {
  161. $info = $list[$date . $time];
  162. $info['part'] = max($info['part'], $part);
  163. $info['size'] = $info['size'] + $file->getSize();
  164. } else {
  165. $info['part'] = $part;
  166. $info['size'] = $file->getSize();
  167. }
  168. $extension = strtoupper(pathinfo($file->getFilename(), PATHINFO_EXTENSION));
  169. $info['compress'] = $extension === 'SQL' ? '-' : $extension;
  170. $info['time'] = strtotime($date . $time);
  171. $list[$date . $time] = $info;
  172. }
  173. }
  174. return $list;
  175. }
  176. /**
  177. * @param string $type
  178. * @param int $time
  179. * @return array|false|string
  180. * @throws \Exception
  181. */
  182. public function getFile($type = '', $time = 0)
  183. {
  184. //
  185. if (!is_numeric($time)) {
  186. throw new \Exception("{$time} Illegal data type");
  187. }
  188. switch ($type) {
  189. case 'time':
  190. $name = date('Ymd-His', $time) . '-*.sql*';
  191. $path = realpath($this->config['path']) . DIRECTORY_SEPARATOR . $name;
  192. return glob($path);
  193. break;
  194. case 'timeverif':
  195. $name = date('Ymd-His', $time) . '-*.sql*';
  196. $path = realpath($this->config['path']) . DIRECTORY_SEPARATOR . $name;
  197. $files = glob($path);
  198. $list = array();
  199. foreach ($files as $name) {
  200. $basename = basename($name);
  201. $match = sscanf($basename, '%4s%2s%2s-%2s%2s%2s-%d');
  202. $gz = preg_match('/^\\d{8,8}-\\d{6,6}-\\d+\\.sql.gz$/', $basename);
  203. $list[$match[6]] = array($match[6], $name, $gz);
  204. }
  205. $last = end($list);
  206. if (count($list) === $last[0]) {
  207. return $list;
  208. } else {
  209. throw new \Exception("File {$files['0']} may be damaged, please check again");
  210. }
  211. break;
  212. case 'pathname':
  213. return "{$this->config['path']}{$this->file['name']}-{$this->file['part']}.sql";
  214. break;
  215. case 'filename':
  216. return "{$this->file['name']}-{$this->file['part']}.sql";
  217. break;
  218. case 'filepath':
  219. return $this->config['path'];
  220. break;
  221. default:
  222. $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);
  223. return $arr;
  224. }
  225. }
  226. /**
  227. * 删除备份文件
  228. * @param $time
  229. * @return mixed
  230. * @throws \Exception
  231. */
  232. public function delFile($time)
  233. {
  234. if ($time) {
  235. $file = $this->getFile('time', $time);
  236. array_map("unlink", $this->getFile('time', $time));
  237. if (count($this->getFile('time', $time))) {
  238. throw new \Exception("File {$time} deleted failed");
  239. } else {
  240. return $time;
  241. }
  242. } else {
  243. throw new \Exception("{$time} Time parameter is incorrect");
  244. }
  245. }
  246. /**
  247. * 下载备份
  248. *
  249. * @param $time
  250. * @param int $part
  251. * @throws \Exception
  252. */
  253. public function downloadFile($time, int $part = 0, bool $isFile = false)
  254. {
  255. $file = $this->getFile('time', $time);
  256. $fileName = $file[$part];
  257. if (file_exists($fileName)) {
  258. if ($isFile) {
  259. $key = password_hash(time() . $fileName, PASSWORD_DEFAULT);
  260. CacheService::set($key, ['path' => $fileName, 'fileName' => substr(strstr($fileName, 'backup'), 7)], 300);
  261. return $key;
  262. }
  263. ob_end_clean();
  264. header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
  265. header('Content-Description: File Transfer');
  266. header('Access-Control-Allow-Origin: ' . request()->domain());
  267. header('Content-Type: application/octet-stream');
  268. header('Content-Length: ' . filesize($fileName));
  269. header('Content-Disposition: attachment; filename=' . basename($fileName));
  270. return 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, $sql = '')
  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. }
  347. //数据总数
  348. $result = $db->query("SELECT COUNT(*) AS count FROM `{$table}`");
  349. $count = $result['0']['count'];
  350. //备份表数据
  351. if ($count) {
  352. //写入数据注释
  353. if (0 == $start) {
  354. $sql .= "-- -----------------------------\n";
  355. $sql .= "-- Records of `{$table}`\n";
  356. $sql .= "-- -----------------------------\n";
  357. }
  358. //备份数据记录
  359. $result = $db->query("SELECT * FROM `{$table}` LIMIT :MIN, 1000", ['MIN' => intval($start)]);
  360. foreach ($result as $row) {
  361. $row = array_map('addslashes', $row);
  362. $sql .= "INSERT INTO `{$table}` VALUES ('" . str_replace(array("\r", "\n"), array('\\r', '\\n'), implode("', '", $row)) . "');\n";
  363. }
  364. if (false === $this->write($sql)) {
  365. return false;
  366. }
  367. //还有更多数据
  368. if ($count > $start + 1000) {
  369. //return array($start + 1000, $count);
  370. return $this->backup($table, $start + 1000);
  371. }
  372. }
  373. //备份下一表
  374. return 0;
  375. }
  376. /**
  377. * 优化表
  378. *
  379. * @param array|string $tables
  380. * @throws \think\db\exception\BindParamException
  381. * @throws \think\exception\PDOException
  382. */
  383. public function optimize($tables)
  384. {
  385. if ($tables) {
  386. $db = self::connect();
  387. if (is_array($tables)) {
  388. $tables = implode('`,`', $tables);
  389. $list = $db->query("OPTIMIZE TABLE `{$tables}`");
  390. } else {
  391. $list = $db->query("OPTIMIZE TABLE {$tables}");
  392. }
  393. if (!$list) {
  394. throw new \Exception("data sheet'{$tables}'Repair mistakes please try again!");
  395. }
  396. return $list;
  397. } else {
  398. throw new \Exception("Please specify the table to be repaired!");
  399. }
  400. }
  401. /**
  402. * 修复表
  403. *
  404. * @param string|null $tables
  405. * @return array
  406. * @throws \think\db\exception\BindParamException
  407. * @throws \think\exception\PDOException
  408. */
  409. public function repair(?string $tables = null)
  410. {
  411. if ($tables) {
  412. $db = self::connect();
  413. if (is_array($tables)) {
  414. $tables = implode('`,`', $tables);
  415. $list = $db->query("REPAIR TABLE `{$tables}`");
  416. } else {
  417. $list = $db->query("REPAIR TABLE {$tables}");
  418. }
  419. if ($list) {
  420. return $list;
  421. } else {
  422. throw new \Exception("data sheet'{$tables}'Repair mistakes please try again!");
  423. }
  424. } else {
  425. throw new \Exception("Please specify the table to be repaired!");
  426. }
  427. }
  428. /**
  429. * 写入SQL语句
  430. *
  431. * @param string $sql 要写入的SQL语句
  432. * @return boolean true - 写入成功,false - 写入失败!
  433. */
  434. private function write(string $sql)
  435. {
  436. $size = strlen($sql);
  437. //由于压缩原因,无法计算出压缩后的长度,这里假设压缩率为50%,
  438. //一般情况压缩率都会高于50%;
  439. $size = $this->config['compress'] ? $size / 2 : $size;
  440. $this->open($size);
  441. return $this->config['compress'] ? @gzwrite($this->fp, $sql) : @fwrite($this->fp, $sql);
  442. }
  443. /**
  444. * 打开一个卷,用于写入数据
  445. *
  446. * @param integer $size 写入数据的大小
  447. */
  448. private function open(int $size)
  449. {
  450. if ($this->fp) {
  451. $this->size += $size;
  452. if ($this->size > $this->config['part']) {
  453. $this->config['compress'] ? @gzclose($this->fp) : @fclose($this->fp);
  454. $this->fp = null;
  455. $this->file['part']++;
  456. session('backup_file', $this->file);
  457. $this->Backup_Init();
  458. }
  459. } else {
  460. $backuppath = $this->config['path'];
  461. $filename = "{$backuppath}{$this->file['name']}-{$this->file['part']}.sql";
  462. if ($this->config['compress']) {
  463. $filename = "{$filename}.gz";
  464. $this->fp = @gzopen($filename, "a{$this->config['level']}");
  465. } else {
  466. $this->fp = @fopen($filename, 'a');
  467. }
  468. $this->size = filesize($filename) + $size;
  469. }
  470. }
  471. /**
  472. * 检查目录是否可写
  473. *
  474. * @param string $path
  475. * @return bool
  476. */
  477. protected function checkPath(string $path)
  478. {
  479. if (is_dir($path)) {
  480. return true;
  481. }
  482. if (mkdir($path, 0755, true)) {
  483. return true;
  484. } else {
  485. return false;
  486. }
  487. }
  488. /**
  489. * 析构方法,用于关闭文件资源
  490. */
  491. public function __destruct()
  492. {
  493. $this->config['compress'] ? @gzclose($this->fp) : @fclose($this->fp);
  494. }
  495. }