2010-05-28 60 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>(); 
     } 
    } 
}