我们已经在代码库中介绍了Flyway。前面,我们将Postgres函数存储在公共模式中,并使用它来复制租户模式,以创建与租户模式具有相同结构的新模式。repo代码如下:
@Repository
public interface TenantRepository extends JpaRepository<Tenant, UUID> {
@Query(nativeQuery = true, value = "SELECT clone_schema(:defaultSchema,:newSchema,:isCopyData);")
String callCloneSchema(@Param("defaultSchema") String defaultSchema, @Param("newSchema") String newSchema,@Param("isCopyData") boolean isCopyData);
}
我想删除这些函数,并希望使用Flyway创建一个新的模式。Flyway提供这样的可能性吗?
以下是使用单个模式手动触发Flyway迁移的一些步骤:
1。禁用"自动迁移">
默认情况下,Spring引导希望自动运行Flyway SQL脚本。所以你必须禁用这个自动迁移(见4.3。在本博客中)。这里,这是在"Spring Boot主类":
中完成的。@SpringBootApplication
public class FooApplication {
public static void main(String[] args) {
SpringApplication.run(FooApplication.class, args);
}
@Bean
public FlywayMigrationStrategy flywayMigrationStrategy() {
return flyway -> {
// do nothing
};
}
}
2。手动迁移
要使用不同的模式自动执行迁移,这是一种解决方案:
- 注入(默认)
Flyway
实例 - 复制配置,但覆盖要使用的模式
- 触发迁移
示例代码:通过GET请求触发迁移(SQL文件在src/main/resources/db/migration/V#_#_#__xyz.sql
下)
@Controller
public class FooController {
@Autowired
Flyway flyway;
@GetMapping("foo")
public ResponseEntity<?> foo(@RequestParam("schema") String schema) {
Flyway.configure()
// apply/use the default (Spring) flyway configiration
.configuration(flyway.getConfiguration())
// use the passed schema
.schemas(schema)
.defaultSchema(schema)
// get a Flyway instance
.load()
// run the migration
.migrate();
return ResponseEntity.noContent().build();
}
}