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; /** * V152(摘掉 columns 与 biz_shop_key 的 company_id 默认值)的文件审计。 * 需求:2026-10-06「优先处理 columns 等三列 DEFAULT 问题」;合并口径见 V150 头注释第 6 段 * 与 docs/migration-inventory.md(两条都是纯元数据、前提各自独立,要求合并成一版发出)。 * *

为什么必须单独有一支:本仓 pom 无 H2、无 testcontainers,迁移跑不起来,文件审计是唯一 * 能守住的那层(与 {@link CompanyMigrationV144Test}、{@link ShopKeyMigrationV150Test} 同口径)。 * V152 的三条关键决定全都"错了不报错":

*
    *
  1. 摘除范围的边界:只许 columns 与 biz_shop_key。biz_dedupe_total_data 的写侧修复 * (insertBatchIgnore 显式落 company_id)尚未出厂,先摘=每次导入 1364; * biz_product_category / biz_invalid_asin_data 的 DEFAULT 1 是承重约束 * (共享表写侧有意不落该列、靠它满足 NOT NULL),先摘=每次新建 1364——三个名字 * 都不许出现在可执行段;
  2. *
  3. 写法只许 ALTER COLUMN ... DROP DEFAULT(纯元数据、不重建表);写成 MODIFY 会重建表 * 并按"当时的列默认值"物化历史行——V144/V150 头注释都点名过这条禁写;
  4. *
  5. 前提是"两台已跑 V149/V150 起的 jar":本类把 149/150/151 的生产校验和在本机复算比对 * (10-07 只读实查:success=1、installed_on=2026-10-06 17:32:29、checksum 见 * {@link #appliedV149V150V151BytesAreFrozenAgainstProdChecksum})。谁动了已应用迁移的 * 字节,会在部署前的测试里先红,而不是在下次重启的启动期把两台 java 一起撂倒。
  6. *
* *

{@code stripComments}/{@code normalize}/{@code flywayChecksum} 逐字沿用 * {@link CompanyMigrationV144Test} 那一份实现:注释里的 {@code --} 与字符串字面量里的 * {@code --} 是两件事,另写一版简化实现会让断言打在残缺 SQL 上。

*/ class CompanyDefaultDropV152Test { private static final Path ROOT = Path.of(System.getProperty("user.dir")); private static final Path DB_DIR = ROOT.resolve("src/main/resources/db"); /** 生产 flyway_schema_history 只读取证(2026-10-07,主机A):这三条已应用,字节就此封死。 */ private record Applied(String fileName, int prodChecksum) { } private static final List APPLIED_IN_PROD = List.of( new Applied("V149__permission_menu_company_tree.sql", 593432281), new Applied("V150__shop_key_company_scope.sql", 2113095084), new Applied("V151__rule_tables_shared_across_companies.sql", 613473408)); // ---------------------------------------------------------------- 取文件 private static List versionFiles() throws IOException { try (Stream s = Files.list(DB_DIR)) { return s.filter(p -> p.getFileName().toString().matches("^V\\d+(?:_\\d+)?__.*\\.sql$")) .sorted() .toList(); } } private static Path migration() throws IOException { List hits = versionFiles().stream() .filter(p -> p.getFileName().toString().startsWith("V152__")) .toList(); assertEquals(1, hits.size(), "V152 必须恰好一个迁移文件,实际 " + hits.size() + " 个(0 个=摘 DEFAULT 还没落盘;2 个=撞号,Flyway 启动即失败)"); return hits.get(0); } 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 预处理 // 与 CompanyMigrationV144Test / ShopKeyMigrationV150Test 逐字同实现,理由见类注释。 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 工作树算出同一个值)。 */ 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(); } private static int count(String haystack, String needle) { int n = 0, i = haystack.indexOf(needle); while (i >= 0) { n++; i = haystack.indexOf(needle, i + needle.length()); } return n; } // ------------------------------------------------------------------ 用例 /** 破坏点:取到已应用的号(原地改=两台起不来),或取到退役洞 132/133/148(Flyway 报未应用)。 */ @Test void migrationIsVersionedOneFiveTwo() throws IOException { Path file = migration(); Matcher m = Pattern.compile("^V(\\d+)(?:_\\d+)?__").matcher(file.getFileName().toString()); assertTrue(m.find(), "文件名应能抽出整数版本:" + file.getFileName()); assertEquals(152, Integer.parseInt(m.group(1)), "本迁移必须是 V152(V151 之后的下一号)"); assertTrue(file.getFileName().toString().matches("^V152__[A-Za-z0-9_.-]+\\.sql$"), "命名应 V152__.sql:" + file.getFileName()); } /** * 可执行段必须恰好是两条裸的 ALTER COLUMN ... DROP DEFAULT,一张表一条。 * *

破坏点 ①:加了 information_schema 守卫却又留在"无操作"事实之外——守卫是留给 * "重复执行会报错"的动作(V142/V143 的 ADD COLUMN/INDEX);DROP DEFAULT 对已无默认值的列 * 重复执行不发生任何改变(scratch MySQL 8.4.9 重放两遍证实),裸写才是与 V144 同口径。 * 破坏点 ②:把列名写错(companyId/company_id 手滑)或把 DROP DEFAULT 写成 MODIFY—— * 后者会重建表并把历史行按"当时的默认值"物化(本迁移要防的那件事本身)。

*/ @Test void executableSectionIsExactlyTwoBareDropDefaults() throws IOException { String sql = statements(); assertTrue(sql.contains("ALTER TABLE `columns` ALTER COLUMN company_id DROP DEFAULT;"), "应有 columns 的摘默认语句(逐字):" + sql); assertTrue(sql.contains("ALTER TABLE `biz_shop_key` ALTER COLUMN company_id DROP DEFAULT;"), "应有 biz_shop_key 的摘默认语句(逐字):" + sql); List altered = new ArrayList<>(); Matcher alter = Pattern.compile("ALTER TABLE `([A-Za-z0-9_]+)`").matcher(sql); while (alter.find()) { altered.add(alter.group(1)); } assertEquals(List.of("columns", "biz_shop_key"), altered, "只允许改这两张表、各恰一次(多了=范围越界;少了=漏摘);实际 " + altered); assertFalse(sql.toUpperCase().contains("PREPARE"), "本笔不需要条件 DDL 守卫(裸写口径,理由见头注释)"); assertFalse(sql.contains("information_schema"), "可执行段不该查元数据表(验证 SQL 只在注释里给人工跑)"); assertFalse(sql.toUpperCase().contains("MODIFY"), "禁 MODIFY COLUMN:重建表会按当时的默认值物化历史行"); assertFalse(Pattern.compile("DROP\\s+(COLUMN|TABLE|INDEX)", Pattern.CASE_INSENSITIVE).matcher(sql).find(), "本笔不是回滚也不是删列:不得出现 DROP COLUMN/TABLE/INDEX"); assertFalse(sql.toUpperCase().contains("ADD COLUMN"), "列由 V149/V150 建好,这里再 ADD COLUMN 重跑必报 1060"); assertFalse(sql.toUpperCase().contains("CREATE TABLE"), "V152 不建表"); assertFalse(Pattern.compile("\\b(UPDATE|INSERT|DELETE|REPLACE)\\b", Pattern.CASE_INSENSITIVE).matcher(sql).find(), "摘默认值是纯元数据:一条 DML 都不该有(历史行不靠回填)"); assertFalse(sql.toUpperCase().contains("ADD INDEX") || sql.toUpperCase().contains("ADD KEY"), "本版本不加索引"); } /** * 漏口防线:可执行段不得出现三张"碰不得"的表。 * dedupe 的写侧修复未出厂(先摘=每次导入 1364);两张共享表的 DEFAULT 是承重约束 * (先摘=每次新建 1364,next 版走 DROP COLUMN)。名字出现在注释里没问题—— * 断言只打在可执行段上。 */ @Test void forbiddenTablesStayOutOfTheExecutableSection() throws IOException { String sql = statements(); for (String table : List.of("biz_dedupe_total_data", "biz_product_category", "biz_invalid_asin_data")) { assertFalse(sql.contains(table), table + " 不在本版的摘除范围(理由见头注释第 6 段),不许出现在可执行段"); } assertFalse(sql.contains("`users`"), "users 的 DEFAULT 已由 V144 摘掉,本文件不该再出现它"); } /** 破坏点:头注释没把"为什么是这两张、为什么不是那三张"与前提证据写全 → 下一笔迁移会重演误摘。 */ @Test void headerCarriesPremiseEvidenceAndMergeBasis() throws IOException { String raw = rawMigration(); 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("V150"), "头注释应点名合并依据来自 V150 第 6 段"); assertTrue(raw.contains("migration-inventory"), "头注释应点名盘点文档里的同款待办"); assertTrue(raw.contains("1364"), "头注释应写清「宁可撞 1364 也不静默归错公司」的取舍"); assertTrue(raw.contains("2026-10-06 17:32"), "头注释应带上「V149/V150 已应用」的实查时刻"); assertTrue(raw.contains("COMPANY_DEFAULT_STILL_PRESENT"), "头注释应点名哨兵签名,上线后才能把「这两张表还响不响」当验收项"); assertTrue(raw.contains("biz_dedupe_total_data"), "头注释应写明 dedupe 为什么不在本版(写侧修复未出厂,先摘=每次导入 1364)"); assertTrue(raw.contains("biz_product_category") && raw.contains("biz_invalid_asin_data"), "头注释应写明两张共享表为什么永远不许加进来(DEFAULT 承重)"); assertTrue(raw.contains("无操作"), "头注释应写清可重跑的依据(重复执行无操作,非守卫式)"); } /** * V152 的前提是"V149/V150 的写侧已在两台生产跑";而这又要求它们的字节没被人动过。 * 破坏点:有人"顺手"改进已应用迁移的一个空格、一句注释——那样 jar 里的字节与 * flyway_schema_history.checksum 不等,下一批部署重启时两台都报校验失败直接起不来。 */ @Test void appliedV149V150V151BytesAreFrozenAgainstProdChecksum() throws IOException { for (Applied applied : APPLIED_IN_PROD) { Path file = DB_DIR.resolve(applied.fileName()); assertTrue(Files.isRegularFile(file), "已应用迁移应仍在扫描路径内:" + applied.fileName()); int computed = flywayChecksum(raw(file)); assertEquals(applied.prodChecksum(), computed, applied.fileName() + " 已经应用到生产库(2026-10-06 17:32),原地改它的字节会让" + "下次启动 Flyway 校验失败、两台都起不来。要改口径就写下一条迁移。"); } } /** * 摘掉 DEFAULT 之后哨兵对这两张表本应静默,但清单要留着——它是"被装回"(dump 重建、 * 手滑 SET DEFAULT)时的唯一自动出口(V144 摘 users 时同样没把 users 从清单里删)。 * 破坏点:有人把"已摘除"读成"可以清理",把两表从 WATCHED_TABLES 或探针 SQL 里删掉。 */ @Test void sentinelStillListsBothTablesAfterRemoval() 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 原样(巡检按它 grep)"); assertTrue(text.contains("\"columns\"") && text.contains("\"biz_shop_key\""), "WATCHED_TABLES 应保留这两张表(摘除后静默;被装回时要能再喊)"); assertTrue(text.contains("'columns'") && text.contains("'biz_shop_key'"), "探针 SQL 的 IN 列表应同时保留这两张表(清单与 SQL 双向钉同源)"); } /** 破坏点:盘点文档没跟着 V152 改 ⇒ 下一个人按"取号起点"取号就撞号,或按"最新版本"漏掉本文件。 */ /** 自检:本用例集扫的是真文件,且 normalize 后仍能命中关键串(0 命中的断言是恒绿的)。 */ @Test void scannedSignaturesAreActuallyPresent() throws IOException { String sql = statements(); assertTrue(sql.length() > 100, "剥注释后的 SQL 太短,说明预处理把内容吃掉了:" + sql.length()); assertTrue(count(sql, "ALTER COLUMN") == 2, "关键签名命中数应为 2(恰好两条),实际 " + count(sql, "ALTER COLUMN") + ":预处理或文件路径坏了,本类的断言全部不可信"); } }