数据库版本更新

version1
anthonyywj2 2 years ago
parent 1e49a88194
commit 8de0bb30af

@ -0,0 +1,81 @@
package com.glxp.sale.admin.config;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.lang.UUID;
import com.glxp.sale.admin.dao.param.DbVersionDao;
import com.glxp.sale.admin.entity.param.DbVersionEntity;
import com.glxp.sale.admin.entity.param.SchemaData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Order(1)
@Component
@Slf4j
public class HdSchemaExecutor implements ApplicationRunner {
@Resource
DbVersionDao hdCommonDao;
private List<SchemaData> schema = new ArrayList<>();
@Override
public void run(ApplicationArguments args) throws Exception {
//初始版本列表
buildSchemas();
//定义sql文件路径
String basePath = "schemas/";
//非版本控制,初始化脚本
ClassLoader loader = this.getClass().getClassLoader();
//通过流的方式获取项目路径下的文件
InputStream inputStream = loader.getResourceAsStream(basePath + "init.sql");
//获取文件内容
String sql = IoUtil.readUtf8(inputStream);
try {
//判断版本表是否存在
int count = hdCommonDao.selectTableExist("hd_version");
if (count == 0) {
hdCommonDao.updateSql(sql);
}
for (SchemaData schemaData : schema) {
//查询版本记录是否存在
count = hdCommonDao.selectVersion(schemaData.getVersion());
if (count == 0) {
log.info("--------------执行数据脚本,版本:" + schemaData.getVersion());
//获取对应sql脚本
inputStream = loader.getResourceAsStream(basePath + schemaData.getFileName());
sql = IoUtil.readUtf8(inputStream);
hdCommonDao.updateSql(sql);
DbVersionEntity entity = new DbVersionEntity();
entity.setId(UUID.randomUUID().toString());
entity.setVersion(schemaData.getVersion());
entity.setCreated(new Date());
entity.setRemark(schemaData.getFileName());
//写入版本记录
hdCommonDao.insertVersion(entity);
}
}
} catch (IORuntimeException e) {
e.printStackTrace();
} finally {
//关闭流
inputStream.close();
}
}
public void buildSchemas() {
// schema.add(new SchemaData("v2.1", "schema_v2.1.sql"));
// schema.add(new SchemaData("v2.2", "schema_v2.2.sql"));
// schema.add(new SchemaData("v2.3", "schema_v2.3.sql"));
}
}

@ -0,0 +1,24 @@
package com.glxp.sale.admin.dao.param;
import com.glxp.sale.admin.entity.param.DbVersionEntity;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Update;
@Mapper
public interface DbVersionDao {
int selectVersion(@Param("version") String version);
//查询版本表是否存在
int selectTableExist(@Param("tableName") String tableName);
//新增版本
int insertVersion(DbVersionEntity entity);
//执行sql
@Update("${sql}")
void updateSql(@Param("sql") String sql);
}

@ -0,0 +1,15 @@
package com.glxp.sale.admin.entity.param;
import lombok.Data;
import java.util.Date;
@Data
public class DbVersionEntity {
private String id;
private String version;
private String remark;
private Date created;
}

@ -0,0 +1,22 @@
package com.glxp.sale.admin.entity.param;
import lombok.Data;
@Data
public class SchemaData {
/**
*
*/
public String version;
/**
*
*/
public String fileName;
public SchemaData(String version, String fileName) {
this.version = version;
this.fileName = fileName;
}
}

@ -1,10 +1,10 @@
# \u751F\u4EA7\u73AF\u5883
server.port=9989
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.jdbc-url=jdbc:mysql://127.0.0.1:3306/udispsync?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true
spring.datasource.jdbc-url=jdbc:mysql://127.0.0.1:3306/udispsync?allowMultiQueries=true&serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true
spring.datasource.username=root
#spring.datasource.password=root
spring.datasource.password=mysql80
spring.datasource.password=123456
#server.servlet.context-path=
logging.level.com.glxp.sale.admin.dao=debug
# \u8DE8\u57DF\u8BBE\u7F6E
@ -27,8 +27,6 @@ file_path=D:/share/udisps/
#file_path=/share/order/sync
back_file_path=D:/share/udisps/back/
#back_file_path=/share/order/sync_back
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8
#UDI管理系统地址

