Database.php 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. <?php
  2. namespace extend\database;
  3. use think\facade\Db;
  4. class Database
  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 $config;
  26. /**
  27. * 数据库备份构造方法
  28. * @param array $file 备份或还原的文件信息
  29. * @param array $config 备份配置信息
  30. * @param string $type 执行类型,export - 备份数据, import - 还原数据
  31. */
  32. public function __construct($file = [], $config = [], $type = 'export')
  33. {
  34. $this->file = $file;
  35. $this->config = $config;
  36. }
  37. /**
  38. * 查询所有表
  39. */
  40. public function getTableList()
  41. {
  42. $table_list = Db::query("SHOW TABLE STATUS");
  43. return success([ 'list' => $table_list ]);
  44. }
  45. /**
  46. * 修复表
  47. */
  48. public function repair($tables)
  49. {
  50. if ($tables) {
  51. Db::startTrans();
  52. try {
  53. if (is_array($tables)) {
  54. $tables = implode('`,`', $tables);
  55. Db::query("REPAIR TABLE `{$tables}`");
  56. } else {
  57. Db::query("REPAIR TABLE `{$tables}`");
  58. }
  59. Db::commit();
  60. return success([], "数据表修复完成");
  61. } catch (\Exception $e) {
  62. // 回滚事务
  63. Db::rollback();
  64. return error([], "数据表修复失败");
  65. }
  66. } else {
  67. return error([], "请指定要修复的表");
  68. }
  69. }
  70. /**
  71. * 打开一个卷,用于写入数据
  72. * @param integer $size 写入数据的大小
  73. */
  74. private function open($size)
  75. {
  76. if ($this->fp) {
  77. $this->size += $size;
  78. if ($this->size > $this->config[ 'part' ]) {
  79. $this->config[ 'compress' ] ? @gzclose($this->fp) : @fclose($this->fp);
  80. $this->fp = null;
  81. $this->file[ 'part' ]++;
  82. session('backup_file', $this->file);
  83. $this->create();
  84. }
  85. } else {
  86. $backuppath = $this->config[ 'path' ];
  87. $filename = "{$backuppath}{$this->file['name']}-{$this->file['part']}.sql";
  88. if ($this->config[ 'compress' ]) {
  89. $filename = "{$filename}.gz";
  90. $this->fp = @gzopen($filename, "a{$this->config['level']}");
  91. } else {
  92. $this->fp = @fopen($filename, 'a');
  93. }
  94. $this->size = filesize($filename) + $size;
  95. }
  96. }
  97. /**
  98. * 写入初始数据
  99. * @return boolean true - 写入成功,false - 写入失败
  100. */
  101. public function create()
  102. {
  103. $config = config('database');
  104. $sql = "-- -----------------------------\n";
  105. $sql .= "-- Niucloud MySQL Data Transfer \n";
  106. $sql .= "-- author niuteam \n";
  107. $sql .= "-- \n";
  108. $sql .= "-- Host : " . $config[ 'connections' ][ 'mysql' ][ 'hostname' ] . "\n";
  109. $sql .= "-- Port : " . $config[ 'connections' ][ 'mysql' ][ 'hostport' ] . "\n";
  110. $sql .= "-- Database : " . $config[ 'connections' ][ 'mysql' ][ 'database' ] . "\n";
  111. $sql .= "-- \n";
  112. $sql .= "-- Part : #{$this->file['part']}\n";
  113. $sql .= "-- Date : " . date("Y-m-d H:i:s") . "\n";
  114. $sql .= "-- -----------------------------\n\n";
  115. $sql .= "SET FOREIGN_KEY_CHECKS = 0;\n\n";
  116. return $this->write($sql);
  117. }
  118. /**
  119. * 写入SQL语句
  120. * @param string $sql 要写入的SQL语句
  121. * @return boolean true - 写入成功,false - 写入失败!
  122. */
  123. private function write($sql)
  124. {
  125. $size = strlen($sql);
  126. //由于压缩原因,无法计算出压缩后的长度,这里假设压缩率为50%,
  127. //一般情况压缩率都会高于50%;
  128. $size = $this->config[ 'compress' ] ? $size / 2 : $size;
  129. $this->open($size);
  130. return $this->config[ 'compress' ] ? @gzwrite($this->fp, $sql) : @fwrite($this->fp, $sql);
  131. }
  132. /**
  133. * 备份表结构
  134. * @param string $table 表名
  135. * @param integer $start 起始行数
  136. * @return boolean false - 备份失败
  137. */
  138. public function backup($table, $start)
  139. {
  140. //备份表结构
  141. if (0 == $start) {
  142. $result = Db::query("SHOW CREATE TABLE `{$table}`");
  143. $sql = "\n";
  144. $sql .= "-- -----------------------------\n";
  145. $sql .= "-- Table structure for `{$table}`\n";
  146. $sql .= "-- -----------------------------\n";
  147. $sql .= "DROP TABLE IF EXISTS `{$table}`;\n";
  148. $sql .= trim($result[ 0 ][ 'Create Table' ]) . ";\n\n";
  149. if (false === $this->write($sql)) {
  150. return false;
  151. }
  152. }
  153. //数据总数
  154. $result = Db::query("SELECT COUNT(*) AS count FROM `{$table}`");
  155. $count = $result[ '0' ][ 'count' ];
  156. //备份表数据
  157. if ($count) {
  158. //写入数据注释
  159. if (0 == $start) {
  160. $sql = "-- -----------------------------\n";
  161. $sql .= "-- Records of `{$table}`\n";
  162. $sql .= "-- -----------------------------\n";
  163. $this->write($sql);
  164. }
  165. //备份数据记录
  166. $result = Db::query("SELECT * FROM `{$table}`");
  167. foreach ($result as $row) {
  168. $row = array_map(
  169. function($item) {
  170. if (is_json($item)) {
  171. return json_encode(json_decode($item, true), JSON_UNESCAPED_UNICODE);
  172. } else {
  173. return $item;
  174. }
  175. },
  176. $row
  177. );
  178. $sql = "INSERT INTO `{$table}` VALUES ('" . implode("', '", $row) . "');\n";
  179. if (false === $this->write($sql)) {
  180. return false;
  181. }
  182. }
  183. }
  184. //备份下一表
  185. return 0;
  186. }
  187. /**
  188. * 还原表数据
  189. * @param unknown $start
  190. */
  191. public function import($start)
  192. {
  193. //还原数据
  194. if ($this->config[ 'compress' ]) {
  195. $gz = gzopen($this->file[ 1 ], 'r');
  196. $size = 0;
  197. } else {
  198. $size = filesize($this->file[ 1 ]);
  199. $gz = fopen($this->file[ 1 ], 'r');
  200. }
  201. $sql = '';
  202. if ($start) {
  203. $this->config[ 'compress' ] ? gzseek($gz, $start) : fseek($gz, $start);
  204. }
  205. for ($i = 0; $i < 1000; $i++) {
  206. $sql .= $this->config[ 'compress' ] ? gzgets($gz) : fgets($gz);
  207. if (preg_match('/.*;$/', trim($sql))) {
  208. // Log::write('恢复sql'.$sql);
  209. if (false !== Db::execute($sql)) {
  210. $start += strlen($sql);
  211. } else {
  212. return false;
  213. }
  214. $sql = '';
  215. } elseif ($this->config[ 'compress' ] ? gzeof($gz) : feof($gz)) {
  216. return 0;
  217. }
  218. }
  219. return array ( $start, $size );
  220. }
  221. /**
  222. * 析构方法,用于关闭文件资源
  223. */
  224. public function __destruct()
  225. {
  226. $this->config[ 'compress' ] ? @gzclose($this->fp) : @fclose($this->fp);
  227. }
  228. }