Database.php 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. <?php
  2. namespace com;
  3. use think\Db;
  4. use think\Config;
  5. use think\Session;
  6. //数据导出模型
  7. class Database{
  8. /**
  9. * 文件指针
  10. * @var resource
  11. */
  12. private $fp;
  13. /**
  14. * 备份文件信息 part - 卷号,name - 文件名
  15. * @var array
  16. */
  17. private $file;
  18. /**
  19. * 当前打开文件大小
  20. * @var integer
  21. */
  22. private $size = 0;
  23. /**
  24. * 备份配置
  25. * @var integer
  26. */
  27. private $config;
  28. /**
  29. * 数据库备份构造方法
  30. * @param array $file 备份或还原的文件信息
  31. * @param array $config 备份配置信息
  32. * @param string $type 执行类型,export - 备份数据, import - 还原数据
  33. */
  34. public function __construct($file, $config, $type = 'export'){
  35. $this->file = $file;
  36. $this->config = $config;
  37. }
  38. /**
  39. * 打开一个卷,用于写入数据
  40. * @param integer $size 写入数据的大小
  41. */
  42. private function open($size){
  43. if($this->fp){
  44. $this->size += $size;
  45. if($this->size > $this->config['part']){
  46. $this->config['compress'] ? @gzclose($this->fp) : @fclose($this->fp);
  47. $this->fp = null;
  48. $this->file['part']++;
  49. Session::set('backup_file', $this->file);
  50. $this->create();
  51. }
  52. } else {
  53. $backuppath = $this->config['path'];
  54. $filename = "{$backuppath}{$this->file['name']}-{$this->file['part']}.sql";
  55. if($this->config['compress']){
  56. $filename = "{$filename}.gz";
  57. $this->fp = @gzopen($filename, "a{$this->config['level']}");
  58. } else {
  59. $this->fp = @fopen($filename, 'a');
  60. }
  61. $this->size = filesize($filename) + $size;
  62. }
  63. }
  64. /**
  65. * 写入初始数据
  66. * @return boolean true - 写入成功,false - 写入失败
  67. */
  68. public function create(){
  69. $sql = "-- -----------------------------\n";
  70. $sql .= "-- Think MySQL Data Transfer \n";
  71. $sql .= "-- \n";
  72. $sql .= "-- Host : " . Config::get('database.hostname') . "\n";
  73. $sql .= "-- Port : " . Config::get('database.hostport') . "\n";
  74. $sql .= "-- Database : " . Config::get('database.database') . "\n";
  75. $sql .= "-- \n";
  76. $sql .= "-- Part : #{$this->file['part']}\n";
  77. $sql .= "-- Date : " . date("Y-m-d H:i:s") . "\n";
  78. $sql .= "-- -----------------------------\n\n";
  79. $sql .= "SET FOREIGN_KEY_CHECKS = 0;\n\n";
  80. return $this->write($sql);
  81. }
  82. /**
  83. * 写入SQL语句
  84. * @param string $sql 要写入的SQL语句
  85. * @return boolean true - 写入成功,false - 写入失败!
  86. */
  87. private function write($sql){
  88. $size = strlen($sql);
  89. //由于压缩原因,无法计算出压缩后的长度,这里假设压缩率为50%,
  90. //一般情况压缩率都会高于50%;
  91. $size = $this->config['compress'] ? $size / 2 : $size;
  92. $this->open($size);
  93. return $this->config['compress'] ? @gzwrite($this->fp, $sql) : @fwrite($this->fp, $sql);
  94. }
  95. /**
  96. * 备份表结构
  97. * @param string $table 表名
  98. * @param integer $start 起始行数
  99. * @return boolean false - 备份失败
  100. */
  101. public function backup($table, $start){
  102. //创建DB对象
  103. $db = Db::connect();
  104. //备份表结构
  105. if(0 == $start){
  106. $result = $db->query("SHOW CREATE TABLE `{$table}`");
  107. $sql = "\n";
  108. $sql .= "-- -----------------------------\n";
  109. $sql .= "-- Table structure for `{$table}`\n";
  110. $sql .= "-- -----------------------------\n";
  111. $sql .= "DROP TABLE IF EXISTS `{$table}`;\n";
  112. $sql .= trim($result[0]['Create Table']) . ";\n\n";
  113. if(false === $this->write($sql)){
  114. return false;
  115. }
  116. }
  117. //数据总数
  118. $result = $db->query("SELECT COUNT(*) AS count FROM `{$table}`");
  119. $count = $result['0']['count'];
  120. //备份表数据
  121. if($count){
  122. //写入数据注释
  123. if(0 == $start){
  124. $sql = "-- -----------------------------\n";
  125. $sql .= "-- Records of `{$table}`\n";
  126. $sql .= "-- -----------------------------\n";
  127. $this->write($sql);
  128. }
  129. //备份数据记录
  130. $result = $db->query("SELECT * FROM `{$table}` LIMIT {$start}, 1000");
  131. foreach ($result as $row) {
  132. $row = array_map('addslashes', $row);
  133. $sql = "INSERT INTO `{$table}` VALUES ('" . str_replace(array("\r","\n"),array('\r','\n'),implode("', '", $row)) . "');\n";
  134. if(false === $this->write($sql)){
  135. return false;
  136. }
  137. }
  138. //还有更多数据
  139. if($count > $start + 1000){
  140. return array($start + 1000, $count);
  141. }
  142. }
  143. //备份下一表
  144. return 0;
  145. }
  146. public function import($start){
  147. //还原数据
  148. $db = Db::connect();
  149. if($this->config['compress']){
  150. $gz = gzopen($this->file[1], 'r');
  151. $size = 0;
  152. } else {
  153. $size = filesize($this->file[1]);
  154. $gz = fopen($this->file[1], 'r');
  155. }
  156. $sql = '';
  157. if($start){
  158. $this->config['compress'] ? gzseek($gz, $start) : fseek($gz, $start);
  159. }
  160. for($i = 0; $i < 100; $i++){
  161. $sql .= $this->config['compress'] ? gzgets($gz) : fgets($gz);
  162. if(preg_match('/.*;$/', trim($sql))){
  163. if(false !== $db->execute($sql)){
  164. $start += strlen($sql);
  165. } else {
  166. return false;
  167. }
  168. $sql = '';
  169. } elseif ($this->config['compress'] ? gzeof($gz) : feof($gz)) {
  170. return 0;
  171. }
  172. }
  173. return array($start, $size);
  174. }
  175. /**
  176. * 析构方法,用于关闭文件资源
  177. */
  178. public function __destruct(){
  179. $this->config['compress'] ? @gzclose($this->fp) : @fclose($this->fp);
  180. }
  181. }