Backup.php 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: liu21st <liu21st@gmail.com>
  10. // +----------------------------------------------------------------------
  11. namespace mall;
  12. use think\facade\Db;
  13. //数据导出模型
  14. class Backup{
  15. /**
  16. * 文件指针
  17. * @var resource
  18. */
  19. private $fp;
  20. /**
  21. * 备份文件信息 part - 卷号,name - 文件名
  22. * @var array
  23. */
  24. private $file;
  25. /**
  26. * 当前打开文件大小
  27. * @var integer
  28. */
  29. private $size = 0;
  30. /**
  31. * 备份配置
  32. * @var integer
  33. */
  34. private $config;
  35. /**
  36. * 数据库备份构造方法
  37. * @param array $file 备份或还原的文件信息
  38. * @param array $config 备份配置信息
  39. * @param string $type 执行类型,export - 备份数据, import - 还原数据
  40. */
  41. public function __construct($file, $config, $type = 'export'){
  42. $this->file = $file;
  43. $this->config = $config;
  44. }
  45. /**
  46. * 打开一个卷,用于写入数据
  47. * @param integer $size 写入数据的大小
  48. */
  49. private function open($size){
  50. if($this->fp){
  51. $this->size += $size;
  52. if($this->size > $this->config['part']){
  53. $this->config['compress'] ? @gzclose($this->fp) : @fclose($this->fp);
  54. $this->fp = null;
  55. $this->file['part']++;
  56. session('backup_file', $this->file);
  57. $this->create();
  58. }
  59. } else {
  60. $backuppath = $this->config['path'];
  61. $filename = "{$backuppath}{$this->file['name']}-{$this->file['part']}.sql";
  62. if($this->config['compress']){
  63. $filename = "{$filename}.gz";
  64. $this->fp = @gzopen($filename, "a{$this->config['level']}");
  65. } else {
  66. $this->fp = @fopen($filename, 'a');
  67. }
  68. $this->size = filesize($filename) + $size;
  69. }
  70. }
  71. /**
  72. * 写入初始数据
  73. * @return boolean true - 写入成功,false - 写入失败
  74. */
  75. public function create(){
  76. $sql = "-- -----------------------------\n";
  77. $sql .= "-- Think MySQL Data Transfer \n";
  78. $sql .= "-- \n";
  79. $sql .= "-- Host : " . config('database.hostname') . "\n";
  80. $sql .= "-- Port : " . config('database.hostport') . "\n";
  81. $sql .= "-- Database : " . config('database.database') . "\n";
  82. $sql .= "-- \n";
  83. $sql .= "-- Part : #{$this->file['part']}\n";
  84. $sql .= "-- Date : " . date("Y-m-d H:i:s") . "\n";
  85. $sql .= "-- -----------------------------\n\n";
  86. $sql .= "SET FOREIGN_KEY_CHECKS = 0;\n\n";
  87. return $this->write($sql);
  88. }
  89. /**
  90. * 写入SQL语句
  91. * @param string $sql 要写入的SQL语句
  92. * @return boolean true - 写入成功,false - 写入失败!
  93. */
  94. private function write($sql){
  95. $size = strlen($sql);
  96. //由于压缩原因,无法计算出压缩后的长度,这里假设压缩率为50%,
  97. //一般情况压缩率都会高于50%;
  98. $size = $this->config['compress'] ? $size / 2 : $size;
  99. $this->open($size);
  100. return $this->config['compress'] ? @gzwrite($this->fp, $sql) : @fwrite($this->fp, $sql);
  101. }
  102. /**
  103. * 备份表结构
  104. * @param string $table 表名
  105. * @param integer $start 起始行数
  106. * @return boolean false - 备份失败
  107. */
  108. public function backup($table, $start){
  109. //备份表结构
  110. if(0 == $start){
  111. $result = Db::name($table)->query("SHOW CREATE TABLE `{$table}`");
  112. $sql = "\n";
  113. $sql .= "-- -----------------------------\n";
  114. $sql .= "-- Table structure for `{$table}`\n";
  115. $sql .= "-- -----------------------------\n";
  116. $sql .= "DROP TABLE IF EXISTS `{$table}`;\n";
  117. $sql .= trim($result[0]['Create Table']) . ";\n\n";
  118. if(false === $this->write($sql)){
  119. return false;
  120. }
  121. }
  122. //数据总数
  123. $result = Db::name($table)->query("SELECT COUNT(*) AS count FROM `{$table}`");
  124. $count = $result['0']['count'];
  125. //备份表数据
  126. if($count){
  127. //写入数据注释
  128. if(0 == $start){
  129. $sql = "-- -----------------------------\n";
  130. $sql .= "-- Records of `{$table}`\n";
  131. $sql .= "-- -----------------------------\n";
  132. $this->write($sql);
  133. }
  134. //备份数据记录
  135. $result = Db::name($table)->query("SELECT * FROM `{$table}` LIMIT {$start}, 1000");
  136. foreach ($result as $row) {
  137. $row = array_map('addslashes', $row);
  138. $sql = "INSERT INTO `{$table}` VALUES ('" . str_replace(array("\r","\n"),array('\r','\n'),implode("', '", $row)) . "');\n";
  139. if(false === $this->write($sql)){
  140. return false;
  141. }
  142. }
  143. //还有更多数据
  144. if($count > $start + 1000){
  145. return array($start + 1000, $count);
  146. }
  147. }
  148. //备份下一表
  149. return 0;
  150. }
  151. public function import($start){
  152. //还原数据
  153. if($this->config['compress']){
  154. $gz = gzopen($this->file[1], 'r');
  155. $size = 0;
  156. } else {
  157. $size = filesize($this->file[1]);
  158. $gz = fopen($this->file[1], 'r');
  159. }
  160. $sql = '';
  161. if($start){
  162. $this->config['compress'] ? gzseek($gz, $start) : fseek($gz, $start);
  163. }
  164. for($i = 0; $i < 1000; $i++){
  165. $sql .= $this->config['compress'] ? gzgets($gz) : fgets($gz);
  166. if(preg_match('/.*;$/', trim($sql))){
  167. if(false !== Db::name($start)->execute($sql)){
  168. $start += strlen($sql);
  169. } else {
  170. return false;
  171. }
  172. $sql = '';
  173. } elseif ($this->config['compress'] ? gzeof($gz) : feof($gz)) {
  174. return 0;
  175. }
  176. }
  177. return array($start, $size);
  178. }
  179. /**
  180. * 析构方法,用于关闭文件资源
  181. */
  182. public function __destruct(){
  183. $this->config['compress'] ? @gzclose($this->fp) : @fclose($this->fp);
  184. }
  185. /**
  186. * 解析
  187. * @access public
  188. * @param mixed $filename
  189. * @return mixed
  190. */
  191. public static function parseSql($filename){
  192. $lines=file($filename);
  193. $lines[0]=str_replace(chr(239).chr(187).chr(191),"",$lines[0]);//去除BOM头
  194. $flage = true;
  195. $sqls = array();
  196. $sql="";
  197. foreach($lines as $line)
  198. {
  199. $line=trim($line);
  200. $char=substr($line,0,1);
  201. if($char!='#' && strlen($line)>0)
  202. {
  203. $prefix=substr($line,0,2);
  204. switch($prefix)
  205. {
  206. case '/*':
  207. {
  208. $flage=(substr($line,-3)=='*/;'||substr($line,-2)=='*/')?true:false;
  209. break 1;
  210. }
  211. case '--': break 1;
  212. default :
  213. {
  214. if($flage)
  215. {
  216. $sql.=$line;
  217. if(substr($line,-1)==";")
  218. {
  219. $sqls[]=$sql;
  220. $sql="";
  221. }
  222. }
  223. if(!$flage)$flage=(substr($line,-3)=='*/;'||substr($line,-2)=='*/')?true:false;
  224. }
  225. }
  226. }
  227. }
  228. return $sqls;
  229. }
  230. /**
  231. * 安装
  232. * @access public
  233. * @param mixed $sqls
  234. * @return mixed
  235. */
  236. public static function install($sqls){
  237. $flag = true;
  238. if(is_array($sqls))
  239. {
  240. foreach($sqls as $sql)
  241. {
  242. if(Db::name()->execute($sql) === false){ $flag = false;}
  243. }
  244. }
  245. return $flag;
  246. }
  247. }