tanghc 3 years ago
parent
commit
e56e837543

+ 12 - 20
gen/src/main/java/com/gitee/gen/GenApplication.java

@@ -1,36 +1,28 @@
 package com.gitee.gen;
 
+import com.gitee.gen.service.UpgradeService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.ApplicationArguments;
+import org.springframework.boot.ApplicationRunner;
 import org.springframework.boot.SpringApplication;
 import org.springframework.boot.autoconfigure.SpringBootApplication;
 import org.springframework.boot.web.servlet.ServletComponentScan;
-import org.springframework.core.io.ClassPathResource;
-import org.springframework.util.FileCopyUtils;
-
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
 
 @ServletComponentScan
 @SpringBootApplication
-public class GenApplication {
+public class GenApplication implements ApplicationRunner {
+
+    @Autowired
+    private UpgradeService upgradeService;
 
     public static void main(String[] args) {
-        initDatabase();
+        UpgradeService.initDatabase();
         SpringApplication.run(GenApplication.class, args);
     }
 
-    public static void initDatabase() {
-        String filename = "gen.db";
-        String filepath = System.getProperty("user.dir") + "/" + filename;
-        File dbFile = new File(filepath);
-        if (!dbFile.exists()) {
-            ClassPathResource resource = new ClassPathResource(filename);
-            try {
-                FileCopyUtils.copy(resource.getInputStream(), new FileOutputStream(dbFile));
-            } catch (IOException e) {
-                throw new RuntimeException("初始化数据库失败", e);
-            }
-        }
+    @Override
+    public void run(ApplicationArguments args) throws Exception {
+        upgradeService.upgrade();
     }
 
 }

+ 27 - 0
gen/src/main/java/com/gitee/gen/entity/ColumnInfo.java

@@ -0,0 +1,27 @@
+package com.gitee.gen.entity;
+
+/**
+ * @author tanghc
+ */
+public class ColumnInfo {
+    /** 字段名 */
+    private String name;
+    /** 字段类型 */
+    private String type;
+
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    public String getType() {
+        return type;
+    }
+
+    public void setType(String type) {
+        this.type = type;
+    }
+}

+ 50 - 0
gen/src/main/java/com/gitee/gen/mapper/UpgradeMapper.java

@@ -0,0 +1,50 @@
+package com.gitee.gen.mapper;
+
+import com.gitee.gen.entity.ColumnInfo;
+import org.apache.ibatis.annotations.Mapper;
+import org.apache.ibatis.annotations.Param;
+
+import java.util.List;
+
+/**
+ * @author tanghc
+ */
+@Mapper
+public interface UpgradeMapper {
+
+    void runSql(@Param("sql") String sql);
+
+    /**
+     * 新增表字段
+     * @param tableName 表名
+     * @param columnName 字段名
+     * @param type 类型
+     */
+    void addColumn(@Param("tableName") String tableName, @Param("columnName")String columnName,@Param("type") String type);
+
+    /**
+     * 新增mysql表字段
+     * @param tableName 表名
+     * @param columnName 字段名
+     * @param type 类型
+     */
+    void addColumnMysql(@Param("tableName") String tableName, @Param("columnName")String columnName,@Param("type") String type);
+
+    /**
+     * 查看表字段信息
+     * @param tableName 表名
+     * @return 返回字段信息
+     */
+    List<ColumnInfo> listColumnInfo(@Param("tableName") String tableName);
+
+    /**
+     * 查看MYSQL表字段信息
+     * @param tableName 表名
+     * @return 返回字段信息
+     */
+    List<ColumnInfo> listColumnInfoMysql(@Param("tableName") String tableName);
+
+    List<String> listTableName();
+
+    List<String> listTableNameMysql();
+}

+ 160 - 0
gen/src/main/java/com/gitee/gen/service/UpgradeService.java

@@ -0,0 +1,160 @@
+package com.gitee.gen.service;
+
+import com.gitee.gen.entity.ColumnInfo;
+import com.gitee.gen.mapper.UpgradeMapper;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.core.io.ClassPathResource;
+import org.springframework.stereotype.Service;
+import org.springframework.util.FileCopyUtils;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.util.List;
+import java.util.Objects;
+
+/**
+ * 升级
+ * @author tanghc
+ */
+@Service
+public class UpgradeService {
+
+    public static final String TABLE_DATASOURCE_CONFIG = "datasource_config";
+    public static final String TABLE_TEMPLATE_CONFIG = "template_config";
+    public static final String TABLE_TEMPLATE_GROUP = "template_group";
+
+    @Autowired
+    private UpgradeMapper upgradeMapper;
+
+    @Value("${spring.datasource.driver-class-name}")
+    private String driverClassName;
+
+    public static void initDatabase() {
+        String filename = "gen.db";
+        String filepath = System.getProperty("user.dir") + "/" + filename;
+        File dbFile = new File(filepath);
+        if (!dbFile.exists()) {
+            ClassPathResource resource = new ClassPathResource(filename);
+            try {
+                FileCopyUtils.copy(resource.getInputStream(), new FileOutputStream(dbFile));
+            } catch (IOException e) {
+                throw new RuntimeException("初始化数据库失败", e);
+            }
+        }
+    }
+
+    /**
+     * 升级
+     */
+    public void upgrade() {
+        upgradeV1_4_0();
+    }
+
+    /**
+     * 升级v1.4.0
+     */
+    private void upgradeV1_4_0() {
+        boolean isCreate = this.createTable(TABLE_TEMPLATE_GROUP);
+        if (isCreate) {
+            runSql("INSERT INTO `template_group` (`id`, `group_name`, `is_deleted`) VALUES (1,'default',0)");
+        }
+
+        this.addColumn(TABLE_DATASOURCE_CONFIG, "package_name", "varchar(100)");
+        this.addColumn(TABLE_DATASOURCE_CONFIG, "del_prefix", "varchar(100)");
+        this.addColumn(TABLE_DATASOURCE_CONFIG, "group_id", "int");
+
+        this.addColumn(TABLE_TEMPLATE_CONFIG, "group_id", "int");
+        this.addColumn(TABLE_TEMPLATE_CONFIG, "group_name", "varchar(100)");
+        runSql("update template_config set group_id=1,group_name='default' where group_id = NULL");
+    }
+
+    private void runSql(String sql) {
+        upgradeMapper.runSql(sql);
+    }
+
+    /**
+     * 添加表字段
+     * @param tableName 表名
+     * @param columnName 字段名
+     * @param type 字段类型,如:varchar(128),text,integer
+     * @return 返回true,插入成功
+     */
+    public boolean addColumn(String tableName, String columnName, String type) {
+        if (!isColumnExist(tableName, columnName)) {
+            if (isMysql()) {
+                upgradeMapper.addColumnMysql(tableName, columnName, type);
+            } else {
+                upgradeMapper.addColumn(tableName, columnName, type);
+            }
+            return true;
+        }
+        return false;
+    }
+
+    /**
+     * 创建表
+     * @param tableName 表名
+     * @return 创建成功返回true
+     */
+    public boolean createTable(String tableName) {
+        if (!isTableExist(tableName)) {
+            String sql = this.loadDDL(tableName);
+            upgradeMapper.runSql(sql);
+            return true;
+        }
+        return false;
+    }
+
+    private String loadDDL(String tableName) {
+        String tmp_mysql = "ddl_%s_mysql.txt";
+        String tmp_sqlite = "ddl_%s_sqlite.txt";
+        String tmp = isMysql() ? tmp_mysql : tmp_sqlite;
+        String filename = "upgrade/" + String.format(tmp, tableName);
+        ClassPathResource resource = new ClassPathResource(filename);
+        if (!resource.exists()) {
+            throw new RuntimeException("找不到文件:" + filename);
+        }
+        try {
+            byte[] bytes = FileCopyUtils.copyToByteArray(resource.getInputStream());
+            return new String(bytes);
+        } catch (IOException e) {
+            e.printStackTrace();
+            throw new RuntimeException("打开文件出错", e);
+        }
+    }
+
+    /**
+     * 判断列是否存在
+     * @param tableName 表名
+     * @param columnName 列名
+     * @return true:存在
+     */
+    public boolean isColumnExist(String tableName, String columnName) {
+        List<ColumnInfo> columnInfoList = isMysql() ? upgradeMapper.listColumnInfoMysql(tableName) :
+                upgradeMapper.listColumnInfo(tableName);
+        return columnInfoList
+                .stream()
+                .anyMatch(columnInfo -> Objects.equals(columnInfo.getName(), columnName));
+    }
+
+    /**
+     * 表是否存在
+     * @param tableName
+     * @return
+     */
+    public boolean isTableExist(String tableName) {
+        List<String> tableNameList;
+        if (isMysql()) {
+            tableNameList = upgradeMapper.listTableNameMysql();
+        } else {
+            tableNameList = upgradeMapper.listTableName();
+        }
+        return tableNameList != null && tableNameList.contains(tableName);
+    }
+
+    private boolean isMysql() {
+        return this.driverClassName.contains("mysql");
+    }
+}

+ 37 - 0
gen/src/main/resources/mybatis/UpgradeMapper.xml

@@ -0,0 +1,37 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<!DOCTYPE  mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
+<mapper namespace="com.gitee.gen.mapper.UpgradeMapper">
+
+    <update id="runSql">
+        ${sql}
+    </update>
+
+    <update id="addColumn">
+        ALTER TABLE ${tableName} ADD ${columnName} ${type}
+    </update>
+
+    <update id="addColumnMysql">
+        ALTER TABLE ${tableName} ADD COLUMN ${columnName} ${type}
+    </update>
+
+    <select id="listColumnInfo" resultType="com.gitee.gen.entity.ColumnInfo">
+        PRAGMA table_info('${tableName}')
+    </select>
+
+    <select id="listColumnInfoMysql" resultType="com.gitee.gen.entity.ColumnInfo">
+        select COLUMN_NAME as 'name', DATA_TYPE as 'type'
+        from information_schema.COLUMNS
+        where table_name = '${tableName}'
+    </select>
+
+
+    <select id="listTableName" resultType="String">
+        SELECT name FROM sqlite_master WHERE type='table'
+    </select>
+
+    <select id="listTableNameMysql" resultType="String">
+        select table_name from information_schema.tables
+        where table_schema='gen'
+    </select>
+
+</mapper>

+ 6 - 0
gen/src/main/resources/upgrade/ddl_template_group_mysql.txt

@@ -0,0 +1,6 @@
+CREATE TABLE `template_group` (
+  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
+  `group_name` varchar(100) DEFAULT NULL COMMENT '模板组名称',
+  `is_deleted` int(11) DEFAULT 0 COMMENT '是否删除,1:已删除,0:未删除',
+  PRIMARY KEY (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='模板组表';

+ 5 - 0
gen/src/main/resources/upgrade/ddl_template_group_sqlite.txt

@@ -0,0 +1,5 @@
+CREATE TABLE IF NOT EXISTS template_group (
+  id integer PRIMARY KEY AUTOINCREMENT NOT NULL,
+  group_name varchar(128) NOT NULL,
+  is_deleted integer NOT NULL
+);