cmvr-wms/ruoyi-project/scripts/IterationMigration.java

167 lines
13 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.sql.*;
import java.util.*;
import java.util.regex.*;
/** 009 开发库迁移执行器:DDL 分步可续跑,全部结构与历史引用通过核验后才写成功标记。 */
public final class IterationMigration {
private static final String DATABASE="cmvr-project-dev";
private static final String NAME="009_project_iterations";
private static final Path SCRIPT=Path.of("ruoyi-project/src/main/resources/db/009_project_iterations.sql");
private static final List<String> CORE=List.of("work_item","project_stage","stage_edge","dependency_condition","stage_revision","stage_rework","flow_definition_revision");
private static final List<String> HISTORY=List.of("history","outbox","notification");
private static final Pattern CONSTRAINT=Pattern.compile("(?is)^ALTER TABLE\\s+(\\w+)\\s+ADD CONSTRAINT\\s+(\\w+)\\s+FOREIGN KEY\\(([^)]+)\\) REFERENCES\\s+(\\w+)\\(([^)]+)\\)$");
/** 执行器仅提供固定迁移或 --verify 只读核验,不接受外部 SQL、目标库或任意路径。 */
private IterationMigration() { }
/**
* 对固定开发库执行增量迁移,已完成时仅验证;可用 --verify 进行完全只读检查。
* @param args 空参数执行迁移,或单一 --verify 参数
* @throws Exception 配置不符、结构不完整或任何引用异常时终止,不写迁移成功标记
*/
public static void main(String[] args) throws Exception {
boolean verifyOnly=args.length==1&&"--verify".equals(args[0]);
if(args.length!=0&&!verifyOnly) throw new IllegalArgumentException("仅支持固定迁移或 --verify");
Map<String,String> config=config(); String url=config.get("url");
if(url==null||!url.matches("^jdbc:mysql://192\\.168\\.28\\.10:3306/"+DATABASE+"(?:\\?.*)?$")) throw new IllegalStateException("只允许仓库指定开发库");
Properties properties=new Properties(); properties.setProperty("user",config.get("username")); properties.setProperty("password",config.get("password"));
properties.setProperty("connectTimeout","5000"); properties.setProperty("socketTimeout","30000");
String script=Files.readString(SCRIPT,StandardCharsets.UTF_8).replace("\uFEFF","");
if(!script.startsWith("-- target-database: "+DATABASE)) throw new IllegalStateException("迁移文件缺少数据库白名单标记");
List<String> statements=statements(script);
try(Connection connection=DriverManager.getConnection(url,properties)) {
if(!DATABASE.equals(connection.getCatalog())) throw new IllegalStateException("当前数据库不符");
if(!applied(connection,"008_stage_revisions")) throw new IllegalStateException("必须先完成 008 迁移");
if(verifyOnly||applied(connection,NAME)) {
verify(connection,statements);
if(!applied(connection,NAME)) throw new IllegalStateException("结构已核验,但 009 尚未标记完成");
System.out.println("009 已应用;迭代结构和引用核验通过"); return;
}
// 命名锁只协调迁移进程。业务写入仍由应用项目锁保护,部署时应先完成迁移再启用新版接口。
scalarEquals(connection,"SELECT GET_LOCK('pm_collab_iteration_migration',10)",1,"其他进程正在执行迭代迁移");
try {
// 等待命名锁期间另一进程可能已经完成;再次检查,避免完整迁移被当作中断恢复重跑。
if(applied(connection,NAME)) { verify(connection,statements); System.out.println("009 已由其他进程完成;核验通过"); return; }
Map<String,String> before=identitySnapshot(connection);
String marker=null;
for(String statement:statements) {
if(statement.startsWith("INSERT INTO pm_collab_schema_migration")) { marker=statement; continue; }
if(skipExistingDdl(connection,statement)) continue;
try(Statement command=connection.createStatement()) { command.execute(statement); }
}
verify(connection,statements);
if(!before.equals(identitySnapshot(connection))) throw new IllegalStateException("原业务行数量或 ID 校验改变,拒绝标记完成");
if(marker==null) throw new IllegalStateException("缺少迁移成功标记语句");
try(Statement command=connection.createStatement()) { command.execute(marker); }
System.out.println("009 迭代迁移已应用;原业务行 ID、全部历史引用及复合外键核验通过");
} finally {
try(Statement command=connection.createStatement()) { command.execute("SELECT RELEASE_LOCK('pm_collab_iteration_migration')"); }
}
}
}
/** 凭据只读取现有主数据源和环境变量,不输出 URL 以外的连接信息。 */
private static Map<String,String> config() throws Exception {
Map<String,String> values=new HashMap<>(); boolean master=false;
for(String line:Files.readAllLines(Path.of("ruoyi-admin/src/main/resources/application-druid.yml"),StandardCharsets.UTF_8)) {
if(line.trim().equals("master:")) { master=true; continue; }
if(line.trim().equals("slave:")) break;
if(master) { int colon=line.indexOf(':'); if(colon>0) values.put(line.substring(0,colon).trim(),value(line.substring(colon+1).trim())); }
}
return values;
}
/** 兼容配置中的环境变量默认值及引号,始终不回显实际密码。 */
private static String value(String raw) {
if(raw.startsWith("${")&&raw.endsWith("}")) {
String inside=raw.substring(2,raw.length()-1); int split=inside.indexOf(':');
String environment=System.getenv(split<0?inside:inside.substring(0,split));
raw=environment!=null?environment:split<0?"":inside.substring(split+1);
}
if(raw.length()>1&&(raw.startsWith("'")&&raw.endsWith("'")||raw.startsWith("\"")&&raw.endsWith("\""))) return raw.substring(1,raw.length()-1);
return raw;
}
/** 标记只代表完整成功,部分 DDL 自动提交后仍允许恢复执行。 */
private static boolean applied(Connection connection,String name) throws Exception {
try(PreparedStatement statement=connection.prepareStatement("SELECT COUNT(*) FROM pm_collab_schema_migration WHERE name=?")) {
statement.setString(1,name); try(ResultSet result=statement.executeQuery()) { result.next(); return result.getInt(1)>0; }
}
}
/** 对已存在列、索引和约束跳过重复 DDL;缺失的 DROP INDEX 也可安全续跑。 */
private static boolean skipExistingDdl(Connection connection,String sql) throws Exception {
Matcher column=Pattern.compile("(?is)^ALTER TABLE\\s+(\\w+)\\s+ADD COLUMN\\s+(\\w+)\\s+.*").matcher(sql);
if(column.matches()) try(ResultSet result=connection.getMetaData().getColumns(DATABASE,null,column.group(1),column.group(2))) { return result.next(); }
Matcher constraint=CONSTRAINT.matcher(sql);
if(constraint.matches()) return exists(connection,"TABLE_CONSTRAINTS","CONSTRAINT_NAME",constraint.group(1),constraint.group(2));
Matcher index=Pattern.compile("(?is)^ALTER TABLE\\s+(\\w+)\\s+ADD (?:UNIQUE )?INDEX\\s+(\\w+)\\(.*").matcher(sql);
if(index.matches()) return exists(connection,"STATISTICS","INDEX_NAME",index.group(1),index.group(2));
Matcher drop=Pattern.compile("(?is)^ALTER TABLE\\s+(\\w+)\\s+DROP INDEX\\s+(\\w+)$").matcher(sql);
if(drop.matches()) return !exists(connection,"STATISTICS","INDEX_NAME",drop.group(1),drop.group(2));
return false;
}
/** 只向固定 information_schema 表及列发出元数据查询,实际业务标识使用参数绑定。 */
private static boolean exists(Connection connection,String table,String column,String businessTable,String name) throws Exception {
if(!Set.of("TABLE_CONSTRAINTS","STATISTICS").contains(table)||!Set.of("CONSTRAINT_NAME","INDEX_NAME").contains(column)) throw new IllegalArgumentException("非法元数据范围");
try(PreparedStatement statement=connection.prepareStatement("SELECT COUNT(*) FROM information_schema."+table+" WHERE TABLE_SCHEMA=? AND TABLE_NAME=? AND "+column+"=?")) {
statement.setString(1,DATABASE); statement.setString(2,businessTable); statement.setString(3,name);
try(ResultSet result=statement.executeQuery()) { result.next(); return result.getInt(1)>0; }
}
}
/** SQL 文件约定不含字符串内分号或存储过程,去掉整行注释后按语句处理。 */
private static List<String> statements(String sql) {
List<String> result=new ArrayList<>();
for(String statement:sql.replaceAll("(?m)^--.*$","").split(";")) if(!statement.isBlank()) result.add(statement.strip());
return result;
}
/** 原对象 ID 校验覆盖当前、历史及软删除行,迁移只能添加范围而不能增删业务对象。 */
private static Map<String,String> identitySnapshot(Connection connection) throws Exception {
Map<String,String> result=new LinkedHashMap<>(); List<String> tables=new ArrayList<>(CORE); tables.addAll(HISTORY);
for(String table:tables) try(Statement statement=connection.createStatement(); ResultSet row=statement.executeQuery("SELECT COUNT(*),COALESCE(SUM(id),0),COALESCE(BIT_XOR(CRC32(CAST(id AS CHAR))),0) FROM pm_collab_"+table)) {
row.next(); result.put(table,row.getString(1)+":"+row.getString(2)+":"+row.getString(3));
}
return result;
}
/**
* 核验非空回填、历史范围、所有新复合外键的实际列顺序,防止同名但错误的约束被误判完成。
* 纯项目级事件允许 iteration_id=NULL,工作项事件和阶段事件必须取得原迭代范围。
*/
private static void verify(Connection connection,List<String> statements) throws Exception {
for(String table:List.of("pm_collab_iteration","pm_collab_iteration_request")) try(ResultSet result=connection.getMetaData().getTables(DATABASE,null,table,null)) { if(!result.next()) throw new IllegalStateException("缺少 "+table); }
List<String> tables=new ArrayList<>(CORE); tables.addAll(HISTORY);
for(String table:tables) {
try(ResultSet result=connection.getMetaData().getColumns(DATABASE,null,"pm_collab_"+table,"iteration_id")) {
if(!result.next()||CORE.contains(table)&&result.getInt("NULLABLE")!=DatabaseMetaData.columnNoNulls) throw new IllegalStateException(table+" 的迭代列不完整");
}
scalarEquals(connection,"SELECT COUNT(*) FROM pm_collab_"+table+" d LEFT JOIN pm_collab_iteration i ON i.id=d.iteration_id AND i.project_id=d.project_id WHERE "+(CORE.contains(table)?"i.id IS NULL":"d.iteration_id IS NOT NULL AND i.id IS NULL"),0,table+" 存在未回填或跨项目迭代引用");
}
for(String table:HISTORY) scalarEquals(connection,"SELECT COUNT(*) FROM pm_collab_"+table+" d LEFT JOIN pm_collab_work_item w ON w.id=d.work_item_id AND w.project_id=d.project_id AND w.iteration_id=d.iteration_id WHERE d.work_item_id IS NOT NULL AND w.id IS NULL",0,table+" 存在历史工作项范围缺失");
for(String sql:statements) {
Matcher expected=CONSTRAINT.matcher(sql); if(!expected.matches()) continue;
List<String> actual=new ArrayList<>();
try(PreparedStatement query=connection.prepareStatement("SELECT COLUMN_NAME,REFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME FROM information_schema.KEY_COLUMN_USAGE WHERE CONSTRAINT_SCHEMA=? AND TABLE_NAME=? AND CONSTRAINT_NAME=? ORDER BY ORDINAL_POSITION")) {
query.setString(1,DATABASE); query.setString(2,expected.group(1)); query.setString(3,expected.group(2));
try(ResultSet rows=query.executeQuery()) { while(rows.next()) actual.add(rows.getString(1)+":"+rows.getString(2)+":"+rows.getString(3)); }
}
String[] columns=expected.group(3).split(","),references=expected.group(5).split(","); List<String> desired=new ArrayList<>();
for(int index=0;index<columns.length;index++) desired.add(columns[index].trim()+":"+expected.group(4)+":"+references[index].trim());
if(!actual.equals(desired)) throw new IllegalStateException("复合外键不符:"+expected.group(2));
}
scalarEquals(connection,"SELECT COUNT(*) FROM pm_collab_history WHERE iteration_id IS NULL AND LEFT(action,6)='STAGE_'",0,"阶段历史范围回填不完整");
scalarEquals(connection,"SELECT COUNT(*) FROM pm_collab_outbox WHERE iteration_id IS NULL AND LEFT(event_type,6)='STAGE_'",0,"阶段事件范围回填不完整");
}
/** 断言聚合结果而不输出业务内容,错误仅报告结构或范围问题。 */
private static void scalarEquals(Connection connection,String sql,long expected,String message) throws Exception {
try(Statement statement=connection.createStatement();ResultSet result=statement.executeQuery(sql)) { result.next(); if(result.getLong(1)!=expected) throw new IllegalStateException(message); }
}
}