在 Java 中清理(删除所有对象、表、 View 等)Oracle 数据库模式的最佳方法是什么?
我可以运行类似 https://stackoverflow.com/a/1690419/812093 的东西使用 Oracle 数据库客户端,但是否有可以使用的 Java 库或工具?我知道我可以读取连接元数据,遍历所有对象并删除它们,但我想知道以前是否有人这样做过,是否有任何开箱即用的东西可以使用。
我需要这个功能来设置集成测试 - 清理数据库模式 - 针对该模式执行一堆脚本以初始化数据库
最佳答案
飞行路线
它看起来像 Flyway数据库迁移工具提供了我一直在寻找的功能——至少如果你喜欢黑客 :) 因为我只需要这个功能来进行集成测试,所以它对我来说已经足够好了。让我分享我的代码。
添加Flyway和Oracle驱动依赖
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
<version>5.1.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc7</artifactId>
<version>12.1.0.2</version>
<scope>provided</scope>
</dependency>
执行脚本和清理数据库的主类
public class ExecuteScriptsAgainstOracle {
public static void main(String args[]) throws Exception, SQLException {
Flyway flyway = new Flyway();
flyway.setDataSource("jdbc:oracle:thin:@xxx:1521:yyy", "zzz", "zzz");
flyway.setTable("auto_schema_setup_flyway");
Database<?> database = DatabaseFactory.createDatabase(flyway.getConfiguration(), false);
// clean the database (remove all objects of the schema)
flyway.clean();
flyway.setSkipDefaultResolvers(true);
flyway.setResolvers(new MyMigrationResolver(database, flyway.getConfiguration()));
flyway.migrate();
}
}
列出要执行文件的MigrationResolver
包 org.flywaydb.core.internal.resolver.sql;
公共(public)类 MyMigrationResolver 实现 MigrationResolver {
private Database<?> database;
private Configuration configuration;
private int order = 0;
public MyMigrationResolver(Database<?> database, Configuration configuration) {
this.database = database;
this.configuration = configuration;
}
@Override
public Collection<ResolvedMigration> resolveMigrations() {
Collection<ResolvedMigration> scripts = new LinkedList<ResolvedMigration>();
scripts.add(script(folder1\\somescript.dml"));
scripts.add(script("folder2\\someOtherScript.sql"));
return scripts;
}
private ResolvedMigrationImpl script(String scriptName) {
String baseFolder = "target\\scripts\\";
order++;
ResolvedMigrationImpl migration = new ResolvedMigrationImpl();
migration.setScript(baseFolder+scriptName);
migration.setType(MigrationType.SQL);
migration.setDescription(""+String.format("%03d",order)+" "+scriptName);
migration.setExecutor(new SqlMigrationExecutor(database,
new FileSystemResource(migration.getScript(), configuration.getEncoding()),
new PlaceholderReplacer() {
@Override
public String replacePlaceholders(String input) {
// just remove parts of the sql that flyway can't deal with
input = StringUtils.replace(input, "WHENEVER SQLERROR EXIT SQL.SQLCODE ROLLBACK;", "");
input = StringUtils.replace(input, "SET DEFINE OFF;", "");
return input;
}
@Override
public Map<String, String> getPlaceholderReplacements() {
return null;
}
}
, configuration));
return migration;
}
关于java - 如何删除 java 中模式的所有数据库对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50879385/