
io.smilego.tenant.flyway.TenantFlywayMigration Maven / Gradle / Ivy
package io.smilego.tenant.flyway;
import io.smilego.tenant.event.TenantMigration;
import io.smilego.tenant.model.Tenant;
import io.smilego.tenant.persistence.TenantRepository;
import io.smilego.tenant.util.AESUtils;
import org.flywaydb.core.Flyway;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.event.EventListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jdbc.datasource.SingleConnectionDataSource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Collection;
public class TenantFlywayMigration {
Logger log = LoggerFactory.getLogger(this.getClass());
@Value("${multitenancy.security.encryption-key}")
private String encryptionKey;
@Value("${multitenancy.application.name}")
private String applicationName;
@Autowired
private TenantRepository tenantRepository;
@Autowired
private RedisTemplate redisTemplate;
private static final String MIGRATION_KEY = "MIGRATION_EXECUTED";
public void migrateTenant(Tenant tenant) {
String cacheKey = String.format("%s::%s::%s", MIGRATION_KEY, tenant.getTenantId(), applicationName);
Boolean isMigrationExecuted = redisTemplate.hasKey(cacheKey);
if (isMigrationExecuted != null && !isMigrationExecuted) {
redisTemplate.opsForValue().set(cacheKey, "true");
try (Connection connection = DriverManager.getConnection(tenant.getUrl().concat("_").concat(applicationName),
tenant.getDb(),
AESUtils.decrypt(encryptionKey, tenant.getPassword()))) {
String scriptLocation = "classpath:db/migration/tenant";
DataSource tenantDataSource = new SingleConnectionDataSource(connection, false);
Flyway flyway = Flyway.configure()
.locations(scriptLocation)
.baselineOnMigrate(Boolean.TRUE)
.dataSource(tenantDataSource)
.schemas("public")
.load();
flyway.migrate();
} catch (Exception e) {
log.error("Failed to run Flyway migrations for tenant " + tenant.getTenantId(), e.getMessage());
}
}
}
@EventListener(TenantMigration.class)
public void tenantMigrationListener(TenantMigration tenantMigration) {
Tenant tenant = tenantMigration.getSource();
this.migrateTenant(tenant);
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy