Forked from mattbroekhuis/HibernateDDLFlywayMigration.java
Created
September 9, 2019 12:56
-
-
Save allanfreitas/08746d1be9f850f1cbdcd061c2939670 to your computer and use it in GitHub Desktop.
Export hibernate ddl changes to flyway db migrations in spring mvc or spring boot
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Slf4j | |
@Component | |
@Profile("exportDDL") | |
@org.springframework.context.annotation.Configuration | |
class HibernateDDLFlywayMigration { | |
@Bean ExportDDLExecutor exportDDLExecutor(Environment environment, Flyway flyway, EntityManagerFactory factory){ | |
return new ExportDDLExecutor(environment, flyway, factory) | |
} | |
static class ExportDDLExecutor { | |
ExportDDLExecutor(Environment environment, Flyway flyway, EntityManagerFactory factory) throws Exception { | |
if (factory.unwrap(SessionFactoryImpl.class) == null) { | |
throw new NullPointerException("factory is not a hibernate factory"); | |
} | |
SessionFactoryImpl hibernateFactory = factory.unwrap(SessionFactoryImpl.class); | |
Dialect dialect = hibernateFactory.dialect | |
Configuration config = hibernateFactory.serviceRegistry.@configuration | |
DatabaseMetadata meta = new DatabaseMetadata(flyway.dataSource.getConnection(), dialect, config); | |
List<SchemaUpdateScript> schemaUpdates = config.generateSchemaUpdateScriptList(dialect, meta) | |
MigrationInfo last = null; | |
if (flyway.info().all() && flyway.info().all().size() > 0) { | |
last = flyway.info().all().last() | |
} | |
int nextIndex = last ? Integer.parseInt(last.version.toString()) + 1 : 1 | |
if (!schemaUpdates) { | |
log.info("no schema updates detected") | |
} | |
for (SchemaUpdateScript update : schemaUpdates) { | |
if (last && last.script && (update.script == last.script)) { | |
continue | |
} | |
String migrationFile = "src/main/resources/db/migration/V${nextIndex}__${generateDescription(update.script)}.sql" | |
log.info("creating migration @${migrationFile} \n" + update.script) | |
new File(migrationFile).write(update.script + ";") | |
println update.script | |
++nextIndex | |
} | |
if (environment.acceptsProfiles("applyDDL")) { | |
log.info("applying schema migrations where applicable") | |
flyway.migrate() | |
} | |
} | |
static String generateDescription(String sql) { | |
if (sql.startsWith("SELECT")) { | |
return "DML"; | |
} else { | |
return "DDL"; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment