将DB表从最少依赖到最依赖

时间:2010-05-28 09:04:15

标签: database migration timesten

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

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

提前致谢。

1 个答案:

答案 0 :(得分:2)

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