import java.sql.*; import java.util.*; import java.nio.file.*; import java.security.MessageDigest; import java.time.LocalDateTime; import com.fasterxml.jackson.databind.ObjectMapper; /** Exact two-table synchronization with a bound plan, one backup and atomic readback. */ class MenuTransfer { static final ObjectMapper JSON=new ObjectMapper(); static final Path DIR=Path.of("runtime/dev-private/menu-mysql-20261118"); record Column(String name,String type) {} record Data(List columns,List> rows) {} static String sha(Object value) throws Exception { return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(JSON.writeValueAsBytes(value))); } static Data read(Connection c,String table,List columns,boolean mysql) throws Exception { String names=String.join(",",columns.stream().map(x->mysql?"`"+x.name+"`":"\""+x.name.toUpperCase(Locale.ROOT)+"\"").toList()); var rows=new ArrayList>(); try(var s=c.createStatement();var r=s.executeQuery("SELECT "+names+" FROM "+table+" ORDER BY "+(table.equals("sys_menu")?"menu_id":"role_id,menu_id"))) { while(r.next()) { var row=new ArrayList(); for(int i=0;i columns(Connection c,String table) throws Exception { var out=new ArrayList(); try(var s=c.prepareStatement("SELECT column_name,data_type FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name=? ORDER BY ordinal_position")) { s.setString(1,table);try(var r=s.executeQuery()){while(r.next())out.add(new Column(r.getString(1),r.getString(2)));} }return out; } static Map roles(Connection c) throws Exception { var out=new TreeMap(); try(var s=c.createStatement();var r=s.executeQuery("SELECT role_id,role_key FROM sys_role")){while(r.next())out.put(r.getString(1),r.getString(2));} return out; } static int index(Data d,String column){return d.columns.stream().map(Column::name).toList().indexOf(column);} static void validate(Map data,Map sourceRoles,Map targetRoles) { Data menus=data.get("sys_menu"), grants=data.get("sys_role_menu"); var parents=new HashMap(); for(var row:menus.rows)parents.put(row.get(index(menus,"menu_id")),row.get(index(menus,"parent_id"))); for(String id:parents.keySet()) { var seen=new HashSet();String next=id; while(next!=null&&!next.equals("0")) { if(!seen.add(next)||!parents.containsKey(next))throw new IllegalStateException("Invalid menu parent or cycle"); next=parents.get(next); } } for(var row:grants.rows) { String role=row.get(index(grants,"role_id")); if(!parents.containsKey(row.get(index(grants,"menu_id")))||!sourceRoles.containsKey(role)||!Objects.equals(sourceRoles.get(role),targetRoles.get(role))) throw new IllegalStateException("Menu grant has missing menu or mismatched role identity"); } } static void insert(Connection c,String table,Data data) throws Exception { String cols=String.join(",",data.columns.stream().map(x->"\""+x.name.toUpperCase(Locale.ROOT)+"\"").toList()); try(var p=c.prepareStatement("INSERT INTO "+table+"("+cols+") VALUES("+String.join(",",Collections.nCopies(data.columns.size(),"?"))+")")) { int n=0; for(var row:data.rows) { for(int i=0;i>(); for(var r:target.rows)old.put(table.equals("sys_menu")?r.get(0):r.get(0)+":"+r.get(1),r); int added=0,changed=0,same=0; var fields=new TreeMap(); for(var r:source.rows) { var before=old.remove(table.equals("sys_menu")?r.get(0):r.get(0)+":"+r.get(1)); if(before==null)added++;else if(before.equals(r))same++;else { changed++; for(int i=0;i();var target=new TreeMap(); for(String table:List.of("sys_menu","sys_role_menu")) { var cols=columns(src,table);source.put(table,read(src,table,cols,true));target.put(table,read(dst,table,cols,false)); differences(table,source.get(table),target.get(table)); } var sr=roles(src);var dr=roles(dst);validate(source,sr,dr); String sourceHash=sha(source),targetHash=sha(target); var plan=Map.of("sourceSha256",sourceHash,"targetSha256",targetHash,"sourceRolesSha256",sha(sr),"targetRolesSha256",sha(dr),"targetSchema",schema); Path planPath=DIR.resolve("plan.json"); if(mode.equals("plan")) { Files.createDirectories(DIR); if(Files.exists(planPath)&&!JSON.readTree(Files.readString(planPath)).equals(JSON.valueToTree(plan)))throw new IllegalStateException("Existing plan changed; reconcile first"); if(!Files.exists(planPath))Files.writeString(planPath,JSON.writeValueAsString(plan),StandardOpenOption.CREATE_NEW); System.out.println("PLAN_BOUND; role identities and parent graph verified; database unchanged"); } else if(mode.equals("verify")) { if(!sourceHash.equals(targetHash))throw new IllegalStateException("Menu or role-menu content mismatch"); System.out.println("FULL_COLUMN_EQUAL=true PARENTS_VALID=true ROLE_MENU_VALID=true"); } else if(mode.equals("apply")) { if(!JSON.readTree(Files.readString(planPath)).equals(JSON.valueToTree(plan)))throw new IllegalStateException("Source or target drift since plan"); Path backup=DIR.resolve("before.json"); if(Files.exists(backup))throw new IllegalStateException("Previous attempt exists; verify before retry"); Files.writeString(backup,JSON.writeValueAsString(target),StandardOpenOption.CREATE_NEW); try(var s=dst.createStatement()){s.executeUpdate("DELETE FROM sys_role_menu");s.executeUpdate("DELETE FROM sys_menu");} insert(dst,"sys_menu",source.get("sys_menu"));insert(dst,"sys_role_menu",source.get("sys_role_menu")); var after=new TreeMap(); for(String table:source.keySet())after.put(table,read(dst,table,source.get(table).columns,false)); if(!sha(after).equals(sourceHash))throw new IllegalStateException("Full-column readback mismatch before commit"); validate(after,sr,roles(dst));committing=true;dst.commit();committing=false;committed=true; Files.writeString(DIR.resolve("result.json"),JSON.writeValueAsString(Map.of("status","COMMITTED","sourceSha256",sourceHash,"menus",source.get("sys_menu").rows.size(),"roleMenus",source.get("sys_role_menu").rows.size())),StandardOpenOption.CREATE_NEW); System.out.println("COMMITTED; all menu fields and role-menu grants read back equal"); } if(!mode.equals("apply"))dst.rollback();src.rollback(); }catch(Exception e){ if(committed){System.err.println("COMMITTED_REPORT_FAILED: verify before any further operation");System.exit(2);} if(committing){System.err.println("COMMIT_UNKNOWN: verify before retry");System.exit(2);} try{dst.rollback();}catch(Exception x){System.err.println("ROLLBACK_UNKNOWN");System.exit(2);} if(e instanceof SQLException sql)System.err.println("FAILED SQLSTATE="+sql.getSQLState()+" code="+sql.getErrorCode()); else System.err.println("FAILED: "+e.getMessage()); System.exit(1); } }catch(SQLException e){System.err.println("CONNECTION_FAILED SQLSTATE="+e.getSQLState()+" code="+e.getErrorCode());System.exit(1);} } }