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:
2026-10-07 04:26:43 +08:00
parent 3359b14e6e
commit 2b7c377e7e
9 changed files with 594 additions and 25 deletions
@@ -28,10 +28,10 @@ public interface DedupeTotalDataMapper extends BaseMapper<DedupeTotalDataEntity>
@Insert("""
<script>
INSERT IGNORE INTO biz_dedupe_total_data
(data_value, country, group_id, uploader_user_id, uploader_username)
(data_value, country, group_id, uploader_user_id, uploader_username, company_id)
VALUES
<foreach collection="rows" item="row" separator=",">
(#{row.dataValue}, #{row.country}, #{row.groupId}, #{row.uploaderUserId}, #{row.uploaderUsername})
(#{row.dataValue}, #{row.country}, #{row.groupId}, #{row.uploaderUserId}, #{row.uploaderUsername}, #{row.companyId})
</foreach>
</script>
""")
@@ -15,6 +15,16 @@ public class DedupeTotalDataEntity {
@TableId(type = IdType.AUTO)
private Long id;
/**
* 归属公司(V145 加列)。写侧一律显式落值——create 与 insertBatchIgnore 的入口都经
* {@code CompanyScopeSupport.requireCompanyId(操作者)} 解析后带进每个 insert,不许依赖列上那条
* 临时的 {@code DEFAULT 1}:V145 留它只为历史行与同批的旧 jar 不报 1364,待摘
* (CompanyDefaultGuard 哨兵在喊)。
*
* <p>读侧仍按 {@code uploader_user_id} 认公司(见 DedupeTotalDataService.applyCompanyScope):
* 历史行该列全部是 DEFAULT 兜的 1,对区分公司没有信息量。</p>
*/
private Long companyId;
private String dataValue;
private String country;
private Long groupId;
@@ -468,6 +468,7 @@ public class DedupeTotalDataService {
@Transactional
public DedupeTotalDataItemVo create(DedupeTotalDataCreateRequest request, Long operatorId) {
AdminUserEntity uploader = getOperator(operatorId);
Long companyId = companyScopeSupport.requireCompanyId(uploader);
ShopManageGroupEntity group = resolveWritableGroup(request.getGroupId(), uploader);
String dataValue = normalizeComparableValue(request.getDataValue());
ensureUnique(dataValue, null);
@@ -476,6 +477,7 @@ public class DedupeTotalDataService {
entity.setGroupId(group.getId());
entity.setUploaderUserId(uploader.getId());
entity.setUploaderUsername(uploader.getUsername());
entity.setCompanyId(companyId);
dedupeTotalDataMapper.insert(entity);
return toItemVo(getById(entity.getId()), group.getGroupName());
}
@@ -526,6 +528,7 @@ public class DedupeTotalDataService {
throw new BusinessException("导入文件超过大小上限");
}
AdminUserEntity uploader = getOperator(operatorId);
Long companyId = companyScopeSupport.requireCompanyId(uploader);
ShopManageGroupEntity group = resolveWritableGroup(groupId, uploader);
if (!importSlots.tryAcquire()) {
throw new BusinessException("导入任务过多,请稍后重试");
@@ -546,7 +549,8 @@ public class DedupeTotalDataService {
File tempFile = saveMultipartToTempFile(file);
String filename = file.getOriginalFilename();
Thread.ofVirtual().start(() -> runImportTask(
importId, tempFile, filename, uploader.getId(), uploader.getUsername(), group.getId()));
importId, tempFile, filename, uploader.getId(), uploader.getUsername(), group.getId(),
companyId));
} catch (Exception e) {
importSlots.release();
importProgressMap.remove(importId);
@@ -660,7 +664,7 @@ public class DedupeTotalDataService {
}
private void runImportTask(String importId, File tempFile, String filename,
Long uploaderUserId, String uploaderUsername, Long groupId) {
Long uploaderUserId, String uploaderUsername, Long groupId, Long companyId) {
DedupeTotalDataImportProgressVo progress = importProgressMap.get(importId);
if (progress == null) {
importSlots.release();
@@ -669,7 +673,7 @@ public class DedupeTotalDataService {
progress.setStatus("running");
try (InputStream inputStream = Files.newInputStream(tempFile.toPath())) {
DedupeTotalDataImportVo result = importFromExcelInternal(
inputStream, filename, progress, uploaderUserId, uploaderUsername, groupId);
inputStream, filename, progress, uploaderUserId, uploaderUsername, groupId, companyId);
progress.setTotalRows(result.getTotalRows());
progress.setAsinCount(result.getAsinCount());
progress.setInsertedCount(result.getInsertedCount());
@@ -721,11 +725,12 @@ public class DedupeTotalDataService {
throw new BusinessException("请上传 xlsx 文件");
}
AdminUserEntity uploader = getOperator(operatorId);
Long companyId = companyScopeSupport.requireCompanyId(uploader);
ShopManageGroupEntity group = resolveWritableGroup(groupId, uploader);
try (InputStream inputStream = file.getInputStream()) {
return importFromExcelInternal(
inputStream, file.getOriginalFilename(), null, uploader.getId(), uploader.getUsername(),
group.getId());
group.getId(), companyId);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
@@ -759,7 +764,7 @@ public class DedupeTotalDataService {
private DedupeTotalDataImportVo importFromExcelInternal(InputStream inputStream, String filename,
DedupeTotalDataImportProgressVo progress,
Long uploaderUserId, String uploaderUsername,
Long groupId) {
Long groupId, Long companyId) {
String lowerFilename = filename == null ? "" : filename.toLowerCase();
if (!(lowerFilename.endsWith(".xlsx") || lowerFilename.endsWith(".xls"))) {
throw new BusinessException("仅支持 .xlsx 或 .xls 文件");
@@ -769,7 +774,7 @@ public class DedupeTotalDataService {
// 此前 WorkbookFactory.create 把整表读成 DOM(50 万行约 1~2GB 堆),且行数上限在
// 加载完之后才校验(等于没有防线)。现在内存只保留单批待插入值与文件内去重集合,
// 行数上限在迭代过程中即时生效。
ImportSession session = new ImportSession(progress, groupId, uploaderUserId, uploaderUsername);
ImportSession session = new ImportSession(progress, groupId, uploaderUserId, uploaderUsername, companyId);
try {
ExcelStreamReader.readFirstSheet(inputStream, new ExcelStreamReader.SheetRowHandler() {
private Integer countryColumnIndex;
@@ -845,6 +850,7 @@ public class DedupeTotalDataService {
private final Long groupId;
private final Long uploaderUserId;
private final String uploaderUsername;
private final Long companyId;
private final Set<String> seenInFile = new HashSet<>();
private final List<String> pendingValues = new ArrayList<>(IMPORT_BATCH_SIZE);
private final Map<String, String> pendingCountries = new HashMap<>();
@@ -855,11 +861,12 @@ public class DedupeTotalDataService {
private int skippedCount;
private ImportSession(DedupeTotalDataImportProgressVo progress, Long groupId,
Long uploaderUserId, String uploaderUsername) {
Long uploaderUserId, String uploaderUsername, Long companyId) {
this.progress = progress;
this.groupId = groupId;
this.uploaderUserId = uploaderUserId;
this.uploaderUsername = uploaderUsername;
this.companyId = companyId;
}
private void acceptRow(Map<Integer, String> rowMap, Integer countryColumnIndex) {
@@ -897,7 +904,7 @@ public class DedupeTotalDataService {
return;
}
ImportBatchResult batch = insertImportBatch(
pendingValues, pendingCountries, groupId, uploaderUserId, uploaderUsername);
pendingValues, pendingCountries, groupId, uploaderUserId, uploaderUsername, companyId);
insertedCount += batch.insertedCount();
skippedCount += batch.skippedCount();
pendingValues.clear();
@@ -928,7 +935,8 @@ public class DedupeTotalDataService {
Map<String, String> countriesByValue,
Long groupId,
Long uploaderUserId,
String uploaderUsername) {
String uploaderUsername,
Long companyId) {
if (values == null || values.isEmpty()) {
return new ImportBatchResult(0, 0);
}
@@ -944,6 +952,7 @@ public class DedupeTotalDataService {
entity.setGroupId(groupId);
entity.setUploaderUserId(uploaderUserId);
entity.setUploaderUsername(uploaderUsername);
entity.setCompanyId(companyId);
rows.add(entity);
}
if (rows.isEmpty()) {
@@ -1285,8 +1294,9 @@ public class DedupeTotalDataService {
* 公司 tab 收窄:本表按「上传账号」认公司——{@code uploader_user_id} 是 NOT NULL(V75 先回灌再收紧),
* 且有 idx_uploader_user_id_id 可走点查。
*
* <p>不读 V145 新加的 company_id:写入侧实体没有该字段、{@code insertBatchIgnore} 的列清单也不带,
* 全靠 MySQL 的 DEFAULT 1 兜底,所以第 2 家账号新导入的行今天仍会被盖成公司 1。那一列不能当读侧依据。</p>
* <p>不按 V145 加的 company_id 筛:那一列对 V145 之前的历史行全部是 DEFAULT 兜的 1,没有区分力。
* 写侧现已显式落值(create 与 insertBatchIgnore 都带 company_id),但读侧一旦改用它,历史行会整批归到
* 公司 1——所以那列只供写入留存与 uk_company_data_value 使用,读侧口径维持按上传账号推导。</p>
*
* <p>空集给一条不可能命中的条件而不是"不筛":tab 选了这家公司却看得到全平台,比看不到更坏。</p>
*/
@@ -0,0 +1,79 @@
-- =============================================================
-- 迁移 V152__columns_shop_key_company_id_drop_default
-- 模板:docs/flyway-migration-template.md
-- 需求:2026-10-06「优先处理 columns 等三列 DEFAULT 问题」
-- 合并依据:V150 头注释第 6 段与 docs/migration-inventory.md 的同款待办都要求
-- 「columns 与 biz_shop_key 这两条摘 DEFAULT 合并成一版发出」(两条都是纯元数据、
-- 前提各自独立);第三条 biz_dedupe_total_data 为什么不在本版见第 6 段。
--
-- 1. 变更目的:摘掉两列在混合版本窗口期留的兜底默认值 DEFAULT 1——
-- 留着的唯一后果是:任何绕过显式落列的写入被静默塞进第 1 家(厦门米椿花)。
-- 摘掉之后同类写入会撞 MySQL 1364(Field 'company_id' doesn't have a default value)
-- 炸在日志里——这是取舍,不是缺陷:宁可当场炸,也不要静默归错公司(同 V144 的取舍)。
--
-- 摘除的前提【已逐条取证,2026-10-07】:
-- · 带 V149/V150 的 jar 已在两台同版运行:flyway_schema_history 只读实查,
-- 149/150/151 三条 success=1、installed_on=2026-10-06 17:32:29(此后 10-07 各批 jar
-- 均为其后代,写侧代码只多不少);
-- · columns 的 INSERT 通道都显式落 company_id:PermissionMenuService.create /
-- copyTreeFromTemplate;PermissionMenuSchemaInitializer 的种子 INSERT(生产默认关:
-- @ConditionalOnProperty 要求 AIIMAGE_PERMISSION_SCHEMA_INIT_ENABLED=true,
-- 两台 .env 实查未设);
-- · biz_shop_key 的唯一 INSERT 通道 ShopKeyService.create 显式落 company_id;
-- · 两列的 COLUMN_DEFAULT 当前都是 1(10-07 只读实查 information_schema)。
--
-- 2. 影响表与数据量:只动两列的默认值属性。不写数据、不加索引、不删列。
-- · columns:154 行(10-07 只读取证:公司 1/2/3 各 52/51/51 行);
-- · biz_shop_key:16 行(全部 company_id = 1)。
-- DROP DEFAULT 不改变任何已存行的读值:instant 加列后的历史行读值由加列时记录的
-- 默认值给出(本机 MySQL 8.4.9 实验证实摘除前后读值一致),摘除只影响"之后省略
-- 该列的 INSERT"。
--
-- 3. 锁表风险:极低。ALTER TABLE ... ALTER COLUMN ... DROP DEFAULT 是纯元数据操作
-- (瞬时完成、不重建表、不扫描行)。
-- 【禁写成 MODIFY COLUMN ... NOT NULL】——MODIFY 走重建表,重建按"当时的列默认值"
-- 物化历史行;默认值刚被摘掉,历史归属就失去依据(V144/V150 头注释同款禁令)。
-- 不碰 users / company / biz_shop_manage / biz_dedupe_total_data 等任何其他表。
--
-- 4. 验证 SQL(迁移后跑,不许只看启动日志的 Successfully applied):
-- SHOW COLUMNS FROM `columns` LIKE 'company_id';
-- -> 期望 Null = NO,Default = NULL
-- SHOW COLUMNS FROM `biz_shop_key` LIKE 'company_id';
-- -> 期望 Null = NO,Default = NULL
-- SELECT TABLE_NAME, COLUMN_DEFAULT FROM information_schema.COLUMNS
-- WHERE TABLE_SCHEMA = DATABASE() AND COLUMN_NAME = 'company_id'
-- AND TABLE_NAME IN ('columns','biz_shop_key');
-- -> 期望两行 COLUMN_DEFAULT 均为 NULL
-- 启动期 CompanyDefaultGuard 对这两张表不再打 COMPANY_DEFAULT_STILL_PRESENT
-- (签名与清单原样保留:哪天 DEFAULT 被装回——dump 重建、手滑 SET DEFAULT——
-- 它会再喊出来;biz_dedupe_total_data 仍会喊,它还没摘,见第 6 段)。
--
-- 5. 回滚步骤:人工补丁 backend-java/docs/rollback-V152-columns-shop-key-default.sql
-- (在 Flyway 扫描路径之外;版本化回滚等于让"决定回滚"这件事自己发生)。
-- 触发场景是「摘错了」——场外的、省略 company_id 的写入被 1364 打出来。
-- 顺序:停两台应用 → 跑脚本(两条 ALTER COLUMN ... SET DEFAULT 1,纯元数据)
-- → 删 flyway_schema_history 的 version='152' 行 → 回滚 jar → 起应用。
-- 仅仅回滚 jar(代码问题、与默认值无关)不需要本补丁:V149/V150 起的 jar 全部
-- 显式落列,对默认值在不在毫无感知,V152 保持应用态即可。
--
-- 6. 上线窗口与「为什么只剩这一条」:随 jar 双节点同窗口发布,金丝雀过了立刻补第二台。
-- biz_dedupe_total_data 的 DEFAULT 1 不在本版:它的写入侧(insertBatchIgnore 的列
-- 清单)历史上不带 company_id、实体也没有该字段,全靠 DEFAULT 兜底——先修写侧、
-- 上线并验证真实导入之后才谈摘(修复已落码,尚未出厂)。在那之前启动期哨兵继续
-- 通过 COMPANY_DEFAULT_STILL_PRESENT 盯它,不靠人记得。
-- 【不要顺手加入 biz_product_category / biz_invalid_asin_data】:那两张共享表的
-- DEFAULT 1 是承重约束(写侧有意不落该列、靠 DEFAULT 满足 NOT NULL),摘它=每次
-- 新建报 1364。它们真正消失的时点是另一笔迁移直接 DROP COLUMN,不是这里。
--
-- 【可重跑性】本文件只有两条 ALTER COLUMN ... DROP DEFAULT:对"已无默认值"的列重复
-- 执行是无操作(发布前在 scratch MySQL 8.4.9 上重放两遍证实),列由 V149/V150 建、
-- Flyway 保证顺序 ⇒ 不需要 information_schema 守卫(与 V144 同口径;守卫是留给
-- "重复执行会报错"的 ADD COLUMN/INDEX 那一类)。按「补数据 → flyway repair → 重启」
-- 恢复时重跑本文件安全。
-- =============================================================
ALTER TABLE `columns`
ALTER COLUMN company_id DROP DEFAULT;
ALTER TABLE `biz_shop_key`
ALTER COLUMN company_id DROP DEFAULT;
@@ -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(否则上面「装回两次」的断言进了恒绿分支)");
}
}
@@ -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));
}
}
@@ -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;
}