瀏覽代碼

新增数据还原

wangliang 2 年之前
父節點
當前提交
ee893236ca

+ 158 - 0
distributed-print-business/src/main/java/com/qmth/distributed/print/business/backup/MySQLDatabaseBackup.java

@@ -0,0 +1,158 @@
+package com.qmth.distributed.print.business.backup;
+
+import cn.hutool.core.date.DateUtil;
+import com.aventrix.jnanoid.jnanoid.NanoIdUtils;
+import com.qmth.teachcloud.common.config.DictionaryConfig;
+import com.qmth.teachcloud.common.contant.SystemConstant;
+import com.qmth.teachcloud.common.enums.ExceptionResultEnum;
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.io.IOUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+
+import javax.annotation.Resource;
+import java.io.*;
+import java.nio.charset.StandardCharsets;
+import java.util.Date;
+import java.util.Objects;
+import java.util.Optional;
+
+/**
+ * @Description: MySQL数据库备份
+ * @Param:
+ * @return:
+ * @Author: wangliang
+ * @Date: 2022/11/14
+ */
+@Component
+public class MySQLDatabaseBackup {
+    private final static Logger log = LoggerFactory.getLogger(MySQLDatabaseBackup.class);
+
+    @Resource
+    DictionaryConfig dictionaryConfig;
+
+    /**
+     * Java代码实现MySQL数据库导出
+     *
+     * @param hostIP
+     * @param userName
+     * @param password
+     * @param fileName
+     * @param databaseName
+     * @return
+     * @throws Exception
+     */
+    public boolean exportDatabaseTool(String hostIP, String userName, String password, String fileName, String databaseName) throws Exception {
+//        File saveFile = new File(savePath);
+//        if (!saveFile.exists()) {// 如果目录不存在
+//            saveFile.mkdirs();// 创建文件夹
+//        }
+//        if (!savePath.endsWith(File.separator)) {
+//            savePath = savePath + File.separator;
+//        }
+//        File file = new File(dictionaryConfig.fssLocalFileDomain().getConfig() + File.separator + fileName);
+        File file = new File("/Users/king/Downloads/file-temp/db/backup" + File.separator + fileName);
+        if (!file.exists()) {
+            file.getParentFile().mkdirs();
+            file.createNewFile();
+        }
+
+        PrintWriter printWriter = null;
+        BufferedReader bufferedReader = null;
+        try {
+            printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8));
+            String execSql = "mysqldump -h" + hostIP + " -u" + userName + " -p" + password + " --set-charset=" + StandardCharsets.UTF_8 + " " + databaseName;
+            Process process = Runtime.getRuntime().exec(execSql);
+            InputStreamReader inputStreamReader = new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8);
+            bufferedReader = new BufferedReader(inputStreamReader);
+            IOUtils.copy(bufferedReader, printWriter);
+            if (process.waitFor() == 0) {//0 表示线程正常终止。
+                return true;
+            }
+        } catch (Exception e) {
+            log.error(SystemConstant.LOG_ERROR, e);
+        } finally {
+            if (Objects.nonNull(bufferedReader)) {
+                bufferedReader.close();
+            }
+            if (Objects.nonNull(printWriter)) {
+                printWriter.close();
+            }
+        }
+        return false;
+    }
+
+    /**
+     * 删除数据库数据
+     *
+     * @param hostIP
+     * @param userName
+     * @param password
+     * @param databaseName
+     * @param fileName
+     * @param schoolId
+     * @throws Exception
+     */
+    public void deleteDbTool(String hostIP, String userName, String password, String databaseName, String fileName, Long schoolId) throws Exception {
+//        InputStream inputStream = MySQLDatabaseBackup.class.getClassLoader().getResourceAsStream(fileName);
+//        Optional.ofNullable(inputStream).orElseThrow(() -> ExceptionResultEnum.ERROR.exception(fileName + "未找到"));
+//        File file = new File(dictionaryConfig.fssLocalFileDomain().getConfig() + File.separator + fileName);
+//        if (!file.exists()) {
+//            file.getParentFile().mkdirs();
+//            file.createNewFile();
+//        }
+//        FileUtils.copyInputStreamToFile(inputStream, file);
+
+        Optional.ofNullable(schoolId).orElseThrow(() -> ExceptionResultEnum.ERROR.exception("学校id不能为空"));
+        File file = new File("/Users/king/Downloads/file-temp/db/delete" + File.separator + DateUtil.format(new Date(), SystemConstant.BACK_UP_DATE_PATTERN) + "_" + NanoIdUtils.randomNanoId() + "_" + schoolId + "_delete.sql");
+        if (!file.exists()) {
+            file.getParentFile().mkdirs();
+            file.createNewFile();
+        }
+        FileUtils.copyInputStreamToFile(new FileInputStream(new File(fileName)), file);
+
+        ByteArrayOutputStream ou = new ByteArrayOutputStream();
+        IOUtils.copy(new FileInputStream(file), ou);
+        String string = new String(ou.toByteArray(), StandardCharsets.UTF_8);
+        if (Objects.nonNull(string)) {
+            string = string.replaceAll("\\#\\{schoolId\\}", String.valueOf(schoolId));
+        }
+        IOUtils.write(string.getBytes(StandardCharsets.UTF_8), new FileOutputStream(file));
+        String cmdarray[] = {"mysql -h" + hostIP + " -u" + userName + " -p" + password + " " + databaseName, "source " + file.getPath()};
+        Runtime runtime = Runtime.getRuntime();
+        OutputStream os = null;
+        OutputStreamWriter writer = null;
+        try {
+            Process process = runtime.exec(cmdarray[0]);//cmd之后执行数组的第一个条件进入数据库
+            //执行了第一条命令以后已经登录到mysql了
+            os = process.getOutputStream();
+            writer = new OutputStreamWriter(os);
+            IOUtils.write(cmdarray[1], writer);
+        } finally {
+            if (Objects.nonNull(writer)) {
+                writer.close();
+            }
+            if (Objects.nonNull(os)) {
+                os.close();
+            }
+        }
+    }
+
+//    public static void main(String[] args) {
+//        try {
+//            String host = "127.0.0.1", userName = "root", password = "123456789", databaseName = "distributed-v3.2.0";
+//            Long schoolId = 290869043907264512L;
+//            if (exportDatabaseTool(host, userName, password, DateUtil.format(new Date(), SystemConstant.BACK_UP_DATE_PATTERN) + "_" + NanoIdUtils.randomNanoId() + "_backup.sql", databaseName)) {
+//                System.out.println("数据库成功备份!!!");
+////                deleteDbTool(host, userName, password, databaseName, SystemConstant.PRINT_DELETE_DATA_FILE_NAME, schoolId);
+//                deleteDbTool(host, userName, password, databaseName, "/Users/king/git/distributed-print-service/distributed-print-business/src/main/resources/db/4、delete-data.sql", schoolId);
+//                System.out.println("删除数据成功!!!");
+//            } else {
+//                System.out.println("数据库备份失败!!!");
+//            }
+//        } catch (Exception e) {
+//            e.printStackTrace();
+//        }
+//    }
+}

