65 lines
2.9 KiB
Java
65 lines
2.9 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 MigrateRun2 {
|
|
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> tableNames = new ArrayList<>();
|
|
List<List<String>> tableStmts = 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] : "";
|
|
if (!body.contains("ALTER TABLE") && !body.contains("EXEC sp_rename")) continue;
|
|
// drop GO lines, split statements by ';'
|
|
StringBuilder sb = new StringBuilder();
|
|
for (String line : body.split("\\R")) {
|
|
if (line.trim().equalsIgnoreCase("GO")) continue;
|
|
sb.append(line).append("\n");
|
|
}
|
|
List<String> stmts = new ArrayList<>();
|
|
for (String s : sb.toString().split(";")) {
|
|
String t = s.trim();
|
|
if (!t.isEmpty()) stmts.add(t);
|
|
}
|
|
tableNames.add(name);
|
|
tableStmts.add(stmts);
|
|
}
|
|
|
|
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);
|
|
List<String> stmts = tableStmts.get(t);
|
|
conn.setAutoCommit(false);
|
|
boolean failed = false;
|
|
for (String s : stmts) {
|
|
try (Statement st = conn.createStatement()) { st.execute(s); }
|
|
catch (SQLException e) {
|
|
System.err.println("FAILED on " + tbl + ": " + e.getMessage());
|
|
System.err.println(" SQL: " + s.replaceAll("\\s+", " ").trim());
|
|
failed = true; break;
|
|
}
|
|
}
|
|
if (failed) { conn.rollback(); System.err.println(" -> ROLLED BACK " + tbl); }
|
|
else { conn.commit(); System.out.println("OK: " + tbl + " (" + stmts.size() + " stmts)"); ok++; }
|
|
}
|
|
}
|
|
System.out.println("\nMigrated OK: " + ok + "/" + tableNames.size());
|
|
}
|
|
}
|