@ -0,0 +1,26 @@
<?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.glxp.sale.admin.dao.param.DbVersionDao">
<select id="selectVersion" resultType="int">
selecT count(1)
from db_version
where version = #{version}
</select>
<select id="selectTableExist" resultType="int">
select count(*) count
from information_schema.TABLES
where TABLE_NAME = #{tableName} and table_schema = (select database())
</select>
<insert id="insertVersion">
insert into db_version(id, version, remark, created)
values (uuid(), #{version}, #{remark}, #{created})
</insert>
</mapper>

@ -0,0 +1,109 @@
SET NAMES utf8mb4;
SET
FOREIGN_KEY_CHECKS = 0;
DROP TABLE IF EXISTS `db_version`;
CREATE TABLE `db_version`
(
`id` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
`version` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '版本号',
`created` datetime(0) NULL DEFAULT NULL COMMENT '创建时间',
`remark` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '备注',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '数据版本' ROW_FORMAT = Dynamic;
SET
FOREIGN_KEY_CHECKS = 1;
/* 创建函数Pro_Temp_ColumnWork操作表字段 */
DROP PROCEDURE IF EXISTS Pro_Temp_ColumnWork;
CREATE PROCEDURE `Pro_Temp_ColumnWork`(TableName VARCHAR ( 50 ), ColumnName VARCHAR ( 50 ), SqlStr VARCHAR ( 4000 ),
CType INT)
BEGIN
DECLARE
Rows1 INT;
SET
Rows1 = 0;
SELECT COUNT(*)
INTO Rows1
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_schema = DATABASE()
AND upper(table_name) = TableName
AND upper(column_name) = ColumnName;
IF
( CType = 1 AND Rows1 <= 0 ) THEN
SET SqlStr := CONCAT( 'ALTER TABLE ', TableName, ' ADD COLUMN ', ColumnName, ' ', SqlStr );
ELSEIF
( CType = 2 AND Rows1 > 0 ) THEN
SET SqlStr := CONCAT( 'ALTER TABLE ', TableName, ' MODIFY ', ColumnName, ' ', SqlStr );
ELSEIF
( CType = 3 AND Rows1 > 0 ) THEN
SET SqlStr := CONCAT( 'ALTER TABLE ', TableName, ' DROP COLUMN ', ColumnName );
ELSE
SET SqlStr := '';
END IF;
IF
( SqlStr <> '' ) THEN
SET @SQL1 = SqlStr;
PREPARE stmt1
FROM
@SQL1;
EXECUTE stmt1;
END IF;
END;
/** 函数创建结束 **/
/*创建定义普通索引函数*/
DROP PROCEDURE IF EXISTS Modify_index;
CREATE PROCEDURE Modify_index(
TableName VARCHAR ( 50 ),
ColumnNames VARCHAR ( 500 ),
idx_name VARCHAR ( 50 ),
idx_type VARCHAR ( 50 ))
BEGIN
DECLARE
Rows1 int;
DECLARE
SqlStr VARCHAR(4000);
DECLARE
target_database VARCHAR ( 100 );
SELECT DATABASE
()
INTO target_database;
SET
Rows1 = 0;
SELECT COUNT(*)
INTO Rows1
FROM information_schema.statistics
WHERE table_schema = DATABASE()
AND upper(table_name) = upper(TableName)
AND upper(index_name) = upper(idx_name);
IF
Rows1<=0 THEN
SET SqlStr := CONCAT( 'alter table ', TableName, ' ADD INDEX ', idx_name, '(', ColumnNames, ') USING ', idx_type );
END IF;
IF
( SqlStr <> '' ) THEN
SET @SQL1 = SqlStr;
PREPARE stmt1
FROM
@SQL1;
EXECUTE stmt1;
END IF;
END;
/*创建定义普通索引函数结束*/
Loading…
Cancel
Save