+ 79 - 0
distributed-print-business/src/main/resources/db/4、delete-data.sql

@@ -0,0 +1,79 @@
+SET NAMES utf8mb4;
+
+DELETE t FROM basic_attachment t where t.school_id = #{schoolId};
+DELETE t FROM basic_campus t where t.school_id = #{schoolId};
+DELETE t FROM basic_card_rule t where t.school_id = #{schoolId};
+DELETE t FROM basic_clazz t where t.school_id = #{schoolId};
+DELETE t FROM basic_college t where t.school_id = #{schoolId};
+DELETE t FROM basic_course t where t.school_id = #{schoolId};
+DELETE t FROM t_c_statistics_temp t where exists(select temp.* from(select be.id from basic_exam be where be.school_id = #{schoolId}) temp where t.exam_id = temp.id);
+DELETE t FROM t_c_statistics t where exists(select temp.* from(select be.id from basic_exam be where be.school_id = #{schoolId}) temp where t.exam_id = temp.id);
+DELETE t FROM basic_exam t where t.school_id = #{schoolId};
+DELETE t FROM basic_exam_rule t where t.school_id = #{schoolId};
+DELETE t FROM basic_major t where t.school_id = #{schoolId};
+DELETE t FROM basic_message t where t.school_id = #{schoolId};
+DELETE t FROM basic_print_config t where t.school_id = #{schoolId};
+DELETE t FROM basic_semester t where t.school_id = #{schoolId};
+DELETE t FROM basic_student t where t.school_id = #{schoolId};
+DELETE t FROM basic_template t where t.school_id = #{schoolId};
+DELETE t FROM basic_template_org t where t.school_id = #{schoolId};
+DELETE t FROM basic_user_course t where t.school_id = #{schoolId};
+DELETE t FROM basic_verify_code t where t.school_id = #{schoolId};
+
+DELETE t FROM client_print_data t where t.school_id = #{schoolId};
+DELETE t FROM client_status t where t.school_id = #{schoolId};
+
+DELETE t FROM cloud_user_push_status t where t.school_id = #{schoolId};
+
+DELETE t FROM exam_card_detail t where exists(select temp.* from(select ecd.id from exam_card_detail ecd join exam_card ec on ec.id = ecd.card_id where ec.school_id = #{schoolId}) temp where t.id = temp.id);
+DELETE t FROM exam_card t where t.school_id = #{schoolId};
+DELETE t FROM exam_detail t where t.school_id = #{schoolId};
+DELETE t FROM exam_detail_course t where t.school_id = #{schoolId};
+DELETE t FROM exam_paper_group_marker t where exists(select temp.* from (select epgm.id from exam_paper_group_marker epgm join exam_paper_group epg on epg.id = epgm.group_id join exam_paper_structure eps on eps.id = epg.exam_paper_structure_id where eps.school_id = #{schoolId}) temp where temp.id = t.id);
+DELETE t FROM exam_paper_group t where exists(select temp.* from (select epg.id from exam_paper_group epg join exam_paper_structure eps on eps.id = epg.exam_paper_structure_id where eps.school_id = #{schoolId}) temp where temp.id = t.id);
+DELETE t FROM exam_paper_structure t where t.school_id = #{schoolId};
+DELETE t FROM exam_print_plan t where t.school_id = #{schoolId};
+DELETE t FROM exam_student t where t.school_id = #{schoolId};
+DELETE t FROM exam_task t where t.school_id = #{schoolId};
+DELETE t FROM exam_task_apply_temp t where t.school_id = #{schoolId};
+DELETE t FROM exam_task_detail t where exists(select temp.* from(select et.id from exam_task et where et.school_id = #{schoolId}) temp where t.exam_task_id = temp.id);
+DELETE t FROM exam_task_paper_log t where exists(select temp.* from(select et.id from exam_task et where et.school_id = #{schoolId}) temp where t.exam_task_id = temp.id);
+DELETE t FROM exam_task_print t where t.school_id = #{schoolId};
+DELETE t FROM exam_task_review_log t where exists(select temp.* from(select et.id from exam_task et where et.school_id = #{schoolId}) temp where t.exam_task_id = temp.id);
+DELETE t FROM exam_task_temp t where t.school_id = #{schoolId};
+
+DELETE t FROM grade_batch_student t where exists(select temp.* from(select gb.id from grade_batch gb where gb.school_id = #{schoolId}) temp where t.batch_id = temp.id);
+DELETE t FROM grade_batch_student_clazz t where exists(select temp.* from(select gb.id from grade_batch gb where gb.school_id = #{schoolId}) temp where t.batch_id = temp.id);
+DELETE t FROM grade_batch t where t.school_id = #{schoolId};
+DELETE t FROM grade_batch_paper t where t.school_id = #{schoolId};
+DELETE t FROM grade_module_define t where t.school_id = #{schoolId};
+DELETE t FROM grade_module_evaluation t where t.school_id = #{schoolId};
+DELETE t FROM grade_paper t where t.school_id = #{schoolId};
+DELETE t FROM grade_paper_dimension t where t.school_id = #{schoolId};
+DELETE t FROM grade_paper_struct t where t.school_id = #{schoolId};
+
+DELETE t FROM sys_config t where t.school_id = #{schoolId};
+DELETE t FROM sys_org t where t.school_id = #{schoolId};
+DELETE t FROM sys_role_group_member t where exists(select temp.* from(select sr.id from sys_role sr where sr.school_id = #{schoolId}) temp where t.role_id = temp.id);
+DELETE t FROM sys_role_privilege t where exists(select temp.* from(select sr.id from sys_role sr where sr.school_id = #{schoolId}) temp where t.role_id = temp.id);
+DELETE t FROM sys_user_role t where exists(select temp.* from(select sr.id from sys_role sr where sr.school_id = #{schoolId}) temp where t.role_id = temp.id);
+DELETE t FROM sys_role t where t.school_id = #{schoolId};
+DELETE t FROM sys_user t where t.school_id = #{schoolId};
+
+DELETE t FROM t_b_session t where t.school_id = #{schoolId};
+DELETE t FROM t_b_sync_task t where t.school_id = #{schoolId};
+DELETE t FROM t_b_task t where t.school_id = #{schoolId};
+DELETE t FROM t_f_flow_join t where exists(select temp.* from (select tffe.id from t_f_custom_flow_entity tffe join t_f_custom_flow tfcf on tfcf.id = tffe.t_f_custom_flow_id where tfcf.school_id = #{schoolId}) temp where t.flow_entity_id = temp.id);
+DELETE t FROM t_f_custom_flow_entity t where exists(select temp.* from(select tfcf.id from t_f_custom_flow tfcf where tfcf.school_id = #{schoolId}) temp where t.t_f_custom_flow_id = temp.id);
+DELETE t FROM t_f_custom_flow t where t.school_id = #{schoolId};
+DELETE t FROM t_f_flow_approve t where t.school_id = #{schoolId};
+DELETE t FROM t_f_flow_log t where t.school_id = #{schoolId};
+DELETE t FROM t_g_error t where t.school_id = #{schoolId};
+DELETE t FROM t_m_mq_message t where t.school_id = #{schoolId};
+DELETE t FROM t_s_auth t where t.school_id = #{schoolId};
+DELETE t FROM t_school_privilege t where t.school_id = #{schoolId};
+DELETE t FROM t_sync_exam_student_score t where t.school_id = #{schoolId};
+
+DELETE t FROM teach_clazz t where t.school_id = #{schoolId};
+DELETE t FROM teach_course t where t.school_id = #{schoolId};
+DELETE t FROM teach_student t where t.school_id = #{schoolId};

+ 6 - 0
pom.xml

@@ -52,6 +52,7 @@
         <activiti.version>6.0.0</activiti.version>
         <activiti-modeler.version>5.22.0</activiti-modeler.version>
         <zip4j.version>1.3.3</zip4j.version>
+        <nanoid.version>2.0.0</nanoid.version>
     </properties>
 
     <dependencyManagement>
@@ -339,6 +340,11 @@
                 <artifactId>zip4j</artifactId>
                 <version>${zip4j.version}</version>
             </dependency>
+            <dependency>
+                <groupId>com.aventrix.jnanoid</groupId>
+                <artifactId>jnanoid</artifactId>
+                <version>${nanoid.version}</version>
+            </dependency>
         </dependencies>
     </dependencyManagement>
 

+ 4 - 0
teachcloud-common/pom.xml

@@ -157,5 +157,9 @@
             <groupId>net.lingala.zip4j</groupId>
             <artifactId>zip4j</artifactId>
         </dependency>
+        <dependency>
+            <groupId>com.aventrix.jnanoid</groupId>
+            <artifactId>jnanoid</artifactId>
+        </dependency>
     </dependencies>
 </project>

+ 2 - 0
teachcloud-common/src/main/java/com/qmth/teachcloud/common/contant/SystemConstant.java

@@ -35,6 +35,7 @@ public class SystemConstant {
     /**
      * 系统常量
      */
+    public static final String PRINT_DELETE_DATA_FILE_NAME = "db/4、delete-data.sql";
     public static final String SYS_CONFIG_KEY_CHARSETS = "sys.txt.charset";
     public static final String SYS_PDF_SIZE_LIST = "sys.pdf.size.list";
     public static final String PDF_SIZE_LIST = "pdf.size.list";
@@ -88,6 +89,7 @@ public class SystemConstant {
     public static final String DEFAULT_DATE_PATTERN = "yyyy-MM-dd HH:mm:ss";
     public static final String DATE_PATTERN = "yyyy-MM-dd";
     public static final String TIME_PATTERN = "HH:mm";
+    public static final String BACK_UP_DATE_PATTERN = "yyyyMMddHHmmss";
     public static final int PAGE_NUMBER = 0;
     public static final int PAGE_SIZE = 10000000;
     public static final int PAGE_SIZE_MIN = 10;