fix(多租户): V152 摘 columns/biz_shop_key 的 company_id 列默认值,去重库写侧显式带归属
- V152:两条裸 ALTER COLUMN DROP DEFAULT(纯元数据、可重跑)。依据 V150 §6「合并成一版」 与 migration-inventory 取号;前提=V149/150/151 已于 10-06 17:32:29 落库、写侧三条通道 (PermissionMenuService create/copyTreeFromTemplate、ShopKeyService)均显式落列。 - 去重库:DedupeTotalDataMapper/Entity/Service 的 INSERT 显式写 company_id,不再靠列 DEFAULT 1 兜底(第二家公司开通后静默归错)。biz_dedupe_total_data 的 DEFAULT 摘除排在 本批上线并验证写入之后,不在本版。 - CompanyDefaultDropV152Test 9 例(含 V149/150/151 已应用字节的 CRC 冻结)+ dedupe 两支测试 + rollback-V152 人工补丁(默认档可直接执行)+ 盘点文档同步(取号起点改 V153)。
This commit is contained in:
@@ -0,0 +1,337 @@
|
||||
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(两条都是纯元数据、前提各自独立,要求合并成一版发出)。
|
||||
*
|
||||
* <p>为什么必须单独有一支:本仓 pom 无 H2、无 testcontainers,迁移跑不起来,文件审计是唯一
|
||||
* 能守住的那层(与 {@link CompanyMigrationV144Test}、{@link ShopKeyMigrationV150Test} 同口径)。
|
||||
* V152 的三条关键决定全都"错了不报错":</p>
|
||||
* <ol>
|
||||
* <li>摘除范围的边界:只许 columns 与 biz_shop_key。biz_dedupe_total_data 的写侧修复
|
||||
* (insertBatchIgnore 显式落 company_id)尚未出厂,先摘=每次导入 1364;
|
||||
* biz_product_category / biz_invalid_asin_data 的 DEFAULT 1 是承重约束
|
||||
* (共享表写侧有意不落该列、靠它满足 NOT NULL),先摘=每次新建 1364——三个名字
|
||||
* 都不许出现在可执行段;</li>
|
||||
* <li>写法只许 ALTER COLUMN ... DROP DEFAULT(纯元数据、不重建表);写成 MODIFY 会重建表
|
||||
* 并按"当时的列默认值"物化历史行——V144/V150 头注释都点名过这条禁写;</li>
|
||||
* <li>前提是"两台已跑 V149/V150 起的 jar":本类把 149/150/151 的生产校验和在本机复算比对
|
||||
* (10-07 只读实查:success=1、installed_on=2026-10-06 17:32:29、checksum 见
|
||||
* {@link #appliedV149V150V151BytesAreFrozenAgainstProdChecksum})。谁动了已应用迁移的
|
||||
* 字节,会在部署前的测试里先红,而不是在下次重启的启动期把两台 java 一起撂倒。</li>
|
||||
* </ol>
|
||||
*
|
||||
* <p>{@code stripComments}/{@code normalize}/{@code flywayChecksum} 逐字沿用
|
||||
* {@link CompanyMigrationV144Test} 那一份实现:注释里的 {@code --} 与字符串字面量里的
|
||||
* {@code --} 是两件事,另写一版简化实现会让断言打在残缺 SQL 上。</p>
|
||||
*/
|
||||
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> 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<Path> versionFiles() throws IOException {
|
||||
try (Stream<Path> 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<Path> 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()));
|
||||
}
|
||||
|
||||
private static Path rollbackPatch() {
|
||||
return ROOT.resolve("docs/rollback-V152-columns-shop-key-default.sql");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ 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__<snake 描述>.sql:" + file.getFileName());
|
||||
}
|
||||
|
||||
/**
|
||||
* 可执行段必须恰好是两条裸的 ALTER COLUMN ... DROP DEFAULT,一张表一条。
|
||||
*
|
||||
* <p>破坏点 ①:加了 information_schema 守卫却又留在"无操作"事实之外——守卫是留给
|
||||
* "重复执行会报错"的动作(V142/V143 的 ADD COLUMN/INDEX);DROP DEFAULT 对已无默认值的列
|
||||
* 重复执行不发生任何改变(scratch MySQL 8.4.9 重放两遍证实),裸写才是与 V144 同口径。
|
||||
* 破坏点 ②:把列名写错(companyId/company_id 手滑)或把 DROP DEFAULT 写成 MODIFY——
|
||||
* 后者会重建表并把历史行按"当时的默认值"物化(本迁移要防的那件事本身)。</p>
|
||||
*/
|
||||
@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<String> 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 校验失败、两台都起不来。要改口径就写下一条迁移。");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 回滚补丁的默认档就是"两条 SET DEFAULT 1"——与 rollback-V150 的"空档"相反:
|
||||
* 本笔被动过的只有默认值属性,装回它既是完整回滚、又是纯元数据、可逆无损。
|
||||
* 破坏点:写成 MODIFY(重建表)或忘了删 flyway_schema_history 行(半套回滚,
|
||||
* 会让"重装 V152 时跳过执行"与"库里 DEFAULT 已被装回"长期互相矛盾)。
|
||||
*/
|
||||
@Test
|
||||
void rollbackPatchRestoresTheDefaultAndDeletesHistoryRow() throws IOException {
|
||||
Path doc = rollbackPatch();
|
||||
assertTrue(Files.isRegularFile(doc), "V152 的人工回滚补丁必须存在:" + doc);
|
||||
String whole = raw(doc);
|
||||
assertTrue(whole.contains("flyway_schema_history"), "回滚必须写明删 version='152' 的历史行");
|
||||
assertTrue(whole.contains("'152'"), "回滚补丁要点名本版本号,后来人才知道删的是哪一行");
|
||||
String executable = normalize(stripComments(whole));
|
||||
assertTrue(!executable.isEmpty(), "本笔回滚是可逆的元数据操作,默认档必须直接可执行(不学 V150 的空档)");
|
||||
assertEquals(2, count(executable, "SET DEFAULT 1"),
|
||||
"默认档应把两列的 DEFAULT 都装回去(各恰一次),实际可执行段:" + executable);
|
||||
assertTrue(executable.contains("ALTER TABLE `columns` ALTER COLUMN company_id SET DEFAULT 1;")
|
||||
&& executable.contains("ALTER TABLE `biz_shop_key` ALTER COLUMN company_id SET DEFAULT 1;"),
|
||||
"装回语句应逐字用 ALTER COLUMN ... SET DEFAULT 1:" + executable);
|
||||
assertFalse(executable.toUpperCase().contains("MODIFY"),
|
||||
"禁 MODIFY:重建表对这两张表的历史行归属没有意义且徒增风险");
|
||||
}
|
||||
|
||||
/**
|
||||
* 摘掉 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 改 ⇒ 下一个人按"取号起点"取号就撞号,或按"最新版本"漏掉本文件。 */
|
||||
@Test
|
||||
void inventoryDocTracksV152() throws IOException {
|
||||
Path doc = ROOT.resolve("docs/migration-inventory.md");
|
||||
String text = raw(doc);
|
||||
assertTrue(text.contains(migration().getFileName().toString()),
|
||||
"盘点文档应逐字保留本迁移文件名:" + migration().getFileName());
|
||||
assertTrue(text.contains("V150__shop_key_company_scope.sql"),
|
||||
"盘点文档应同时保留更早的文件名:只钉最新一条会重演「推进概览时把旧条目挤掉」那一次回归");
|
||||
}
|
||||
|
||||
/** 自检:本用例集扫的是真文件,且 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")
|
||||
+ ":预处理或文件路径坏了,本类的断言全部不可信");
|
||||
String rollbackExecutable = normalize(stripComments(raw(rollbackPatch())));
|
||||
assertTrue(count(rollbackExecutable, "ALTER COLUMN") == 2,
|
||||
"回滚补丁可执行段的 ALTER COLUMN 也应为 2(否则上面「装回两次」的断言进了恒绿分支)");
|
||||
}
|
||||
}
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
package com.nanri.aiimage.modules.dedupe.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.MybatisConfiguration;
|
||||
import com.nanri.aiimage.modules.dedupe.model.entity.DedupeTotalDataEntity;
|
||||
import org.apache.ibatis.builder.annotation.MapperAnnotationBuilder;
|
||||
import org.apache.ibatis.mapping.BoundSql;
|
||||
import org.apache.ibatis.mapping.MappedStatement;
|
||||
import org.apache.ibatis.session.Configuration;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* {@code insertBatchIgnore} 生成 SQL 的审计:去重库写侧必须显式带 {@code company_id}。
|
||||
*
|
||||
* <p>为什么必须单独有一支:服务层测试用 mock 捕获的是实体对象,看不到最终 SQL——本表写侧
|
||||
* 靠的是注解里的列清单(不是 MyBatis-Plus 的实体字段推导),把 {@code company_id} 从清单里漏掉
|
||||
* 或把 {@code #{row.companyId}} 写成 {@code ${...}} 都是"SQL 变了而 service 测试照样绿"。
|
||||
* 走 {@code MapperAnnotationBuilder} 解析注解、向真 {@code BoundSql} 断言,
|
||||
* 口径照抄 {@code ShopDataDuplicateCheckCompanyScopeTest#boundSqlFor}。</p>
|
||||
*/
|
||||
class DedupeTotalDataMapperSqlTest {
|
||||
|
||||
@Test
|
||||
void insertBatchCarriesCompanyIdOnEveryRow() throws Exception {
|
||||
BoundSql boundSql = boundSqlFor(2);
|
||||
|
||||
String sql = boundSql.getSql().replaceAll("\\s+", " ");
|
||||
assertTrue(sql.contains("INSERT IGNORE INTO biz_dedupe_total_data"),
|
||||
"批插语句应保留 INSERT IGNORE 形态: " + sql);
|
||||
assertTrue(sql.contains(
|
||||
"(data_value, country, group_id, uploader_user_id, uploader_username, company_id)"),
|
||||
"列清单必须逐字带上 company_id(去重库写侧修复的就是这一列): " + sql);
|
||||
// 每行 6 个值占位符:写成 ${row.companyId} 或漏掉一列都会让这里的数字对不上
|
||||
assertEquals(12, sql.chars().filter(c -> c == '?').count(),
|
||||
"2 行应有 12 个 ? 占位符(6 列 x 2 行): " + sql);
|
||||
assertEquals(12, boundSql.getParameterMappings().size(),
|
||||
"参数绑定数应等于占位符数");
|
||||
assertFalse(sql.contains("$"), "不得出现 ${} 拼接面: " + sql);
|
||||
}
|
||||
|
||||
private static BoundSql boundSqlFor(int rowCount) throws Exception {
|
||||
Method method = DedupeTotalDataMapper.class.getMethod("insertBatchIgnore", List.class);
|
||||
String script = String.join(" ", method.getAnnotation(org.apache.ibatis.annotations.Insert.class).value());
|
||||
assertTrue(script.contains("company_id"), "注解原文应含 company_id(生成 SQL 才可能含): " + script);
|
||||
Configuration configuration = new MybatisConfiguration();
|
||||
new MapperAnnotationBuilder(configuration, DedupeTotalDataMapper.class).parse();
|
||||
MappedStatement statement = configuration.getMappedStatement(
|
||||
DedupeTotalDataMapper.class.getName() + ".insertBatchIgnore");
|
||||
List<DedupeTotalDataEntity> rows = new java.util.ArrayList<>(rowCount);
|
||||
for (int i = 0; i < rowCount; i++) {
|
||||
DedupeTotalDataEntity row = new DedupeTotalDataEntity();
|
||||
row.setDataValue("B00000000" + i);
|
||||
row.setCompanyId(2L);
|
||||
rows.add(row);
|
||||
}
|
||||
return statement.getBoundSql(Map.of("rows", rows));
|
||||
}
|
||||
}
|
||||
+29
@@ -7,6 +7,7 @@ import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.modules.dedupe.mapper.DedupeTotalDataMapper;
|
||||
import com.nanri.aiimage.modules.dedupe.model.dto.DedupeTotalDataCreateRequest;
|
||||
import com.nanri.aiimage.modules.dedupe.model.entity.DedupeTotalDataEntity;
|
||||
import com.nanri.aiimage.common.service.CompanyScopeSupport;
|
||||
import com.nanri.aiimage.common.service.NodeSharedStore;
|
||||
import com.nanri.aiimage.modules.dedupe.model.vo.DedupeTotalDataImportProgressVo;
|
||||
import com.nanri.aiimage.modules.dedupe.model.vo.DedupeTotalDataItemVo;
|
||||
@@ -64,6 +65,8 @@ class DedupeTotalDataServiceTest {
|
||||
@Mock
|
||||
private ShopManageGroupMapper shopManageGroupMapper;
|
||||
@Mock
|
||||
private CompanyScopeSupport companyScopeSupport;
|
||||
@Mock
|
||||
private PlatformTransactionManager transactionManager;
|
||||
@Mock
|
||||
private TransactionStatus transactionStatus;
|
||||
@@ -74,6 +77,7 @@ class DedupeTotalDataServiceTest {
|
||||
void createRecordsUploaderIdentity() {
|
||||
AdminUserEntity uploader = user(23L, "normal", "member-a");
|
||||
when(adminUserMapper.selectById(23L)).thenReturn(uploader);
|
||||
when(companyScopeSupport.requireCompanyId(any(AdminUserEntity.class))).thenReturn(1L);
|
||||
stubWritableGroup(23L, 7L);
|
||||
when(dedupeTotalDataMapper.selectOne(any())).thenReturn(null);
|
||||
when(dedupeTotalDataMapper.insert(any(DedupeTotalDataEntity.class))).thenAnswer(invocation -> {
|
||||
@@ -102,6 +106,7 @@ class DedupeTotalDataServiceTest {
|
||||
assertEquals("member-a", captor.getValue().getUploaderUsername());
|
||||
assertEquals("B012345678", captor.getValue().getDataValue());
|
||||
assertEquals(7L, captor.getValue().getGroupId());
|
||||
assertEquals(1L, captor.getValue().getCompanyId(), "create 必须显式落 company_id,不许靠列上的 DEFAULT 兜");
|
||||
assertEquals("member-a", item.getUsername());
|
||||
assertEquals(7L, item.getGroupId());
|
||||
assertEquals("group-7", item.getGroupName());
|
||||
@@ -179,6 +184,7 @@ class DedupeTotalDataServiceTest {
|
||||
@Test
|
||||
void duplicateExcelValueKeepsOriginalUploader() throws Exception {
|
||||
when(adminUserMapper.selectById(23L)).thenReturn(user(23L, "normal", "member-a"));
|
||||
when(companyScopeSupport.requireCompanyId(any(AdminUserEntity.class))).thenReturn(1L);
|
||||
stubWritableGroup(23L, 7L);
|
||||
when(dedupeTotalDataMapper.selectExistingDataValues(List.of("B012345678")))
|
||||
.thenReturn(List.of("B012345678"));
|
||||
@@ -191,9 +197,27 @@ class DedupeTotalDataServiceTest {
|
||||
verify(dedupeTotalDataMapper, never()).insert(any(DedupeTotalDataEntity.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void importRejectsOperatorWithoutCompany() throws Exception {
|
||||
AdminUserEntity noCompany = user(23L, "normal", "member-a");
|
||||
noCompany.setCompanyId(null);
|
||||
when(adminUserMapper.selectById(23L)).thenReturn(noCompany);
|
||||
when(companyScopeSupport.requireCompanyId(any(AdminUserEntity.class)))
|
||||
.thenThrow(new BusinessException(403, "当前账号没有所属公司,无法按公司读写数据"));
|
||||
|
||||
BusinessException exception = assertThrows(
|
||||
BusinessException.class,
|
||||
() -> service.importFromExcel(asinWorkbook("B012345678"), 7L, 23L));
|
||||
|
||||
assertEquals("当前账号没有所属公司,无法按公司读写数据", exception.getMessage());
|
||||
verify(dedupeTotalDataMapper, never()).insertBatchIgnore(any());
|
||||
verify(dedupeTotalDataMapper, never()).insert(any(DedupeTotalDataEntity.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void importReadsAndNormalizesCountryColumn() throws Exception {
|
||||
when(adminUserMapper.selectById(23L)).thenReturn(user(23L, "normal", "member-a"));
|
||||
when(companyScopeSupport.requireCompanyId(any(AdminUserEntity.class))).thenReturn(1L);
|
||||
stubWritableGroup(23L, 7L);
|
||||
when(dedupeTotalDataMapper.selectExistingDataValues(List.of("B012345678"))).thenReturn(List.of());
|
||||
when(dedupeTotalDataMapper.insertBatchIgnore(any())).thenReturn(1);
|
||||
@@ -206,11 +230,14 @@ class DedupeTotalDataServiceTest {
|
||||
verify(dedupeTotalDataMapper).insertBatchIgnore(captor.capture());
|
||||
// US 不在五国范围内,应被过滤掉
|
||||
assertEquals("DE,UK", captor.getValue().getFirst().getCountry());
|
||||
assertEquals(1L, captor.getValue().getFirst().getCompanyId(),
|
||||
"import 批插必须显式带 company_id(DEFAULT 是给历史行与旧 jar 的临时兜底,待摘)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void importKeepsCountryBlankWhenHeaderMissing() throws Exception {
|
||||
when(adminUserMapper.selectById(23L)).thenReturn(user(23L, "normal", "member-a"));
|
||||
when(companyScopeSupport.requireCompanyId(any(AdminUserEntity.class))).thenReturn(1L);
|
||||
stubWritableGroup(23L, 7L);
|
||||
when(dedupeTotalDataMapper.selectExistingDataValues(List.of("B012345678"))).thenReturn(List.of());
|
||||
when(dedupeTotalDataMapper.insertBatchIgnore(any())).thenReturn(1);
|
||||
@@ -247,6 +274,7 @@ class DedupeTotalDataServiceTest {
|
||||
@Test
|
||||
void concurrentDuplicateDuringImportIsSkipped() throws Exception {
|
||||
when(adminUserMapper.selectById(23L)).thenReturn(user(23L, "normal", "member-a"));
|
||||
when(companyScopeSupport.requireCompanyId(any(AdminUserEntity.class))).thenReturn(1L);
|
||||
stubWritableGroup(23L, 7L);
|
||||
when(dedupeTotalDataMapper.selectOne(any())).thenReturn(null);
|
||||
when(dedupeTotalDataMapper.selectExistingDataValues(List.of("B012345678"))).thenReturn(List.of());
|
||||
@@ -531,6 +559,7 @@ class DedupeTotalDataServiceTest {
|
||||
user.setRole(role);
|
||||
user.setUsername(username);
|
||||
user.setIsAdmin("normal".equals(role) ? 0 : 1);
|
||||
user.setCompanyId(1L);
|
||||
return user;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user