fix(database): enforce Flyway migration governance
This commit is contained in:
@@ -0,0 +1,62 @@
|
||||
package me.iiv.agent.config;
|
||||
|
||||
import org.flywaydb.core.Flyway;
|
||||
import org.h2.jdbcx.JdbcDataSource;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.Statement;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
class FlywayMigrationTest {
|
||||
|
||||
@Test
|
||||
void emptyDatabaseMigratesThroughLatestVersion() throws Exception {
|
||||
JdbcDataSource dataSource = dataSource("empty");
|
||||
Flyway flyway = flyway(dataSource, false);
|
||||
|
||||
flyway.migrate();
|
||||
|
||||
assertEquals("2", flyway.info().current().getVersion().getVersion());
|
||||
assertEquals(255, passwordHashLength(dataSource));
|
||||
}
|
||||
|
||||
@Test
|
||||
void legacyV1DatabaseIsBaselinedThenUpgraded() throws Exception {
|
||||
JdbcDataSource dataSource = dataSource("legacy");
|
||||
try (Connection connection = dataSource.getConnection(); Statement statement = connection.createStatement()) {
|
||||
statement.execute("CREATE TABLE admin_user (id BIGINT AUTO_INCREMENT PRIMARY KEY, password_hash CHAR(64) NOT NULL)");
|
||||
}
|
||||
Flyway flyway = flyway(dataSource, true);
|
||||
|
||||
flyway.migrate();
|
||||
|
||||
assertEquals("2", flyway.info().current().getVersion().getVersion());
|
||||
assertEquals(255, passwordHashLength(dataSource));
|
||||
}
|
||||
|
||||
private static Flyway flyway(JdbcDataSource dataSource, boolean baseline) {
|
||||
return Flyway.configure().dataSource(dataSource).locations("classpath:db/migration")
|
||||
.baselineOnMigrate(baseline).baselineVersion("1").validateMigrationNaming(true)
|
||||
.cleanDisabled(true).load();
|
||||
}
|
||||
|
||||
private static JdbcDataSource dataSource(String name) {
|
||||
JdbcDataSource dataSource = new JdbcDataSource();
|
||||
dataSource.setURL("jdbc:h2:mem:flyway_" + name + ";MODE=MySQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1");
|
||||
dataSource.setUser("sa");
|
||||
return dataSource;
|
||||
}
|
||||
|
||||
private static int passwordHashLength(JdbcDataSource dataSource) throws Exception {
|
||||
try (Connection connection = dataSource.getConnection();
|
||||
Statement statement = connection.createStatement();
|
||||
ResultSet result = statement.executeQuery("SELECT CHARACTER_MAXIMUM_LENGTH FROM INFORMATION_SCHEMA.COLUMNS "
|
||||
+ "WHERE TABLE_NAME='admin_user' AND COLUMN_NAME='password_hash'")) {
|
||||
result.next();
|
||||
return result.getInt(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package me.iiv.agent.config;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.TreeMap;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class MigrationGovernanceTest {
|
||||
|
||||
private static final Path MIGRATIONS = Path.of("src/main/resources/db/migration");
|
||||
private static final Path ROLLBACKS = Path.of("sql/rollback");
|
||||
private static final Pattern NAME = Pattern.compile("V(\\d+)__[a-z0-9_]+\\.sql");
|
||||
|
||||
@Test
|
||||
void migrationsAreOrderedAndHaveRollbackPlans() throws Exception {
|
||||
assertTrue(Files.isDirectory(MIGRATIONS), "缺少 Flyway migration 目录");
|
||||
List<Path> files;
|
||||
try (var stream = Files.list(MIGRATIONS)) {
|
||||
files = stream.filter(path -> path.getFileName().toString().endsWith(".sql")).sorted().toList();
|
||||
}
|
||||
assertFalse(files.isEmpty(), "至少保留一个基线 migration");
|
||||
|
||||
Map<Integer, Path> versions = new TreeMap<>();
|
||||
for (Path file : files) {
|
||||
Matcher matcher = NAME.matcher(file.getFileName().toString());
|
||||
assertTrue(matcher.matches(), () -> "迁移文件名不合规: " + file.getFileName());
|
||||
int version = Integer.parseInt(matcher.group(1));
|
||||
assertFalse(versions.containsKey(version), () -> "迁移版本重复: V" + version);
|
||||
versions.put(version, file);
|
||||
String sql = Files.readString(file);
|
||||
assertFalse(Pattern.compile("(?im)^\\s*(USE|CREATE\\s+DATABASE)\\b").matcher(sql).find(),
|
||||
() -> "migration 只能操作当前 svc schema: " + file.getFileName());
|
||||
String rollback = file.getFileName().toString().replace(".sql", ".down.sql");
|
||||
assertTrue(Files.isRegularFile(ROLLBACKS.resolve(rollback)), () -> "缺少回滚方案: " + rollback);
|
||||
}
|
||||
List<Integer> expected = IntStream.rangeClosed(1, versions.size()).boxed().toList();
|
||||
assertEquals(expected, versions.keySet().stream().toList(), "迁移版本必须从 V1 连续递增");
|
||||
}
|
||||
|
||||
@Test
|
||||
void committedMigrationChecksumsMatchManifest() throws Exception {
|
||||
Path manifest = MIGRATIONS.resolve("checksums.sha256");
|
||||
assertTrue(Files.isRegularFile(manifest), "缺少 migration 校验和清单");
|
||||
Map<String, String> checksums = new TreeMap<>();
|
||||
for (String line : Files.readAllLines(manifest)) {
|
||||
if (line.isBlank() || line.startsWith("#")) continue;
|
||||
String[] parts = line.trim().split("\\s+", 2);
|
||||
assertEquals(2, parts.length, "校验和格式应为: sha256 文件名");
|
||||
checksums.put(parts[1], parts[0]);
|
||||
}
|
||||
Set<String> migrationNames;
|
||||
try (var stream = Files.list(MIGRATIONS)) {
|
||||
migrationNames = stream.map(path -> path.getFileName().toString())
|
||||
.filter(name -> name.endsWith(".sql")).collect(java.util.stream.Collectors.toSet());
|
||||
}
|
||||
assertEquals(migrationNames, checksums.keySet(), "校验和清单必须覆盖全部 migration");
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
for (Map.Entry<String, String> entry : checksums.entrySet()) {
|
||||
String actual = HexFormat.of().formatHex(digest.digest(Files.readAllBytes(MIGRATIONS.resolve(entry.getKey()))));
|
||||
assertEquals(entry.getValue(), actual, () -> "历史 migration 被修改: " + entry.getKey());
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user