cmvr-wms/scripts/projectdev/ReadOnlyDataInventory.java

59 lines
5.7 KiB
Java
Raw Permalink Normal View History

import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.sql.*;
import java.util.*;
/** Source inventory only: every database session is an explicit read-only transaction. */
public class ReadOnlyDataInventory {
static final Set<String> ALLOWED = Set.of("wms-dev", "cmvr-project-dev");
public static void main(String[] args) throws Exception {
if (args.length < 1 || args.length > 2 || !ALLOWED.contains(args[0])) throw new IllegalArgumentException("Expected an authorized database name");
String database = args[0];
String output=args.length==2?args[1]:database;
if(!output.matches("[A-Za-z0-9_-]+"))throw new IllegalArgumentException("Invalid output basename");
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(),DatabaseTool.value(line.substring(colon+1).trim())); }
}
String configured = config.get("url");
if(configured==null || !configured.matches("^jdbc:mysql://192\\.168\\.28\\.10:3306/cmvr-project-dev(?:\\?.*)?$")) throw new IllegalStateException("Configured target mismatch");
String url=configured.replace("/cmvr-project-dev", "/"+database);
Properties properties=new Properties(); properties.setProperty("user",config.get("username"));properties.setProperty("password",config.get("password"));properties.setProperty("connectTimeout","5000");properties.setProperty("socketTimeout","60000");properties.setProperty("tinyInt1isBit","false");
Path directory=Path.of(".codex-tmp/real-data-replay");Files.createDirectories(directory);
try(Connection connection=DriverManager.getConnection(url,properties)) {
connection.setReadOnly(true);
connection.setAutoCommit(false);
try(Statement statement=connection.createStatement()) { statement.execute("START TRANSACTION READ ONLY"); }
try(Statement statement=connection.createStatement();ResultSet result=statement.executeQuery("select database()")) {result.next();if(!database.equals(result.getString(1)))throw new IllegalStateException("Database mismatch");}
List<String> names=new ArrayList<>();
try(PreparedStatement statement=connection.prepareStatement("select table_name from information_schema.tables where table_schema=? and table_type='BASE TABLE' order by table_name")) {statement.setString(1,database);try(ResultSet result=statement.executeQuery()){while(result.next())names.add(result.getString(1));}}
StringBuilder schema=new StringBuilder();Map<String,Object> tables=new LinkedHashMap<>();
for(String name:names) {
try(Statement statement=connection.createStatement();ResultSet result=statement.executeQuery("show create table "+identifier(name))) {result.next();schema.append(result.getString(2)).append(";\n\n");}
List<Map<String,Object>> rows=new ArrayList<>();
// Source data is exported for browser form entry. Target is inventoried, never copied.
if(database.equals("wms-dev")) try(Statement statement=connection.createStatement();ResultSet result=statement.executeQuery("select * from "+identifier(name))) {
ResultSetMetaData metadata=result.getMetaData();
while(result.next()){Map<String,Object> row=new LinkedHashMap<>();for(int i=1;i<=metadata.getColumnCount();i++){Object value=result.getObject(i);if(value instanceof byte[])value=Base64.getEncoder().encodeToString((byte[])value);row.put(metadata.getColumnLabel(i),value);}rows.add(row);}
}
long count;
try(Statement statement=connection.createStatement();ResultSet result=statement.executeQuery("select count(*) from "+identifier(name))){result.next();count=result.getLong(1);}
tables.put(name,Map.of("count",count,"rows",rows));System.out.println(name+"\t"+count);
}
Files.writeString(directory.resolve(output+"-schema.sql"),schema,StandardCharsets.UTF_8);
Files.writeString(directory.resolve(output+"-inventory.json"),json(Map.of("database",database,"readOnly",true,"tables",tables)),StandardCharsets.UTF_8);
connection.rollback();
System.out.println("READ ONLY inventory complete: "+database+", tables="+names.size());
}
}
static String identifier(String name){if(!name.matches("[A-Za-z0-9_]+"))throw new IllegalArgumentException("Unsafe table");return "`"+name+"`";}
static String json(Object value){
if(value==null)return "null";if(value instanceof Number||value instanceof Boolean)return value.toString();
if(value instanceof Map<?,?> map){StringJoiner joiner=new StringJoiner(",","{","}");map.forEach((key,item)->joiner.add(json(key.toString())+":"+json(item)));return joiner.toString();}
if(value instanceof Collection<?> collection){StringJoiner joiner=new StringJoiner(",","[","]");collection.forEach(item->joiner.add(json(item)));return joiner.toString();}
StringBuilder result=new StringBuilder("\"");for(char c:value.toString().toCharArray())switch(c){case '"' ->result.append("\\\"");case '\\' ->result.append("\\\\");case '\n' ->result.append("\\n");case '\r' ->result.append("\\r");case '\t' ->result.append("\\t");default->{if(c<32)result.append(String.format("\\u%04x",(int)c));else result.append(c);}}return result.append('"').toString();
}
}