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"))) { throw new IllegalArgumentException("Usage: inspect | apply | cutover"); } Map 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 apply(connection, Path.of(args[1])); } } /** 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 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 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 split(String sql) { List result=new ArrayList<>(); StringBuilder current=new StringBuilder(); char quote=0; boolean comment=false; for (int i=0;i