我正在执行数据迁移,我使用的数据库只允许单独导出和导入每个表。在这样的设置中,导入成为一个问题,因为导入表的顺序很重要(您必须在引用表之前导入引用的表)。
是否有任何外部工具可以让我列出从最不依赖到最依赖排序的数据库表?
提前致谢。
这段代码帮助我解决了这个问题。它根据从数据库元数据中读取的 FK 关系将表从最不依赖到最依赖排序。
public class Main {
public static void main(String[] args) throws SQLException {
DriverManager.registerDriver(new TimesTenDriver());
Connection c = ...;
DatabaseMetaData md = c.getMetaData();
final ResultSet rawTables = md.getTables(null, "<your schema>", "%", null);
List<Table> tables = new ArrayList<Table>();
while (rawTables.next()) {
final String tableName = rawTables.getString("TABLE_NAME");
Table table = new Table(tableName);
ResultSet rawKeys = md.getImportedKeys(null, "<your schema>", tableName);
while (rawKeys.next()) {
table.refs.add(rawKeys.getString("PKTABLE_NAME"));
}
rawKeys.close();
tables.add(table);
}
rawTables.close();
c.close();
LinkedList<List<Table>> layers = new LinkedList<List<Table>>();
while (tables.size() > 0) {
List<Table> indep = new ArrayList<Table>();
for (Table o : tables) {
indep.add(o);
for (Table i : tables) {
if (i.refs.contains(o.name)) {
indep.remove(o);
break;
}
}
}
layers.add(indep);
for (Iterator<Table> it = tables.iterator(); it.hasNext(); ) {
Table t = it.next();
if (indep.contains(t)) {
it.remove();
}
}
}
for (ListIterator<List<Table>> it = layers.listIterator(layers.size()); it.hasPrevious(); ) {
final List<Table> layer = it.previous();
for (Table table : layer) {
System.out.println("ttbulkcp -i <your DSN> <your schema>." + table + " " + table);
}
}
}
private static class Table {
public final String name;
public final Set<String> refs;
public Table(String name) {
this.name = name;
this.refs = new HashSet<String>();
}
}
}