feat(多公司): V144 摘掉 users.company_id 的默认值,并把「已应用迁移不许原地改」做成护栏
V143 已于 2026-10-04 10:48:54 应用到生产库(校验和 1539570901),而 spring.flyway.validate-on-migrate=true 是硬编码 —— 想摘 DEFAULT 就不能原地改 V143, 否则下一次启动校验失败、两台 java 都起不来。所以按前向修复写成 V144,并让 CompanyMigrationV144Test 按 Flyway 的 CRC32 复算 V142/V143 与生产存量校验和比对, 把这件事从口头纪律变成 mvn test 阶段能咬红的护栏。 取舍:宁可让绕过 createUser 的写入撞 MySQL 1364 炸在日志里,也不要被静默塞进 厦门米椿花(users 全仓只有 1 条 INSERT,且它恒显式赋值,故不会新增失败面)。 - V144:ALTER TABLE users MODIFY COLUMN company_id bigint NOT NULL(不带 DEFAULT), 头注释含模板六项 + 验证 SQL(期望 Default = NULL)+ 人工回滚步骤 - CompanyMigrationV144Test 8 例,变异自证 7/7 被咬死(含「原地改 V143」那条) - CompanyMigrationV143Test 删掉「V143 必须是当前最大版本」——V144 落盘后它是假前提, 号段连续性仍由 MigrationInventoryTest 把守 - migration-inventory.md:文件数 143、范围 V1..V144、取号起点 V145、新增存量校验和表
This commit is contained in:
@@ -0,0 +1,286 @@
|
||||
package com.nanri.aiimage.config;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.StringReader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Stream;
|
||||
import java.util.zip.CRC32;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* V144(摘掉 users.company_id 的列默认值)与「已应用迁移字节封死」契约。
|
||||
* 设计:crawler-plugin/docs/ops/company-multi-tenant-design-2026-10-04.md §6.3 / §8.2。
|
||||
*
|
||||
* <p>背景:V143 出厂时带 {@code NOT NULL DEFAULT 1}(为混合版本窗口的旧 jar 兜底),
|
||||
* 2026-10-04 10:48:54 已被应用到生产库。定案是「归属只由回填与 createUser 显式决定,
|
||||
* 宁可撞 MySQL 1364 也不要静默归错公司」,所以 DEFAULT 必须摘——但**不能原地改 V143**:
|
||||
* Flyway 的 {@code validate-on-migrate} 是硬编码 true,改动已应用迁移的字节会让下一次
|
||||
* 重启在启动期报校验和不匹配,两台都起不来。摘除只能写成 V144 前向修复。</p>
|
||||
*
|
||||
* <p>与 {@link CompanyMigrationV143Test} 同口径:断言打在剥掉注释后的可执行 SQL 上,
|
||||
* 本仓无 H2 / testcontainers,迁移不能真跑,所以文件审计是唯一能守住的层。</p>
|
||||
*/
|
||||
class CompanyMigrationV144Test {
|
||||
|
||||
private static final Path ROOT = Path.of(System.getProperty("user.dir"));
|
||||
private static final Path DB_DIR = ROOT.resolve("src/main/resources/db");
|
||||
private static final Pattern VERSION_FILE = Pattern.compile("^V(\\d+)(?:_(\\d+))?__.*\\.sql$");
|
||||
|
||||
/**
|
||||
* 生产库 flyway_schema_history 的存量校验和(2026-10-04 11:0x 只读实查,主机A 业务库)。
|
||||
* 这两个号已经被应用,字节就此封死;改一个空格都会让下次重启启动期校验失败。
|
||||
*/
|
||||
private record Applied(String fileName, int prodChecksum) {
|
||||
}
|
||||
|
||||
private static final List<Applied> APPLIED_IN_PROD = List.of(
|
||||
new Applied("V142__web_config_sha256.sql", 1152261840),
|
||||
new Applied("V143__company_and_users_company_id.sql", 1539570901));
|
||||
|
||||
// ---------------------------------------------------------------- 取文件
|
||||
|
||||
private static List<Path> versionFiles() throws IOException {
|
||||
try (Stream<Path> s = Files.list(DB_DIR)) {
|
||||
return s.filter(p -> VERSION_FILE.matcher(p.getFileName().toString()).matches())
|
||||
.sorted()
|
||||
.toList();
|
||||
}
|
||||
}
|
||||
|
||||
private static int versionOf(Path p) {
|
||||
Matcher m = VERSION_FILE.matcher(p.getFileName().toString());
|
||||
return m.matches() ? Integer.parseInt(m.group(1)) : -1;
|
||||
}
|
||||
|
||||
private static Path migration() throws IOException {
|
||||
List<Path> hits = versionFiles().stream()
|
||||
.filter(p -> p.getFileName().toString().startsWith("V144__"))
|
||||
.toList();
|
||||
assertFalse(hits.isEmpty(), "缺少 V144__*.sql:摘 DEFAULT 的前向修复还没落盘");
|
||||
assertEquals(1, hits.size(), "V144 只允许一个迁移文件(撞号会让 Flyway 启动失败)");
|
||||
return hits.get(0);
|
||||
}
|
||||
|
||||
private static Path fileNamed(String fileName) {
|
||||
return DB_DIR.resolve(fileName);
|
||||
}
|
||||
|
||||
private static String raw(Path file) throws IOException {
|
||||
return Files.readString(file, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private static String rawMigration() throws IOException {
|
||||
return raw(migration());
|
||||
}
|
||||
|
||||
private static String statements() throws IOException {
|
||||
return normalize(stripComments(rawMigration()));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ SQL 预处理
|
||||
|
||||
/** 去掉 -- 行注释与块注释,保留单引号字符串字面量(避免把字面量里的 -- 当注释吃掉)。 */
|
||||
private static String stripComments(String sql) {
|
||||
StringBuilder out = new StringBuilder(sql.length());
|
||||
int i = 0;
|
||||
while (i < sql.length()) {
|
||||
char c = sql.charAt(i);
|
||||
if (c == '\'') {
|
||||
int end = i + 1;
|
||||
while (end < sql.length()) {
|
||||
if (sql.charAt(end) == '\'') {
|
||||
if (end + 1 < sql.length() && sql.charAt(end + 1) == '\'') {
|
||||
end += 2;
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
end++;
|
||||
}
|
||||
out.append(sql, i, Math.min(end + 1, sql.length()));
|
||||
i = end + 1;
|
||||
continue;
|
||||
}
|
||||
if (c == '-' && i + 1 < sql.length() && sql.charAt(i + 1) == '-') {
|
||||
while (i < sql.length() && sql.charAt(i) != '\n') {
|
||||
i++;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (c == '/' && i + 1 < sql.length() && sql.charAt(i + 1) == '*') {
|
||||
int end = sql.indexOf("*/", i + 2);
|
||||
i = end < 0 ? sql.length() : end + 2;
|
||||
continue;
|
||||
}
|
||||
out.append(c);
|
||||
i++;
|
||||
}
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
private static String normalize(String sql) {
|
||||
return sql.replaceAll("\\s+", " ").trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* Flyway 的校验和:CRC32 逐 {@code BufferedReader.readLine()} 的 UTF-8 字节累加,
|
||||
* 行尾不入 CRC(所以 CRLF 树与 LF 树算出同一个值)。用生产库 142/143 的存量值反证过。
|
||||
*/
|
||||
private static int flywayChecksum(String content) throws IOException {
|
||||
CRC32 crc = new CRC32();
|
||||
try (BufferedReader reader = new BufferedReader(new StringReader(content))) {
|
||||
String line;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
crc.update(line.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
}
|
||||
return (int) crc.getValue();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 用例
|
||||
|
||||
/**
|
||||
* 破坏点:原地改一个已经应用到生产库的迁移。V143 在 10:48 已落库,本次差点把它的闸门句
|
||||
* 就地改成不带 DEFAULT——那样 jar 里的字节与 flyway_schema_history.checksum 不等,
|
||||
* 而 {@code spring.flyway.validate-on-migrate=true} 是硬编码 ⇒ 下一次重启启动期直接失败,
|
||||
* 两台 java 都起不来。这条用例把"已应用"这件事变成代码能拦的东西。
|
||||
*/
|
||||
@Test
|
||||
void appliedMigrationBytesAreFrozenAgainstProdChecksum() throws IOException {
|
||||
for (Applied applied : APPLIED_IN_PROD) {
|
||||
Path file = fileNamed(applied.fileName());
|
||||
assertTrue(Files.isRegularFile(file), "已应用迁移应仍在扫描路径内:" + applied.fileName());
|
||||
int computed = flywayChecksum(raw(file));
|
||||
assertEquals(applied.prodChecksum(), computed,
|
||||
applied.fileName() + " 已经应用到生产库(校验和钉在 flyway_schema_history),"
|
||||
+ "原地改它的字节会让下次启动 Flyway 校验失败、两台都起不来。"
|
||||
+ "要改口径就写下一条迁移(V144 就是这么来的)。");
|
||||
}
|
||||
}
|
||||
|
||||
/** 破坏点:取号取到已应用的 143(原地改)或取到退役洞 132/133,Flyway 启动期撞号或报未应用。 */
|
||||
@Test
|
||||
void migrationIsVersionedOneFourFour() throws IOException {
|
||||
Path file = migration();
|
||||
assertEquals(144, versionOf(file), "摘 DEFAULT 必须是 V144(V143 之后的下一号,不能原地改 V143)");
|
||||
assertTrue(file.getFileName().toString().matches("^V144__[A-Za-z0-9_.-]+$"),
|
||||
"命名应 V144__<snake 描述>.sql: " + file.getFileName());
|
||||
int maxOnDisk = versionFiles().stream().mapToInt(CompanyMigrationV144Test::versionOf).max().orElse(0);
|
||||
assertEquals(144, maxOnDisk, "V144 应是当前最大版本");
|
||||
}
|
||||
|
||||
/**
|
||||
* 破坏点:V144 没把 DEFAULT 摘干净(写成 ADD COLUMN 或又补回 DEFAULT 1)。
|
||||
* 留着默认值的后果不是"多一个 1",而是任何绕过 createUser 的写入被静默塞进厦门米椿花——
|
||||
* 第二家公司开通后这就是归属失真,且一声不响。
|
||||
*/
|
||||
@Test
|
||||
void v144DropsTheColumnDefault() throws IOException {
|
||||
String sql = statements();
|
||||
Matcher gate = Pattern.compile("ALTER TABLE `users`\\s+MODIFY COLUMN `company_id`[^;]*;").matcher(sql);
|
||||
assertTrue(gate.find(), "应有 MODIFY COLUMN company_id 的语句(未匹配到,可能写法改了)");
|
||||
String clause = gate.group();
|
||||
assertTrue(clause.toUpperCase().contains("NOT NULL"), "MODIFY 应保持 NOT NULL,否则回填漏行不再被闸门拦下");
|
||||
assertFalse(clause.toUpperCase().contains("DEFAULT"),
|
||||
"MODIFY 后不得再出现 DEFAULT(本迁移的唯一目的就是摘掉它): " + clause);
|
||||
assertTrue(rawMigration().contains("1364"),
|
||||
"头注释应写清「宁可撞 MySQL 1364 也不静默归错公司」的取舍,否则后人会把 DEFAULT 当漏配加回来");
|
||||
assertTrue(rawMigration().contains("V143"), "头注释应点名 DEFAULT 来自 V143,说明这是前向修复而非补漏");
|
||||
}
|
||||
|
||||
/**
|
||||
* 破坏点:顺手把 users 改回可空、或删列、或动了别的表。
|
||||
* 一期定案是业务表零 DDL + company_id NOT NULL;V144 只该改这一列的默认值属性。
|
||||
*/
|
||||
@Test
|
||||
void v144TouchesOnlyUsersCompanyIdAndIsRerunnable() throws IOException {
|
||||
String sql = statements();
|
||||
|
||||
List<String> altered = new ArrayList<>();
|
||||
Matcher alter = Pattern.compile("ALTER TABLE `([A-Za-z0-9_]+)`").matcher(sql);
|
||||
while (alter.find()) {
|
||||
altered.add(alter.group(1));
|
||||
}
|
||||
assertFalse(altered.isEmpty(), "应有 ALTER TABLE(否则上一条断言是被注释喂绿的)");
|
||||
assertEquals(List.of("users"), altered.stream().distinct().toList(),
|
||||
"V144 只允许改 users,实际改到了 " + altered);
|
||||
|
||||
assertFalse(sql.contains("CREATE TABLE"), "V144 不该建新表");
|
||||
assertFalse(Pattern.compile("DROP\\s+(TABLE|COLUMN|INDEX)").matcher(sql).find(),
|
||||
"V144 是前向修复,不是回滚:不得出现 DROP TABLE/COLUMN/INDEX");
|
||||
assertFalse(sql.contains("ADD COLUMN"),
|
||||
"company_id 已由 V143 建好,这里再 ADD COLUMN 重跑必报 1060");
|
||||
}
|
||||
|
||||
/** 破坏点:头注释缺项 → 上线评审拿不到锁表风险与回滚口径,也看不出这笔与 V143 的关系。 */
|
||||
@Test
|
||||
void v144HeaderCarriesTemplateFieldsAndWhyItExists() throws IOException {
|
||||
String raw = rawMigration();
|
||||
assertTrue(raw.contains("V144"), "头注释应标明迁移版本 V144");
|
||||
for (int i = 1; i <= 6; i++) {
|
||||
assertTrue(raw.contains(i + ". "), "头注释应含模板第 " + i + " 项必填");
|
||||
}
|
||||
for (String field : List.of("变更目的", "影响表与数据量", "锁表风险", "验证 SQL", "回滚步骤", "上线窗口")) {
|
||||
assertTrue(raw.contains(field), "头注释应含必填项:" + field);
|
||||
}
|
||||
assertTrue(raw.contains("已应用"), "头注释应说明 V143 已被应用、因此只能前向修复");
|
||||
assertTrue(raw.contains("校验和") || raw.contains("checksum"),
|
||||
"头注释应说明为什么不能原地改 V143(Flyway 校验和)");
|
||||
}
|
||||
|
||||
/**
|
||||
* 破坏点:没留验证 SQL。这笔迁移的成败只体现在列属性上——启动日志里"Successfully applied"
|
||||
* 与"DEFAULT 摘干净"是两件事,只能靠 SHOW COLUMNS 的 Default 列复核。
|
||||
*/
|
||||
@Test
|
||||
void v144ShipsPostDeployVerificationSql() throws IOException {
|
||||
String raw = rawMigration();
|
||||
assertTrue(raw.contains("验证 SQL"), "头注释应含「验证 SQL」段(模板第 4 项)");
|
||||
assertTrue(raw.contains("SHOW COLUMNS FROM `users` LIKE 'company_id'")
|
||||
|| raw.contains("SHOW COLUMNS FROM users LIKE 'company_id'"),
|
||||
"验证 SQL 应核对 company_id 的 Null / Default");
|
||||
assertTrue(raw.contains("Default = NULL"),
|
||||
"验证 SQL 应把期望写成 Default = NULL,否则验收的人无从判断摘没摘");
|
||||
}
|
||||
|
||||
/**
|
||||
* 破坏点:哨兵被当成历史包袱删掉。V144 上线后 DEFAULT 本应不存在,
|
||||
* 但库里仍可能有(半套发布、老 dump 重建、手工 SET DEFAULT)——那是 §6.3 唯一的自动出口。
|
||||
*/
|
||||
@Test
|
||||
void defaultSentinelStillShipsAndStaysWired() throws IOException {
|
||||
Path guard = ROOT.resolve("src/main/java/com/nanri/aiimage/modules/company/service/CompanyDefaultGuard.java");
|
||||
assertTrue(Files.isRegularFile(guard), "启动期 DEFAULT 哨兵应存在:" + guard);
|
||||
String text = raw(guard);
|
||||
assertTrue(text.contains("COMPANY_DEFAULT_STILL_PRESENT"),
|
||||
"哨兵标记串必须保持 ASCII 原样(巡检脚本按它在 docker logs 里 grep)");
|
||||
assertTrue(text.contains("COLUMN_DEFAULT") || text.contains("information_schema"),
|
||||
"哨兵应真的读列元数据,而不是靠猜");
|
||||
assertTrue(rawMigration().contains("COMPANY_DEFAULT_STILL_PRESENT"),
|
||||
"V144 头注释应点名哨兵签名,上线后才能把「响没响」当验收项");
|
||||
}
|
||||
|
||||
/** 破坏点:盘点文档没跟着 V144 改,下一个人按"取号起点"取号就撞号。 */
|
||||
@Test
|
||||
void inventoryDocTracksV144() throws IOException {
|
||||
Path doc = ROOT.resolve("docs/migration-inventory.md");
|
||||
assertTrue(Files.isRegularFile(doc), "盘点文档应存在");
|
||||
String text = Files.readString(doc, StandardCharsets.UTF_8);
|
||||
assertTrue(text.contains(migration().getFileName().toString()),
|
||||
"盘点文档应记录 V144 文件名 " + migration().getFileName());
|
||||
assertTrue(text.contains("1539570901"),
|
||||
"盘点文档应记下 V143 的生产存量校验和,作为「不许原地改」的证据");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user