feat(db): 新增 Flyway 数据库迁移基线
建立 V1-V5 迁移与迁移布局校验,为实例初始化提供可追踪的结构基线。
This commit is contained in:
@@ -0,0 +1,175 @@
|
||||
package com.qlinker.db;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* 离线迁移文件结构检查。不连接任何数据库,只校验脚本文件本身。
|
||||
* 通过本检查不能推断真实 MySQL 上的迁移执行结果。
|
||||
*/
|
||||
class FlywayMigrationLayoutTests {
|
||||
|
||||
private static final Pattern FILE_NAME = Pattern.compile("^V(\\d+)__([a-z0-9_]+)\\.sql$");
|
||||
|
||||
private static final List<String> REQUIRED_TABLES = List.of(
|
||||
"system_instance", "system_setting", "secret_reference",
|
||||
"user_account", "role", "permission", "user_role", "role_permission", "user_session",
|
||||
"napcat_binding", "napcat_capability",
|
||||
"raw_event", "event_dedup", "event_processing_log",
|
||||
"message", "message_segment");
|
||||
|
||||
private List<Path> migrations() {
|
||||
Path dir = migrationDir();
|
||||
try (var stream = Files.list(dir)) {
|
||||
return stream.filter(p -> p.getFileName().toString().endsWith(".sql"))
|
||||
.sorted(Comparator.comparing(p -> p.getFileName().toString()))
|
||||
.toList();
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private Path migrationDir() {
|
||||
String base = System.getProperty("user.dir");
|
||||
Path dir = Path.of(base, "src", "main", "resources", "db", "migration");
|
||||
assertTrue(Files.isDirectory(dir), "缺少迁移目录:" + dir);
|
||||
return dir;
|
||||
}
|
||||
|
||||
private String read(Path p) {
|
||||
try {
|
||||
return Files.readString(p, StandardCharsets.UTF_8);
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void fileNamesFollowFlywayConventionAndVersionsStrictlyIncreaseWithoutDuplicates() {
|
||||
List<Path> files = migrations();
|
||||
assertFalse(files.isEmpty(), "迁移目录为空");
|
||||
|
||||
List<Integer> versions = new ArrayList<>();
|
||||
Set<Integer> seen = new HashSet<>();
|
||||
for (Path p : files) {
|
||||
Matcher m = FILE_NAME.matcher(p.getFileName().toString());
|
||||
assertTrue(m.matches(), "文件名不符合 V<version>__<description>.sql:" + p.getFileName());
|
||||
int version = Integer.parseInt(m.group(1));
|
||||
assertTrue(seen.add(version), "重复的迁移版本:" + version + " -> " + p.getFileName());
|
||||
versions.add(version);
|
||||
}
|
||||
for (int i = 0; i < versions.size(); i++) {
|
||||
assertEquals(i + 1, versions.get(i), "迁移版本必须从 1 开始严格递增,实际序列:" + versions);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void requiredCoreTablesAreCreatedExactlyOnce() {
|
||||
List<Path> files = migrations();
|
||||
for (String table : REQUIRED_TABLES) {
|
||||
int count = 0;
|
||||
for (Path p : files) {
|
||||
count += occurrences(read(p), "CREATE TABLE `" + table + "` (");
|
||||
}
|
||||
assertEquals(1, count, "表 " + table + " 必须被创建且只创建一次,实际出现 " + count + " 次");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void unknownEventAndSegmentStructuresAreRetainedVerbatim() {
|
||||
String rawEvent = read(findByTable("raw_event"));
|
||||
String segment = read(findByTable("message_segment"));
|
||||
|
||||
assertTrue(rawEvent.contains("`raw_payload` LONGTEXT"),
|
||||
"raw_event.raw_payload 必须使用可逐字保留原始结构的文本列,不得用会规范化内容的 JSON 列");
|
||||
assertTrue(rawEvent.contains("`event_type`") && rawEvent.contains("`parse_status`"),
|
||||
"raw_event 必须保留事件类型与解析状态,未知类型才可标记而非丢弃");
|
||||
assertTrue(rawEvent.contains("`payload_hash` BINARY(32)"), "raw_event 必须保留原始数据哈希");
|
||||
|
||||
assertTrue(segment.contains("`raw_segment` LONGTEXT"), "message_segment.raw_segment 必须逐字保留原始消息段");
|
||||
assertTrue(segment.contains("`segment_index`"), "message_segment 必须保留消息段顺序");
|
||||
assertTrue(segment.contains("`segment_status`"), "message_segment 必须能标记未知段状态");
|
||||
}
|
||||
|
||||
@Test
|
||||
void dedupKeepsSourceScopeAndConversationDeduplicationColumnsExist() {
|
||||
String dedup = read(findByTable("event_dedup"));
|
||||
assertTrue(dedup.contains("UNIQUE KEY `uk_event_dedup_binding_key` (`binding_id`, `dedup_key`)"),
|
||||
"去重必须有 UNIQUE(binding_id, dedup_key),否则重复事件会触发重复副作用");
|
||||
assertTrue(dedup.contains("`dedup_strategy`") && dedup.contains("`expires_at`"),
|
||||
"无稳定来源 ID 的去重策略必须有有效期与策略标识");
|
||||
assertTrue(dedup.contains("会话类型") && dedup.contains("会话 ID"),
|
||||
"dedup_key 必须显式记录「会话类型 + 会话 ID」要求(GC-022)");
|
||||
|
||||
String message = read(findByTable("message"));
|
||||
assertTrue(message.contains("`conversation_type`") && message.contains("`conversation_id`"),
|
||||
"message 必须同时具备会话类型判别与会话 ID");
|
||||
assertTrue(message.contains("(`conversation_type`, `conversation_id`, `message_time`)"),
|
||||
"必须提供会话类型 + 会话 ID + 时间的组合索引");
|
||||
assertFalse(message.contains("UNIQUE KEY `uk_message_source_message_id`"),
|
||||
"不得对 source_message_id 建立全局唯一约束");
|
||||
}
|
||||
|
||||
@Test
|
||||
void migrationsContainOnlyCreateTableStatementsAndNoRealAddresses() {
|
||||
for (Path p : migrations()) {
|
||||
String withoutComments = read(p).replaceAll("(?m)^\\s*--.*$", "");
|
||||
for (String raw : withoutComments.split(";")) {
|
||||
String stmt = raw.strip();
|
||||
if (stmt.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
String head = stmt.split("\\s+", 2)[0].toUpperCase();
|
||||
assertEquals("CREATE", head,
|
||||
p.getFileName() + ":本任务迁移只允许 CREATE TABLE,实际语句以 " + head + " 开头:"
|
||||
+ stmt.substring(0, Math.min(60, stmt.length())));
|
||||
}
|
||||
assertFalse(withoutComments.contains("192.168."), p.getFileName() + ":不得写入真实内网地址");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void allStatementsUseInnoDBAndUtf8mb4() {
|
||||
for (Path p : migrations()) {
|
||||
String sql = read(p);
|
||||
int tables = occurrences(sql, "CREATE TABLE ");
|
||||
int engine = occurrences(sql, "ENGINE = InnoDB");
|
||||
int charset = occurrences(sql, "DEFAULT CHARSET = utf8mb4");
|
||||
assertEquals(tables, engine, p.getFileName() + ":每张表必须显式声明 InnoDB");
|
||||
assertEquals(tables, charset, p.getFileName() + ":每张表必须显式声明 utf8mb4");
|
||||
}
|
||||
}
|
||||
|
||||
private Path findByTable(String table) {
|
||||
return migrations().stream()
|
||||
.filter(p -> read(p).contains("CREATE TABLE `" + table + "` ("))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new AssertionError("未找到创建表 " + table + " 的迁移文件"));
|
||||
}
|
||||
|
||||
private int occurrences(String text, String needle) {
|
||||
int count = 0;
|
||||
int idx = text.indexOf(needle);
|
||||
while (idx >= 0) {
|
||||
count++;
|
||||
idx = text.indexOf(needle, idx + needle.length());
|
||||
}
|
||||
return count;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user