- 为对话框添加防止意外关闭的安全措施 - 实现表单提交时的数据有效性验证 - 集成远程选择器组件提升用户体验 - 更新表格组件样式适配新设计规范 - 优化列表页面加载和错误处理机制 - 统一组件尺寸设置和存储管理
178 lines
14 KiB
Java
178 lines
14 KiB
Java
import java.nio.charset.StandardCharsets;
|
|
import java.nio.file.*;
|
|
import java.sql.*;
|
|
import java.util.*;
|
|
import java.util.regex.*;
|
|
|
|
/** Local schema inspection and additive migration tool, restricted to the authorized database. */
|
|
public class DatabaseTool {
|
|
static final String DATABASE = "cmvr-project-dev";
|
|
public static void main(String[] args) throws Exception {
|
|
if (args.length == 0 || !(args[0].equals("inspect") || args[0].equals("apply") || args[0].equals("cutover") || args[0].equals("restore-collaboration-entry"))) {
|
|
throw new IllegalArgumentException("Usage: inspect | apply <reviewed-sql-file> | cutover | restore-collaboration-entry; collaboration menu removal is no longer authorized");
|
|
}
|
|
Map<String,String> config = 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) config.put(line.substring(0,colon).trim(), value(line.substring(colon+1).trim()));
|
|
}
|
|
}
|
|
String url = config.get("url");
|
|
if (url == null || !url.matches("^jdbc:mysql://192\\.168\\.28\\.10:3306/" + DATABASE + "(?:\\?.*)?$")) {
|
|
throw new IllegalStateException("Refusing database access outside " + DATABASE);
|
|
}
|
|
Properties props = new Properties();
|
|
props.setProperty("user", config.get("username"));
|
|
props.setProperty("password", config.get("password"));
|
|
props.setProperty("connectTimeout", "5000");
|
|
props.setProperty("socketTimeout", "30000");
|
|
try (Connection connection = DriverManager.getConnection(url, props)) {
|
|
try (Statement st = connection.createStatement(); ResultSet rs = st.executeQuery("select database()")) {
|
|
rs.next(); if (!DATABASE.equals(rs.getString(1))) throw new IllegalStateException("Database mismatch");
|
|
}
|
|
if (args[0].equals("inspect")) inspect(connection);
|
|
else if (args[0].equals("cutover")) cutover(connection);
|
|
else if (args[0].equals("restore-collaboration-entry")) restoreCollaborationEntry(connection);
|
|
else apply(connection, Path.of(args[1]));
|
|
}
|
|
}
|
|
/** Restore only the independently owned entry, without granting new role or write permissions. */
|
|
static void restoreCollaborationEntry(Connection connection) throws Exception {
|
|
connection.setAutoCommit(false);
|
|
try (Statement st = connection.createStatement()) {
|
|
try (ResultSet rows = st.executeQuery("select path,menu_type from sys_menu where menu_id=2100 for update")) {
|
|
if (!rows.next() || !"project".equals(rows.getString("path")) || !"M".equals(rows.getString("menu_type"))) {
|
|
throw new IllegalStateException("Project parent identity changed; nothing restored");
|
|
}
|
|
}
|
|
boolean exists = false;
|
|
try (ResultSet rows = st.executeQuery("select menu_id,parent_id,path,component,perms from sys_menu where menu_id=2600 or (parent_id=2100 and path='collaboration') or component='project/manage/index' for update")) {
|
|
while (rows.next()) {
|
|
if (exists || rows.getLong("menu_id") != 2600 || rows.getLong("parent_id") != 2100
|
|
|| !"collaboration".equals(rows.getString("path")) || !"project/manage/index".equals(rows.getString("component"))
|
|
|| !"project:manage:read".equals(rows.getString("perms"))) {
|
|
throw new IllegalStateException("Collaboration entry conflicts with an existing menu; nothing overwritten");
|
|
}
|
|
exists = true;
|
|
}
|
|
}
|
|
int menus = exists ? 0 : st.executeUpdate("insert into sys_menu(menu_id,menu_name,parent_id,order_num,path,component,route_name,is_frame,is_cache,menu_type,visible,status,perms,icon,create_by,create_time,remark) values(2600,'项目协作',2100,2,'collaboration','project/manage/index','',1,0,'C','0','0','project:manage:read','tree','admin',current_timestamp,'保留独立维护的项目协作入口')");
|
|
connection.commit();
|
|
System.out.println("RESTORED collaboration entry=" + menus + " in " + DATABASE + "; role grants, other menus and project business data unchanged");
|
|
} catch (Exception failure) { connection.rollback(); throw failure; }
|
|
}
|
|
/** Preserve only the current physical balance. Historical documents stay untouched. */
|
|
static void cutover(Connection connection) throws Exception {
|
|
connection.setAutoCommit(false);
|
|
try (Statement st = connection.createStatement()) {
|
|
try (ResultSet rs = st.executeQuery("select id from inventory_cost_lock where id=1 for update")) {
|
|
if (!rs.next()) throw new IllegalStateException("Missing inventory mutex");
|
|
}
|
|
try (ResultSet rs = st.executeQuery("select id from inventory_cutover where id=1")) {
|
|
if (rs.next()) { connection.rollback(); System.out.println("CUTOVER ALREADY APPLIED"); return; }
|
|
}
|
|
// Lock the snapshot source too; do not compete with the old application's mutations.
|
|
try (ResultSet rs = st.executeQuery("select id from stock_info order by id for update")) { while (rs.next()) {} }
|
|
try (ResultSet rs = st.executeQuery("select id from stock_lot order by id for update")) { while (rs.next()) {} }
|
|
String reconciliation = "select count(*) from (select s.area_id,s.product_id,s.stock_num,coalesce(sum(case when l.lot_status in (0,1) then l.available_quantity else 0 end),0) lot_num from stock_info s left join stock_lot l on l.area_id=s.area_id and l.product_id=s.product_id group by s.id,s.area_id,s.product_id,s.stock_num having stock_num<>lot_num union all select l.area_id,l.product_id,0,sum(l.available_quantity) from stock_lot l left join stock_info s on s.area_id=l.area_id and s.product_id=l.product_id where s.id is null and l.lot_status in (0,1) group by l.area_id,l.product_id having sum(l.available_quantity)<>0) mismatch";
|
|
try (ResultSet rs = st.executeQuery(reconciliation)) {
|
|
rs.next(); if (rs.getLong(1)!=0) throw new IllegalStateException("Legacy quantity reconciliation failed; no inventory was changed");
|
|
}
|
|
try (ResultSet rs = st.executeQuery("select (select count(*) from inventory_cost_event)+(select count(*) from project_stock_balance)+(select count(*) from project_item_cost)")) {
|
|
rs.next(); if (rs.getLong(1)!=0) throw new IllegalStateException("New inventory already populated without cutover marker");
|
|
}
|
|
st.executeUpdate("insert into inventory_cost_event(project_id,item_id,area_id,event_key,event_type,quantity,receipt_amount,original_cost,effective_cost,create_by) select source_project_id,product_id,area_id,concat('LEGACY-STOCK:',id),'RECEIPT',available_quantity,case when unit_cost>0 then round(available_quantity*unit_cost,6) else null end,case when unit_cost>0 then round(available_quantity*unit_cost,6) else null end,case when unit_cost>0 then round(available_quantity*unit_cost,6) else null end,'inventory-cutover' from stock_lot where lot_status in (0,1) and available_quantity>0 order by id");
|
|
st.executeUpdate("insert into project_stock_balance(project_id,item_id,area_id,quantity) select project_id,item_id,area_id,sum(quantity) from inventory_cost_event group by project_id,item_id,area_id");
|
|
st.executeUpdate("insert into project_item_cost(project_id,item_id,quantity,amount) select project_id,item_id,sum(quantity),case when count(receipt_amount)=count(*) then sum(receipt_amount) else null end from inventory_cost_event group by project_id,item_id");
|
|
st.executeUpdate("insert into inventory_cutover(id,remark) values(1,'Current available stock preserved; historical zero prices treated as unknown; historical documents unchanged')");
|
|
connection.commit();
|
|
System.out.println("CUTOVER APPLIED TO "+DATABASE+"; original stock and documents preserved");
|
|
} catch (Exception failure) { connection.rollback(); throw failure; }
|
|
}
|
|
static String value(String text) {
|
|
if (text.startsWith("${") && text.endsWith("}")) {
|
|
String inside=text.substring(2,text.length()-1); int colon=inside.indexOf(':');
|
|
String name=colon<0?inside:inside.substring(0,colon);
|
|
String found=System.getenv(name); text=found!=null?found:colon<0?"":inside.substring(colon+1);
|
|
}
|
|
if (text.length()>1 && text.startsWith("'") && text.endsWith("'")) return text.substring(1,text.length()-1).replace("''", "'");
|
|
if (text.length()>1 && text.startsWith("\"") && text.endsWith("\"")) return text.substring(1,text.length()-1);
|
|
return text;
|
|
}
|
|
static String identifier(String name) {
|
|
if (!name.matches("[A-Za-z0-9_-]+")) throw new IllegalArgumentException("Unsafe identifier");
|
|
return "`"+name+"`";
|
|
}
|
|
static void inspect(Connection connection) throws Exception {
|
|
connection.setReadOnly(true);
|
|
StringBuilder schema=new StringBuilder("Database: "+DATABASE+"\n");
|
|
List<String> tables=new ArrayList<>();
|
|
try (PreparedStatement st=connection.prepareStatement("select table_name, engine from information_schema.tables where table_schema=? and table_type='BASE TABLE' order by table_name")) {
|
|
st.setString(1,DATABASE);
|
|
try (ResultSet rs=st.executeQuery()) { while(rs.next()) { tables.add(rs.getString(1)); schema.append("TABLE ").append(rs.getString(1)).append(" engine=").append(rs.getString(2)).append('\n'); } }
|
|
}
|
|
for (String table:tables) {
|
|
try (Statement st=connection.createStatement(); ResultSet rs=st.executeQuery("show create table "+identifier(table))) {
|
|
rs.next(); schema.append(rs.getString(2)).append(";\n\n");
|
|
}
|
|
try (Statement st=connection.createStatement(); ResultSet rs=st.executeQuery("select count(*) from "+identifier(table))) {
|
|
rs.next(); System.out.println(table+"\t"+rs.getLong(1));
|
|
}
|
|
}
|
|
Files.createDirectories(Path.of(".codex-tmp"));
|
|
Files.writeString(Path.of(".codex-tmp/projectdev-schema.txt"),schema.toString(),StandardCharsets.UTF_8);
|
|
System.out.println("INSPECTED "+DATABASE+" tables="+tables.size());
|
|
}
|
|
static void apply(Connection connection, Path file) throws Exception {
|
|
String sql=Files.readString(file,StandardCharsets.UTF_8);
|
|
if (!sql.startsWith("-- target-database: "+DATABASE)) throw new IllegalArgumentException("Missing database guard marker");
|
|
List<String> statements=split(sql);
|
|
// Only additive DDL and scoped DML. Never change server configuration, accounts, catalogs or other schemas.
|
|
for (String statement:statements) {
|
|
String normalized=statement.strip();
|
|
if (!normalized.matches("(?is)^(CREATE TABLE(?: IF NOT EXISTS)?|ALTER TABLE|INSERT INTO|UPDATE|SELECT)\\s+.*")) throw new IllegalArgumentException("Unsupported migration statement");
|
|
if (normalized.matches("(?is).*\\b(DROP|TRUNCATE|GRANT|REVOKE|DATABASE|GLOBAL|OUTFILE|INFILE|PREPARE|EXECUTE|CALL)\\b.*")) throw new IllegalArgumentException("Unsafe migration keyword");
|
|
if (Pattern.compile("`[^`]+`\\s*\\.\\s*`[^`]+`").matcher(normalized).find()) throw new IllegalArgumentException("Qualified schemas not allowed");
|
|
}
|
|
for (String statement:statements) {
|
|
Matcher addition=Pattern.compile("(?is)^ALTER TABLE\\s+`?(\\w+)`?\\s+ADD COLUMN\\s+`?(\\w+)`?\\s+.*").matcher(statement);
|
|
if (addition.matches()) {
|
|
try (ResultSet rs=connection.getMetaData().getColumns(DATABASE,null,addition.group(1),addition.group(2))) {
|
|
if(rs.next()) { System.out.println("EXISTS "+addition.group(1)+"."+addition.group(2)); continue; }
|
|
}
|
|
}
|
|
Matcher target=Pattern.compile("(?is)\\b(?:TABLE|INTO|FROM|JOIN|UPDATE)\\s+(?:IF NOT EXISTS\\s+)?(`?\\w[\\w-]*`?)\\s*\\.").matcher(statement);
|
|
if(target.find()) throw new IllegalArgumentException("Cross-schema access is not allowed");
|
|
try (Statement st=connection.createStatement()) {
|
|
if(st.execute(statement)) {
|
|
try(ResultSet rs=st.getResultSet()) { while(rs.next()) { StringJoiner row=new StringJoiner(" | "); for(int i=1;i<=rs.getMetaData().getColumnCount();i++) row.add(String.valueOf(rs.getObject(i))); System.out.println(row); } }
|
|
}
|
|
}
|
|
}
|
|
System.out.println("APPLIED "+file+" to "+DATABASE+" statements="+statements.size());
|
|
}
|
|
static List<String> split(String sql) {
|
|
List<String> result=new ArrayList<>(); StringBuilder current=new StringBuilder();
|
|
char quote=0; boolean comment=false;
|
|
for (int i=0;i<sql.length();i++) {
|
|
char c=sql.charAt(i);
|
|
if (comment) { if(c=='\n') { comment=false; current.append('\n'); } continue; }
|
|
if (quote==0 && c=='-' && i+1<sql.length() && sql.charAt(i+1)=='-') { comment=true; i++; continue; }
|
|
if (quote!=0) {
|
|
current.append(c);
|
|
if(c=='\\' && i+1<sql.length()) current.append(sql.charAt(++i));
|
|
else if(c==quote) { if(i+1<sql.length() && sql.charAt(i+1)==quote) current.append(sql.charAt(++i)); else quote=0; }
|
|
} else if(c=='\'' || c=='\"' || c=='`') { quote=c; current.append(c); }
|
|
else if(c==';') { if(!current.toString().isBlank()) result.add(current.toString().strip()); current.setLength(0); }
|
|
else current.append(c);
|
|
}
|
|
if(quote!=0) throw new IllegalArgumentException("Unclosed SQL string");
|
|
if(!current.toString().isBlank()) result.add(current.toString().strip());
|
|
return result;
|
|
}
|
|
}
|