123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324 |
- <?php
- // +----------------------------------------------------------------------
- // | 海豚PHP框架 [ DolphinPHP ]
- // +----------------------------------------------------------------------
- // | 版权所有 2016~2017 河源市卓锐科技有限公司 [ http://www.zrthink.com ]
- // +----------------------------------------------------------------------
- // | 官方网站: http://dolphinphp.com
- // +----------------------------------------------------------------------
- // | 开源协议 ( http://www.apache.org/licenses/LICENSE-2.0 )
- // +----------------------------------------------------------------------
- namespace util;
- use think\Db;
- /**
- * 导出数据表到文件
- * @author 麦当苗儿 <zuojiazi@vip.qq.com>
- * @alter CaiWeiMing <314013107@qq.com>
- */
- class Database
- {
- /**
- * 文件指针
- * @var resource
- */
- private $fp;
- /**
- * 备份文件信息 part - 卷号,name - 文件名
- * @var array
- */
- private $file;
- /**
- * 当前打开文件大小
- * @var integer
- */
- private $size = 0;
- /**
- * 备份配置
- * @var integer
- */
- private $config;
- /**
- * 数据库备份构造方法
- * @param array $file 备份或还原的文件信息
- * @param array $config 备份配置信息
- * @param string $type 执行类型,export - 备份数据, import - 还原数据
- */
- public function __construct($file, $config, $type = 'export'){
- $this->file = $file;
- $this->config = $config;
- }
- /**
- * 打开一个卷,用于写入数据
- * @param integer $size 写入数据的大小
- */
- private function open($size = 0){
- if($this->fp){
- $this->size += $size;
- if($this->size > $this->config['part']){
- $this->config['compress'] ? @gzclose($this->fp) : @fclose($this->fp);
- $this->fp = null;
- $this->file['part']++;
- session('backup_file', $this->file);
- $this->create();
- }
- } else {
- $backup_path = $this->config['path'];
- $filename = "{$backup_path}{$this->file['name']}-{$this->file['part']}.sql";
- if($this->config['compress']){
- $filename = "{$filename}.gz";
- $this->fp = @gzopen($filename, "a{$this->config['level']}");
- } else {
- $this->fp = @fopen($filename, 'a');
- }
- $this->size = filesize($filename) + $size;
- }
- }
- /**
- * 写入初始数据
- * @return mixed
- */
- public function create(){
- $sql = "-- -----------------------------\n";
- $sql .= "-- MySQL Data Transfer\n";
- $sql .= "--\n";
- $sql .= "-- Host : " . config('database.hostname') . "\n";
- $sql .= "-- Port : " . config('database.hostport') . "\n";
- $sql .= "-- Database : " . config('database.database') . "\n";
- $sql .= "--\n";
- $sql .= "-- Part : #{$this->file['part']}\n";
- $sql .= "-- Date : " . date("Y-m-d H:i:s") . "\n";
- $sql .= "-- -----------------------------\n\n";
- $sql .= "SET FOREIGN_KEY_CHECKS = 0;\n\n";
- return $this->write($sql);
- }
- /**
- * 写入SQL语句
- * @param string $sql 要写入的SQL语句
- * @return int
- */
- private function write($sql = ''){
- $size = strlen($sql);
- // 由于压缩原因,无法计算出压缩后的长度,这里假设压缩率为50%,
- // 一般情况压缩率都会高于50%;
- $size = $this->config['compress'] ? $size / 2 : $size;
- $this->open($size);
- return $this->config['compress'] ? @gzwrite($this->fp, $sql) : @fwrite($this->fp, $sql);
- }
- /**
- * 备份表结构
- * @param string $table 表名
- * @param integer $start 起始行数
- * @return array|bool|int false - 备份失败
- */
- public function backup($table = '', $start = 0){
- // 备份表结构
- if(0 == $start){
- $result = Db::query("SHOW CREATE TABLE `{$table}`");
- $result = array_map('array_change_key_case', $result);
- $sql = "\n";
- $sql .= "-- -----------------------------\n";
- $sql .= "-- Table structure for `{$table}`\n";
- $sql .= "-- -----------------------------\n";
- $sql .= "DROP TABLE IF EXISTS `{$table}`;\n";
- $sql .= trim($result[0]['create table']) . ";\n\n";
- if(false === $this->write($sql)){
- return false;
- }
- }
- // 数据总数
- $result = Db::query("SELECT COUNT(*) AS count FROM `{$table}`");
- $count = $result['0']['count'];
- //备份表数据
- if($count){
- // 写入数据注释
- if(0 == $start){
- $sql = "-- -----------------------------\n";
- $sql .= "-- Records of `{$table}`\n";
- $sql .= "-- -----------------------------\n";
- $this->write($sql);
- }
- // 备份数据记录
- $result = Db::query("SELECT * FROM `{$table}` LIMIT {$start}, 1000");
- foreach ($result as $row) {
- $row = array_map('addslashes', $row);
- $sql = "INSERT INTO `{$table}` VALUES ('" . str_replace(array("\r","\n"),array('\r','\n'),implode("', '", $row)) . "');\n";
- if(false === $this->write($sql)){
- return false;
- }
- }
- //还有更多数据
- if($count > $start + 1000){
- return array($start + 1000, $count);
- }
- }
- // 备份下一表
- return 0;
- }
- /**
- * 导入数据
- * @param integer $start 起始位置
- * @return array|bool|int
- */
- public function import($start = 0){
- if($this->config['compress']){
- $gz = gzopen($this->file[1], 'r');
- $size = 0;
- } else {
- $size = filesize($this->file[1]);
- $gz = fopen($this->file[1], 'r');
- }
- $sql = '';
- if($start){
- $this->config['compress'] ? gzseek($gz, $start) : fseek($gz, $start);
- }
- for($i = 0; $i < 1000; $i++){
- $sql .= $this->config['compress'] ? gzgets($gz) : fgets($gz);
- if(preg_match('/.*;$/', trim($sql))){
- if(false !== Db::execute($sql)){
- $start += strlen($sql);
- } else {
- return false;
- }
- $sql = '';
- } elseif ($this->config['compress'] ? gzeof($gz) : feof($gz)) {
- return 0;
- }
- }
- return array($start, $size);
- }
- /**
- * 导出
- * @param array $tables 表名
- * @param string $path 导出路径
- * @param string $prefix 表前缀
- * @param integer $export_data 是否导出数据
- * @author 蔡伟明 <314013107@qq.com>
- * @return bool
- */
- public static function export($tables = [], $path = '', $prefix = '', $export_data = 1){
- $tables = is_array($tables) ? $tables : explode(',', $tables);
- $datetime = date('Y-m-d H:i:s', time());
- $sql = "-- -----------------------------\n";
- $sql .= "-- 导出时间 `{$datetime}`\n";
- $sql .= "-- -----------------------------\n";
- if (!empty($tables)) {
- foreach ($tables as $table) {
- $sql .= self::getSql($prefix.$table, $export_data);
- }
- // 写入文件
- if (file_put_contents($path, $sql)) {
- return true;
- };
- }
- return false;
- }
- /**
- * 导出卸载文件
- * @param array $tables 表名
- * @param string $path 导出路径
- * @param string $prefix 表前缀
- * @author 蔡伟明 <314013107@qq.com>
- * @return bool
- */
- public static function exportUninstall($tables = [], $path = '', $prefix = ''){
- $tables = is_array($tables) ? $tables : explode(',', $tables);
- $datetime = date('Y-m-d H:i:s', time());
- $sql = "-- -----------------------------\n";
- $sql .= "-- 导出时间 `{$datetime}`\n";
- $sql .= "-- -----------------------------\n";
- if (!empty($tables)) {
- foreach ($tables as $table) {
- $sql .= "DROP TABLE IF EXISTS `{$prefix}{$table}`;\n";
- }
- // 写入文件
- if (file_put_contents($path, $sql)) {
- return true;
- };
- }
- return false;
- }
- /**
- * 获取表结构和数据
- * @param string $table 表名
- * @param integer $export_data 是否导出数据
- * @param integer $start 起始行数
- * @author 蔡伟明 <314013107@qq.com>
- * @return string
- */
- private static function getSql($table = '', $export_data = 0, $start = 0)
- {
- $sql = "";
- if (Db::query("SHOW TABLES LIKE '%{$table}%'")) {
- // 表结构
- if ($start == 0) {
- $result = Db::query("SHOW CREATE TABLE `{$table}`");
- $sql .= "\n-- -----------------------------\n";
- $sql .= "-- 表结构 `{$table}`\n";
- $sql .= "-- -----------------------------\n";
- $sql .= "DROP TABLE IF EXISTS `{$table}`;\n";
- $sql .= trim($result[0]['Create Table']) . ";\n\n";
- }
- // 表数据
- if ($export_data) {
- $sql .= "-- -----------------------------\n";
- $sql .= "-- 表数据 `{$table}`\n";
- $sql .= "-- -----------------------------\n";
- // 数据总数
- $result = Db::query("SELECT COUNT(*) AS count FROM `{$table}`");
- $count = $result['0']['count'];
- // 备份数据记录
- $result = Db::query("SELECT * FROM `{$table}` LIMIT {$start}, 1000");
- foreach ($result as $row) {
- $row = array_map('addslashes', $row);
- $sql .= "INSERT INTO `{$table}` VALUES ('" . str_replace(array("\r","\n"),array('\r','\n'),implode("', '", $row)) . "');\n";
- }
- // 还有更多数据
- if($count > $start + 1000){
- $sql .= self::getSql($table, $export_data, $start + 1000);
- }
- }
- }
- return $sql;
- }
- /**
- * 析构方法,用于关闭文件资源
- */
- public function __destruct(){
- $this->config['compress'] ? @gzclose($this->fp) : @fclose($this->fp);
- }
- }
|