Files
workspace/code/fms/.tmp-fkcheck/MigrateRun.java
T
2026-08-21 23:06:56 +08:00

75 lines
3.2 KiB
Java

import java.io.FileInputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
public class MigrateRun {
public static void main(String[] args) throws Exception {
Properties props = new Properties();
try (FileInputStream in = new FileInputStream(args[0])) { props.load(in); }
String script = new String(Files.readAllBytes(Paths.get(args[1])), StandardCharsets.UTF_8);
// split into per-table blocks by "-- ===== " headers
String[] blocks = script.split("(?m)^-- ===== ");
List<String[]> tableBatches = new ArrayList<>();
List<String> tableNames = new ArrayList<>();
for (String b : blocks) {
if (b.isBlank()) continue;
String[] lines = b.split("\\R", 2);
String name = lines[0].trim();
String body = lines.length > 1 ? lines[1] : "";
// skip comment-only tail
if (!body.contains("ALTER TABLE") && !body.contains("EXEC sp_rename")) continue;
// split body by GO lines
List<String> batches = new ArrayList<>();
StringBuilder cur = new StringBuilder();
for (String line : body.split("\\R")) {
if (line.trim().equalsIgnoreCase("GO")) {
if (!cur.toString().isBlank()) batches.add(cur.toString());
cur.setLength(0);
} else {
cur.append(line).append("\n");
}
}
if (!cur.toString().isBlank()) batches.add(cur.toString());
tableBatches.add(batches.toArray(new String[0]));
tableNames.add(name);
}
System.out.println("Tables to migrate: " + tableNames.size());
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
int ok = 0;
try (Connection conn = DriverManager.getConnection(props.getProperty("url"), props.getProperty("username"), props.getProperty("password"))) {
for (int t = 0; t < tableNames.size(); t++) {
String tbl = tableNames.get(t);
String[] batches = tableBatches.get(t);
conn.setAutoCommit(false);
boolean failed = false;
for (String batch : batches) {
try (Statement st = conn.createStatement()) {
st.execute(batch);
} catch (SQLException e) {
System.err.println("FAILED on " + tbl + " batch: " + e.getMessage());
System.err.println(" SQL: " + batch.replaceAll("\\s+", " ").trim());
failed = true;
break;
}
}
if (failed) {
conn.rollback();
System.err.println(" -> ROLLED BACK " + tbl);
} else {
conn.commit();
System.out.println("OK: " + tbl + " (" + batches.length + " batches)");
ok++;
}
}
}
System.out.println("\nMigrated OK: " + ok + "/" + tableNames.size());
}
}