文件
AiXun-DataGov/script/database/LibraryTransfer.java
T
2026-11-20 15:32:57 +08:00

173 行
12 KiB
Java

import java.sql.*;
import java.util.*;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;
/** Inserts missing rows only, rejects conflicting IDs, preserves IDs and audit fields. */
class LibraryTransfer {
static final ObjectMapper JSON = new ObjectMapper();
static final Set<String> ALLOWED = Set.of(
"std_national_standard_catalog", "std_national_standard_classification",
"std_national_standard_import_batch", "std_national_standard_import_page",
"std_national_standard_import_item", "std_national_standard_observation",
"std_national_standard_replacement", "dq_quality_rule_template",
"dev_transformation_rule_template");
record Col(String name, String type) {}
static String table;
static long count(Connection c, String t) throws Exception {
try(var s=c.createStatement(); var r=s.executeQuery("SELECT COUNT(*) FROM "+t)) {r.next();return r.getLong(1);}
}
static List<Col> columns(Connection source,String t) throws Exception {
var result=new ArrayList<Col>();
try(var s=source.prepareStatement("SELECT column_name,data_type FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name=? AND extra NOT LIKE '%VIRTUAL GENERATED%' AND extra NOT LIKE '%STORED GENERATED%' ORDER BY ordinal_position")) {
s.setString(1,t);try(var r=s.executeQuery()){while(r.next())result.add(new Col(r.getString(1),r.getString(2)));}
}return result;
}
static String keyColumn(Connection source,String t) throws Exception {
var keys=new ArrayList<String>();
try(var r=source.getMetaData().getPrimaryKeys(source.getCatalog(),null,t)){while(r.next())keys.add(r.getString("COLUMN_NAME"));}
if(keys.size()!=1)throw new IllegalStateException("Expected single primary key: "+t);
return keys.get(0);
}
static Object value(ResultSet r,int i,Col col) throws Exception {
String v=r.getString(i);if(v==null)return null;
return switch(col.type) {
case "bigint","int","smallint","tinyint","decimal","numeric","float","double" -> new BigDecimal(v).stripTrailingZeros().toPlainString();
case "timestamp","datetime" -> r.getTimestamp(i).toLocalDateTime().toString();
case "date" -> r.getDate(i).toLocalDate().toString();
case "json" -> JSON.readTree(v);
default -> v;
};
}
static String digest(ResultSet r,List<Col> cols, boolean ignoreSeedTimes) throws Exception {
var values=new ArrayList<Object>();
for(int i=0;i<cols.size();i++) {
Col c=cols.get(i);
if(ignoreSeedTimes && Set.of("create_time","update_time").contains(c.name))continue;
Object v=value(r,i+1,c);
if(v instanceof JsonNode j) v=canonical(j);
values.add(v);
}
return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(JSON.writeValueAsBytes(values)));
}
static Object canonical(JsonNode n) {
if(n.isObject()){var m=new TreeMap<String,Object>();n.properties().forEach(e->m.put(e.getKey(),canonical(e.getValue())));return m;}
if(n.isArray()){var a=new ArrayList<Object>();n.forEach(x->a.add(canonical(x)));return a;}
return n;
}
static void bind(PreparedStatement s,int i,ResultSet r,Col c) throws Exception {
String v=r.getString(i);
if(v==null){s.setNull(i,Types.NULL);return;}
switch(c.type) {
case "bigint","int","smallint","tinyint","decimal","numeric","float","double" -> s.setBigDecimal(i,new BigDecimal(v));
case "timestamp","datetime" -> s.setTimestamp(i,r.getTimestamp(i));
case "date" -> s.setDate(i,r.getDate(i));
default -> s.setString(i,v);
}
}
static void verifyRelations(Connection c,Set<String> tables) throws Exception {
String[][] links={
{"std_national_standard_classification","catalog_standard_id","std_national_standard_catalog","catalog_standard_id"},
{"std_national_standard_observation","catalog_standard_id","std_national_standard_catalog","catalog_standard_id"},
{"std_national_standard_observation","batch_id","std_national_standard_import_batch","batch_id"},
{"std_national_standard_import_page","batch_id","std_national_standard_import_batch","batch_id"},
{"std_national_standard_import_item","batch_id","std_national_standard_import_batch","batch_id"},
{"std_national_standard_import_item","catalog_standard_id","std_national_standard_catalog","catalog_standard_id"},
{"std_national_standard_replacement","catalog_standard_id","std_national_standard_catalog","catalog_standard_id"}
};
int checked=0;
for(String[] link:links) {
if(!tables.contains(link[0])||!tables.contains(link[2]))continue;
try(var s=c.createStatement();var r=s.executeQuery("SELECT COUNT(*) FROM "+link[0]+" c WHERE NOT EXISTS(SELECT 1 FROM "+link[2]+" p WHERE p."+link[3]+"=c."+link[1]+")")) {
r.next();if(r.getLong(1)!=0)throw new IllegalStateException("Dangling reference: "+link[0]+"."+link[1]);
}
checked++;
}
System.out.println("RELATION_CHECKS_PASS="+checked);
}
public static void main(String[] args) throws Exception {
String mode=args[0];String[] tables=args[1].split(",");
if(!Set.of("inventory","plan","apply","verify").contains(mode)||!ALLOWED.containsAll(Arrays.asList(tables)))throw new IllegalArgumentException("Unsupported scope");
String schema=System.getenv("DATAGOV_DM_SCHEMA");
if(!schema.matches("AIXUN_DATAGOV_[A-Z0-9_]+"))throw new IllegalArgumentException("Dedicated schema required");
Properties sp=new Properties();sp.setProperty("user","root");sp.setProperty("password",System.getenv("DG_SOURCE_PASSWORD"));
sp.setProperty("useCursorFetch","true");sp.setProperty("useSSL","false");sp.setProperty("allowPublicKeyRetrieval","true");sp.setProperty("connectionTimeZone","LOCAL");
Properties dp=new Properties();dp.setProperty("user",System.getenv("DATAGOV_DM_USERNAME"));dp.setProperty("password",System.getenv("DATAGOV_DM_PASSWORD"));dp.setProperty("socketTimeout","120000");
boolean committing=false;
try(Connection src=DriverManager.getConnection("jdbc:mysql://127.0.0.1:"+System.getenv("DG_SOURCE_PORT")+"/aixun_datagov_system",sp);
Connection dst=DriverManager.getConnection("jdbc:dm://"+System.getenv("DATAGOV_DM_HOST")+":"+System.getenv("DATAGOV_DM_PORT"),dp)) {
src.setReadOnly(true);src.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);src.setAutoCommit(false);
dst.setSchema(schema);if(!schema.equals(dst.getSchema()))throw new IllegalStateException("Schema mismatch");
dst.setAutoCommit(false);
try {
long totalMissing=0;
for(String t:tables) {
table=t;
long sc=count(src,t),dc=count(dst,t);
if(mode.equals("inventory")){System.out.println(t+" source="+sc+" target="+dc);continue;}
List<Col> cols=columns(src,t);String pk=keyColumn(src,t);
String select=String.join(",",cols.stream().map(c->"\""+c.name.toUpperCase(Locale.ROOT)+"\"").toList());
String sourceSelect=String.join(",",cols.stream().map(c->"`"+c.name+"`").toList());
boolean seed=t.equals("dev_transformation_rule_template");
Map<String,String> existing=new HashMap<>();
Map<String,String> expected=new HashMap<>();
try(var s=dst.createStatement();var r=s.executeQuery("SELECT "+select+" FROM "+t)) {
while(r.next())existing.put(r.getString(pk),digest(r,cols,seed));
}
long missing=0,matched=0,conflicts=0,processed=0;
String insert="INSERT INTO "+t+"("+select+") VALUES("+String.join(",",Collections.nCopies(cols.size(),"?"))+")";
try(var read=src.prepareStatement("SELECT "+sourceSelect+" FROM `"+t+"` ORDER BY `"+pk+"`");var write=dst.prepareStatement(insert)) {
read.setFetchSize(1000);
try(var r=read.executeQuery()) {
while(r.next()) {
String key=r.getString(pk);String previous=existing.get(key);
String hash=(previous!=null||mode.equals("apply"))?digest(r,cols,seed):null;
if(mode.equals("apply"))expected.put(key,hash);
if(previous!=null){if(previous.equals(hash))matched++;else conflicts++;}
else {
missing++;
if(mode.equals("apply")) {
for(int i=0;i<cols.size();i++)bind(write,i+1,r,cols.get(i));
write.addBatch();if(missing%500==0){write.executeBatch();write.clearBatch();}
}
}
processed++;
if(processed%25000==0)System.out.println(t+" scanned="+processed+" committed=false");
}
}
if(mode.equals("apply")){write.executeBatch();write.clearBatch();}
}
System.out.println(t+" source="+sc+" target="+dc+" missing="+missing+" matched="+matched+" conflicts="+conflicts);
if(processed!=sc||conflicts>0)throw new IllegalStateException("Source count changed or conflicting target IDs");
if(mode.equals("verify")&&missing>0)throw new IllegalStateException("Missing source rows");
if(mode.equals("apply")&&count(dst,t)!=dc+missing)throw new IllegalStateException("Target count mismatch");
if(mode.equals("apply")) {
try(var s=dst.createStatement();var r=s.executeQuery("SELECT "+select+" FROM "+t)) {
while(r.next()) {
String hash=expected.remove(r.getString(pk));
if(hash!=null&&!hash.equals(digest(r,cols,seed)))throw new IllegalStateException("Transactional full-column readback mismatch");
}
}
if(!expected.isEmpty())throw new IllegalStateException("Transactional readback has missing IDs");
System.out.println(t+" full_column_readback=PASS committed=false");
}
totalMissing+=missing;
}
if(mode.equals("apply")||mode.equals("verify"))verifyRelations(dst,Set.of(tables));
if(mode.equals("apply")){committing=true;dst.commit();committing=false;System.out.println("COMMITTED_INSERTS="+totalMissing);}
else {dst.rollback();System.out.println("READ_ONLY_COMPLETE missing="+totalMissing);}
src.rollback();
} catch(Exception e) {
if(committing){System.err.println("COMMIT_UNKNOWN: run verify before any 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("ROLLED_BACK table="+table+" SQLSTATE="+sql.getSQLState()+" code="+sql.getErrorCode());
else System.err.println("ROLLED_BACK table="+table+" reason="+e.getMessage());
System.exit(1);
}
}catch(SQLException e){System.err.println("CONNECTION_FAILED SQLSTATE="+e.getSQLState()+" code="+e.getErrorCode());System.exit(1);}
}
}