liquibase - 如何在使用 java 比较两个数据库后从变更日志生成 sql 脚本?

liquibase - how to generate the sql script from the changelog after comparing two databases using java?

我用liquibase java API 3.3.2对比了两个数据库,然后生成了changelog.xml文件。现在,我想生成将更新目标数据库的 sql 脚本。 这是我的代码:

Database database;
Database database2;
try {
    database = CommandLineUtils.createDatabaseObject(org.postgresql.Driver.class.getClassLoader(), "jdbc:postgresql://localhost:5432/loan", "postgres", "", "org.postgresql.Driver", null, null, false, false, null, null, null, null, null);
    database2=CommandLineUtils.createDatabaseObject(org.postgresql.Driver.class.getClassLoader(), "jdbc:postgresql://localhost:5432/loan2", "postgres", "", "org.postgresql.Driver", null, null, false, false, null, null, null, null, null);
    Liquibase liquibase = new Liquibase("", new FileSystemResourceAccessor(), database);
    DiffResult result = liquibase.diff(database, database2, new CompareControl());
    DiffToChangeLog diffLog = new DiffToChangeLog(result, new DiffOutputControl());
    diffLog.print(System.out);
    //new DiffToReport(result, System.out).print();

} catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

编辑 这是我的做法,感谢 Steve donie:

        Database database;
    Database database2;
    try {
        database = CommandLineUtils.createDatabaseObject(org.postgresql.Driver.class.getClassLoader(), "jdbc:postgresql://localhost:5432/loan", "postgres", "", "org.postgresql.Driver", null, null, false, false, null, null, null, null, null);
        database2= CommandLineUtils.createDatabaseObject(org.postgresql.Driver.class.getClassLoader(), "jdbc:postgresql://localhost:5432/loan2", "postgres", "", "org.postgresql.Driver", null, null, false, false, null, null, null, null, null);

        // generate the changelog that contains the differences
        CommandLineUtils.doDiffToChangeLog("changelog.xml", database, database2, new DiffOutputControl(), null, null);

        // generate the sql script from the changeLog (without executing it)
        File sql = new File("output.sql");
        Liquibase liquibase = new Liquibase("changelog.xml", new FileSystemResourceAccessor(), database);
        liquibase.update("Update", new FileWriter(sql));
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

解决此问题的一种方法是从命令行查看 运行 时 Liquibase 本身做了什么。在这种情况下,您通常会使用 diffChangeLog 命令创建更新日志,然后 运行 updateSQL 生成更新数据库所需的 SQL。查看 liquibase.integration.commandline.Main 的 Liquibase 源代码,我看到 what it does is to use the Liquibase.update() method with arguments that specify a non-null output writer(这是 SQL 将保存到的文件)。