2010-05-28 83 views
1

我正在执行数据迁移,我正在使用的数据库只允许分别导出和导入每个表。在这样的设置中,导入成为一个问题,因为导入表的顺序很重要(您必须在引用表之前导入引用的表)。从最不依赖到最依赖的数据库表排序

是否有任何外部工具,允许我列出从最小依赖到最依赖的排序数据库表?

在此先感谢。

+0

您正在使用哪些DBMS? – 2010-05-28 09:05:00

+0

我正在使用TimesTen。看起来没有包含这种工具,所以我正在寻找一些第三方软件。 – 2010-05-28 09:06:03

回答

2

此代码帮助我解决了这个问题。它根据从数据库元数据中读取的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>(); 
     } 
    } 
}