feat(多公司): V143 建 company 与 users.company_id,配 12 例迁移护栏
一期只做账号归属:company 主表 + users.company_id,57 张业务表零 DDL、零回填, 公司维度全部由 user_id → users.company_id 派生。存量账号在迁移里归入「厦门米椿花」, 不需要另外拿脚本对着生产库 UPDATE。 两个不落进代码就会丢的判断: 1) 每条语句都写成幂等。MySQL 的 DDL 不进事务,NOT NULL 闸门失败时前面的建表/插数/加列 已经落库,而 repair + 重启会让 Flyway 从第一条语句重跑整个文件;写成裸 CREATE TABLE / 裸 INSERT 的话,恢复路径自己撞 1050/1060/1062,"补数据后重启"就变成"必须手工清库"。 2) 回滚是 docs/rollback-V143-company.sql,不是一条 V144 迁移。放进 src/main/resources/db/ 等于让 Flyway 在下次启动时自动执行回滚。这两条口径一并写进 migration-inventory.md 的 约束段,供后续所有迁移引用。 闸门留 DEFAULT 1 只为混合版本窗口存在(旧 jar 建号不带 company_id),摘除时机改由启动期 巡检盯(下一步实现),不靠人记。 CompanyMigrationV143Test 12 例,断言打在剥掉注释后的可执行 SQL 上(否则"注释里写了这句话" 就算通过);16 条变异全部被抓到。全量 mvn test 3515 例 0 红。 后端 modules/company、两端前端、DEFAULT 摘除巡检尚未开始。
This commit is contained in:
@@ -0,0 +1,120 @@
|
||||
-- =============================================================
|
||||
-- 迁移 V143__company_and_users_company_id
|
||||
-- 模板:docs/flyway-migration-template.md
|
||||
-- 设计:crawler-plugin/docs/ops/company-multi-tenant-design-2026-10-04.md
|
||||
--
|
||||
-- 1. 变更目的:为多公司(租户)场景引入主表 company,给 users 挂 company_id,并把现有全部
|
||||
-- 账号归属「厦门米椿花」。业务表零 DDL——公司维度一律由 user_id → users.company_id 派生,
|
||||
-- 不给 57 张业务表冗余 company_id(与"数据按账号归属、公司维度跟着账号走"的定案一致)。
|
||||
-- 2. 影响表与数据量:company(新建,1 行);users(全表 UPDATE 一次,行数以生产实查为准——
|
||||
-- aiimage.sql 快照的 AUTO_INCREMENT 有跳号,不等于行数);columns(+1 行后台菜单)。
|
||||
-- 三张表都是百行量级,业务表 0 张受影响。
|
||||
-- 3. 锁表风险:低。MySQL 8 的 ADD COLUMN 为 INSTANT;ADD INDEX 为 INPLACE;
|
||||
-- MODIFY ... NOT NULL 触发 COPY 重建,但 users 只百行量级(毫秒级)。
|
||||
-- 不碰 biz_task_file_job 等锁热点表。
|
||||
-- 4. 验证 SQL:见文件末尾「验证」段。
|
||||
-- 5. 回滚步骤:执行人工补丁脚本 docs/rollback-V143-company.sql(在 Flyway 扫描路径之外)。
|
||||
-- 顺序:停两台应用 → 跑脚本 → 删 flyway_schema_history 的本版本行 → 回滚 jar → 起应用。
|
||||
-- 6. 上线窗口:随 jar 双节点滚动发布,Flyway 在应用启动期执行,第二节点见"已应用"即跳过。
|
||||
-- 建议业务低峰 02:00-06:00。
|
||||
--
|
||||
-- 【可重跑性】MySQL 的 DDL 不进事务。本迁移若在 NOT NULL 闸门处失败,前面的建表/插数/加列
|
||||
-- 已经落库;按「补数据 → flyway repair → 重启」恢复时 Flyway 会从第一条语句重跑整个文件,
|
||||
-- 所以每一条都写成幂等形式(IF NOT EXISTS / INSERT IGNORE / information_schema 条件 DDL /
|
||||
-- WHERE 限定 / NOT EXISTS 守卫)。
|
||||
-- =============================================================
|
||||
|
||||
-- ---------- 1. 公司(租户)主表 ----------
|
||||
-- 与紫鸟语义的 company_name 字段(biz_ziniao_memory_store / biz_publish_file,自由文本无外键)
|
||||
-- 不是同一回事,那两个保持原名不动。
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `company` (
|
||||
`id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键',
|
||||
`company_name` varchar(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '公司名称',
|
||||
`status` tinyint NOT NULL DEFAULT 1 COMMENT '1=启用 0=停用',
|
||||
`remark` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '备注',
|
||||
`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (`id`) USING BTREE,
|
||||
UNIQUE INDEX `uk_company_name`(`company_name` ASC) USING BTREE,
|
||||
INDEX `idx_company_status`(`status` ASC) USING BTREE
|
||||
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '公司(租户)主表' ROW_FORMAT = Dynamic;
|
||||
|
||||
-- id 显式钉为 1:下一步 users.company_id 的 DEFAULT 只能是字面量(MySQL 不允许 DEFAULT 子查询),
|
||||
-- 存量回填也写死 = 1。id 若由 AUTO_INCREMENT 决定,这两处就会指向一个不存在的公司。
|
||||
-- IGNORE 只为重跑服务:id 已钉死 + 公司名唯一,能撞上的只有一模一样的这一行。
|
||||
INSERT IGNORE INTO `company` (`id`, `company_name`, `status`, `remark`)
|
||||
VALUES (1, '厦门米椿花', 1, '初始公司:现有全部账号与数据归属');
|
||||
|
||||
-- ---------- 2. users 挂所属公司 ----------
|
||||
|
||||
SET @db_name = DATABASE();
|
||||
|
||||
SET @col_exists := (
|
||||
SELECT COUNT(*) FROM information_schema.COLUMNS
|
||||
WHERE TABLE_SCHEMA = @db_name AND TABLE_NAME = 'users' AND COLUMN_NAME = 'company_id'
|
||||
);
|
||||
-- 先建成可空:下一节的 UPDATE 才有行可回填,再靠 MODIFY 收成 NOT NULL。
|
||||
-- 列与索引在同一条 ALTER 里,MySQL 保证整条原子,故只需按列存在性判一次。
|
||||
SET @sql := IF(@col_exists = 0,
|
||||
'ALTER TABLE `users` ADD COLUMN `company_id` bigint NULL DEFAULT NULL COMMENT ''所属公司(company.id)'' AFTER `created_by_id`, ADD INDEX `idx_users_company_id`(`company_id` ASC) USING BTREE',
|
||||
'SELECT 1'
|
||||
);
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
-- ---------- 3. 存量账号全部归厦门米椿花 ----------
|
||||
-- WHERE 限定 NULL,重跑时是 no-op;不会覆盖任何已经人工指定过公司的行。
|
||||
|
||||
UPDATE `users` SET `company_id` = 1 WHERE `company_id` IS NULL;
|
||||
|
||||
-- 自检闸门:上一句若漏掉任何一行,这里抛 ER_INVALID_USE_OF_NULL 让迁移失败,
|
||||
-- 而不是留一堆 NULL 静默通过(NULL 意味着这些账号在公司维度上整体失明)。
|
||||
--
|
||||
-- DEFAULT 1 是【临时】的,唯一存在理由是混合版本窗口:发布期间一台新 jar、一台旧 jar,
|
||||
-- /api 经主机 B 的 clb 打到两台,旧 jar 的 AdminUserService.create 不给 company_id 赋值,
|
||||
-- 列若无 DEFAULT,严格模式报 "Field 'company_id' doesn't have a default value",
|
||||
-- 打到旧节点的建号请求全失败。两台同版后新代码永远显式写 company_id,DEFAULT 变成死重,
|
||||
-- 但必须在第二家公司开通前摘除——否则之后每个不传公司的建号都被静默塞进厦门米椿花。
|
||||
-- 摘除时机由启动期巡检盯(见设计文档 §6.3),不在本迁移里处理。
|
||||
ALTER TABLE `users`
|
||||
MODIFY COLUMN `company_id` bigint NOT NULL DEFAULT 1 COMMENT '所属公司(company.id)';
|
||||
|
||||
-- ---------- 4. 后台「公司管理」菜单 ----------
|
||||
-- 挂在「账号与权限」分组(admin_group_account,V103 建)下,与
|
||||
-- admin_users→account/users、admin_group_manage→account/groups 同一命名口径(V109)。
|
||||
-- route_path 必须与 admin-frontend-vue/src/router/routes.ts 的 path 逐字一致,否则菜单点进去 404。
|
||||
-- sort_order 按同级最大值 +5 自算:现有子菜单的 sort_order 来自初始数据,从未被任何迁移设定过,
|
||||
-- 写字面量等于猜。幂等写法照 V103/V106(columns.column_key 上有 uk_column_key,重复插会直接报错)。
|
||||
|
||||
INSERT INTO `columns` (`name`, `column_key`, `menu_type`, `route_path`, `sort_order`, `parent_id`)
|
||||
SELECT '公司管理', 'admin_companies', 'admin', 'account/companies',
|
||||
(SELECT COALESCE(MAX(sib.sort_order), 0) + 5
|
||||
FROM `columns` sib
|
||||
WHERE sib.parent_id = parent.id),
|
||||
parent.id
|
||||
FROM `columns` parent
|
||||
WHERE parent.`column_key` = 'admin_group_account'
|
||||
AND NOT EXISTS (SELECT 1 FROM `columns` x WHERE x.`column_key` = 'admin_companies');
|
||||
|
||||
-- =============================================================
|
||||
-- 验证 SQL(迁移后在库上执行)
|
||||
-- SELECT COUNT(*) AS company_rows FROM `company`;
|
||||
-- -> 期望 1
|
||||
-- SELECT `id`, `company_name`, `status` FROM `company`;
|
||||
-- -> 期望 1 | 厦门米椿花 | 1(id 必须是 1,DEFAULT 1 与回填都指着它)
|
||||
-- SELECT COUNT(*) AS users_total,
|
||||
-- SUM(company_id IS NULL) AS null_company,
|
||||
-- SUM(company_id = 1) AS in_xiamen_michunghua
|
||||
-- FROM `users`;
|
||||
-- -> 期望 null_company = 0 且 users_total = in_xiamen_michunghua
|
||||
-- SHOW COLUMNS FROM `users` LIKE 'company_id';
|
||||
-- -> 期望 Null = NO,Default = 1(Default 一旦不该再是 1,说明公司已 >1 家而临时 DEFAULT 未摘)
|
||||
-- SHOW INDEX FROM `users` WHERE Key_name = 'idx_users_company_id';
|
||||
-- -> 期望 1 行
|
||||
-- SELECT c.`id`, c.`name`, c.`column_key`, c.`route_path`, c.`sort_order`, p.`column_key` AS parent_key
|
||||
-- FROM `columns` c LEFT JOIN `columns` p ON p.`id` = c.`parent_id`
|
||||
-- WHERE c.`column_key` = 'admin_companies';
|
||||
-- -> 期望 1 行,parent_key = admin_group_account,route_path = account/companies
|
||||
-- =============================================================
|
||||
@@ -0,0 +1,435 @@
|
||||
package com.nanri.aiimage.config;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
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 static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* 多公司一期 V143 迁移契约(设计文档 docs/ops/company-multi-tenant-design-2026-10-04.md §3/§6)。
|
||||
*
|
||||
* 本环境无 H2 / testcontainers(见 pom.xml),迁移不能真跑,因此按仓库既有口径做文件审计
|
||||
* (对照 MigrationInventoryTest / IndexMigrationV101Test)。与它们不同的是:断言一律打在
|
||||
* **剥掉注释后的可执行 SQL** 上,避免"注释里写了这句话就算通过";解析用的正则不匹配即红。
|
||||
*/
|
||||
class CompanyMigrationV143Test {
|
||||
|
||||
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$");
|
||||
private static final String ROLLBACK_RELATIVE = "docs/rollback-V143-company.sql";
|
||||
|
||||
// ---------------------------------------------------------------- 取文件
|
||||
|
||||
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 int maxVersionOnDisk() throws IOException {
|
||||
return versionFiles().stream().mapToInt(CompanyMigrationV143Test::versionOf).max().orElse(0);
|
||||
}
|
||||
|
||||
private static Path migration() throws IOException {
|
||||
List<Path> hits = versionFiles().stream()
|
||||
.filter(p -> p.getFileName().toString().startsWith("V143__"))
|
||||
.toList();
|
||||
assertFalse(hits.isEmpty(), "缺少 V143__*.sql:多公司迁移还没落盘");
|
||||
assertEquals(1, hits.size(), "V143 只允许一个迁移文件(撞号会让 Flyway 启动失败)");
|
||||
return hits.get(0);
|
||||
}
|
||||
|
||||
private static String rawMigration() throws IOException {
|
||||
return Files.readString(migration(), StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
/** 按顶层逗号切分(跳过括号内与字符串内的逗号)。 */
|
||||
private static List<String> splitTopLevel(String s) {
|
||||
List<String> parts = new ArrayList<>();
|
||||
StringBuilder cur = new StringBuilder();
|
||||
int depth = 0;
|
||||
boolean inQuote = false;
|
||||
for (int i = 0; i < s.length(); i++) {
|
||||
char c = s.charAt(i);
|
||||
if (inQuote) {
|
||||
cur.append(c);
|
||||
if (c == '\'') {
|
||||
if (i + 1 < s.length() && s.charAt(i + 1) == '\'') {
|
||||
cur.append(s.charAt(++i));
|
||||
} else {
|
||||
inQuote = false;
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (c == '\'') {
|
||||
inQuote = true;
|
||||
cur.append(c);
|
||||
continue;
|
||||
}
|
||||
if (c == '(') {
|
||||
depth++;
|
||||
} else if (c == ')') {
|
||||
depth--;
|
||||
} else if (c == ',' && depth == 0) {
|
||||
parts.add(cur.toString().trim());
|
||||
cur.setLength(0);
|
||||
continue;
|
||||
}
|
||||
cur.append(c);
|
||||
}
|
||||
if (!cur.toString().trim().isEmpty()) {
|
||||
parts.add(cur.toString().trim());
|
||||
}
|
||||
return parts;
|
||||
}
|
||||
|
||||
private static void assertMatches(String sql, String regex, String message) {
|
||||
assertTrue(Pattern.compile(regex).matcher(sql).find(), message + "(未匹配到 " + regex + ")");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 用例
|
||||
|
||||
/**
|
||||
* 破坏点:版本号取错。V132/V133 是永久退役洞,取到它们或取到已被占用的号,
|
||||
* Flyway 启动期直接 "resolved migration not applied" / 撞号失败。
|
||||
*/
|
||||
@Test
|
||||
void migrationIsVersionedOneFourThree() throws IOException {
|
||||
Path file = migration();
|
||||
assertEquals(143, versionOf(file), "多公司迁移必须是 V143(V142 之后的下一号)");
|
||||
assertTrue(file.getFileName().toString().matches("^V143__[A-Za-z0-9_.-]+$"),
|
||||
"命名应 V143__<snake 描述>.sql: " + file.getFileName());
|
||||
assertEquals(maxVersionOnDisk(), 143,
|
||||
"V143 必须是当前最大版本;若磁盘上已有更大的号,说明本迁移被插到了历史中间");
|
||||
}
|
||||
|
||||
/** 破坏点:头注释缺项 → 上线评审拿不到锁表风险与回滚口径。 */
|
||||
@Test
|
||||
void headerCarriesSixMandatoryTemplateFields() throws IOException {
|
||||
String raw = rawMigration();
|
||||
assertTrue(raw.contains("V143"), "头注释应标明迁移版本 V143");
|
||||
for (int i = 1; i <= 6; i++) {
|
||||
assertTrue(raw.contains(i + ". "), "头注释应含模板第 " + i + " 项必填");
|
||||
}
|
||||
for (String field : List.of("变更目的", "影响表与数据量", "锁表风险", "验证 SQL", "回滚步骤", "上线窗口")) {
|
||||
assertTrue(raw.contains(field), "头注释应含必填项:" + field);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 破坏点:company_name 不唯一。公司名是二期登录定位({@code UNIQUE(company_id, username)})
|
||||
* 与后台公司下拉的唯一人类可读标识,重名会让"选公司"这一步不可判定。
|
||||
*/
|
||||
@Test
|
||||
void createsCompanyTableWithUniqueCompanyName() throws IOException {
|
||||
String sql = statements();
|
||||
assertMatches(sql, "CREATE TABLE (IF NOT EXISTS )?`company`\\s*\\(", "应新建 company 主表");
|
||||
assertMatches(sql, "`company_name`\\s+varchar\\(\\d+\\)[^,]*NOT NULL", "company_name 应为非空 varchar");
|
||||
assertMatches(sql, "UNIQUE INDEX `uk_company_name`\\s*\\(\\s*`company_name`",
|
||||
"company_name 上应有唯一索引 uk_company_name");
|
||||
assertMatches(sql, "PRIMARY KEY \\(`id`\\)", "company 应有主键 id");
|
||||
}
|
||||
|
||||
/**
|
||||
* 破坏点:初始公司 id 不是字面量 1。users.company_id 的 DEFAULT 只能是字面量
|
||||
* (MySQL 不允许 DEFAULT 子查询),回填也写死 = 1;id 一旦不是 1,
|
||||
* 混合版本窗口里旧 jar 建的号与全部存量账号都会指向一个不存在的公司。
|
||||
*/
|
||||
@Test
|
||||
void seedsInitialCompanyPinnedToIdOne() throws IOException {
|
||||
String sql = statements();
|
||||
Matcher m = Pattern.compile("INSERT(?: IGNORE)? INTO `company`\\s*\\(([^)]*)\\)\\s*VALUES\\s*\\((.*?)\\)\\s*;")
|
||||
.matcher(sql);
|
||||
assertTrue(m.find(), "应有一条显式插入初始公司的 INSERT(未匹配到 INSERT INTO `company` (...) VALUES (...);)");
|
||||
|
||||
List<String> columns = splitTopLevel(m.group(1)).stream()
|
||||
.map(c -> c.replace("`", "").trim())
|
||||
.toList();
|
||||
List<String> values = splitTopLevel(m.group(2));
|
||||
assertEquals(columns.size(), values.size(),
|
||||
"INSERT 的列数与值数应一致,否则解析口径变了、本用例的断言已失效");
|
||||
|
||||
int idIdx = columns.indexOf("id");
|
||||
assertTrue(idIdx >= 0, "初始公司必须显式指定 id 列,不能交给 AUTO_INCREMENT");
|
||||
assertEquals("1", values.get(idIdx), "初始公司 id 必须钉死为 1(users.company_id DEFAULT 1 依赖它)");
|
||||
|
||||
int nameIdx = columns.indexOf("company_name");
|
||||
assertTrue(nameIdx >= 0, "初始公司必须写入 company_name");
|
||||
assertEquals("'厦门米椿花'", values.get(nameIdx), "存量数据归属的初始公司名");
|
||||
|
||||
int statusIdx = columns.indexOf("status");
|
||||
assertTrue(statusIdx >= 0, "初始公司必须写入 status");
|
||||
assertEquals("1", values.get(statusIdx), "初始公司应为启用状态");
|
||||
}
|
||||
|
||||
/**
|
||||
* 破坏点:users 没挂 company_id 或没建索引。公司维度全靠 user_id → users.company_id 派生,
|
||||
* 缺列则整个方案不成立;缺索引则二期每次 scope 展开都要全表扫 users。
|
||||
* 另一半破坏点是"顺手给业务表也加了 company_id"——那与定案(数据按账号归属、公司维度跟着账号走)
|
||||
* 相反,且会把一期从"业务表零 DDL"变成 57 张表的回填工程。
|
||||
*/
|
||||
@Test
|
||||
void addsUsersCompanyIdColumnAndIndex() throws IOException {
|
||||
String sql = statements();
|
||||
assertMatches(sql, "ALTER TABLE `users`\\s+ADD COLUMN `company_id`\\s+bigint",
|
||||
"users 应新增 bigint 列 company_id");
|
||||
assertMatches(sql, "ADD INDEX `idx_users_company_id`\\s*\\(\\s*`company_id`",
|
||||
"company_id 上应建索引 idx_users_company_id");
|
||||
|
||||
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(),
|
||||
"一期业务表零 DDL:只允许改 users,实际改到了 " + altered);
|
||||
|
||||
List<String> created = new ArrayList<>();
|
||||
Matcher create = Pattern.compile("CREATE TABLE (?:IF NOT EXISTS )?`([A-Za-z0-9_]+)`").matcher(sql);
|
||||
while (create.find()) {
|
||||
created.add(create.group(1));
|
||||
}
|
||||
assertEquals(List.of("company"), created, "只应新建 company 一张表,实际 " + created);
|
||||
}
|
||||
|
||||
/**
|
||||
* 破坏点:回填缺失或顺序颠倒。
|
||||
* 顺序颠倒(先 MODIFY NOT NULL 再 UPDATE)在严格模式下直接 ER_INVALID_USE_OF_NULL 让迁移失败;
|
||||
* 回填缺失而 NOT NULL 闸门也缺失,则存量账号 company_id 静默为 NULL——公司维度对老数据整体失明。
|
||||
*/
|
||||
@Test
|
||||
void backfillsExistingAccountsBeforeNotNullGate() throws IOException {
|
||||
String sql = statements();
|
||||
Pattern backfill = Pattern.compile(
|
||||
"UPDATE `users`\\s+SET\\s+`company_id`\\s*=\\s*1\\s+WHERE\\s+`company_id`\\s+IS\\s+NULL");
|
||||
Pattern gate = Pattern.compile(
|
||||
"ALTER TABLE `users`\\s+MODIFY COLUMN `company_id`\\s+bigint\\s+NOT NULL\\s+DEFAULT 1");
|
||||
|
||||
Matcher b = backfill.matcher(sql);
|
||||
Matcher g = gate.matcher(sql);
|
||||
assertTrue(b.find(), "应把存量账号回填到公司 1(厦门米椿花)");
|
||||
assertTrue(g.find(), "应有 MODIFY ... NOT NULL 自检闸门:回填漏行时让迁移失败,而不是留一堆 NULL 静默通过");
|
||||
assertTrue(b.start() < g.start(), "回填必须在 NOT NULL 闸门之前,否则闸门会先撞上存量 NULL");
|
||||
}
|
||||
|
||||
/**
|
||||
* 破坏点:DEFAULT 1 被提前摘掉。滚动发布期间一台新 jar、一台旧 jar,/api 经 clb 打到两台;
|
||||
* 旧 jar 的 AdminUserService.create 不给 company_id 赋值,列若无 DEFAULT,
|
||||
* 严格模式报 "Field 'company_id' doesn't have a default value",打到旧节点的建号请求全失败(约一半)。
|
||||
*/
|
||||
@Test
|
||||
void notNullGateKeepsTemporaryDefaultOne() throws IOException {
|
||||
String sql = statements();
|
||||
assertMatches(sql, "MODIFY COLUMN `company_id`\\s+bigint\\s+NOT NULL\\s+DEFAULT 1",
|
||||
"company_id 应落为 NOT NULL DEFAULT 1(DEFAULT 只为混合版本窗口存在,摘除时机由启动期巡检盯)");
|
||||
assertTrue(rawMigration().contains("混合版本"),
|
||||
"头注释应写清 DEFAULT 的存在理由与摘除时机,否则后人会当它是永久默认值");
|
||||
}
|
||||
|
||||
/**
|
||||
* 破坏点:菜单行插重、挂错父级、route_path 与前端路由不一致。
|
||||
* route_path 必须与 admin-frontend-vue/src/router/routes.ts 的 path 逐字一致,否则菜单点进去 404;
|
||||
* 非幂等写法在重跑或补数时会插出两行"公司管理"。
|
||||
*/
|
||||
@Test
|
||||
void insertsAdminCompaniesMenuIdempotently() throws IOException {
|
||||
String sql = statements();
|
||||
Matcher m = Pattern.compile("INSERT INTO `columns`\\s*\\(([^)]*)\\)(.*?);").matcher(sql);
|
||||
assertTrue(m.find(), "应插入后台「公司管理」菜单(未匹配到 INSERT INTO `columns`)");
|
||||
|
||||
List<String> columns = splitTopLevel(m.group(1)).stream()
|
||||
.map(c -> c.replace("`", "").trim())
|
||||
.toList();
|
||||
for (String required : List.of("name", "column_key", "menu_type", "route_path", "parent_id")) {
|
||||
assertTrue(columns.contains(required), "菜单插入应显式给出列 " + required);
|
||||
}
|
||||
assertTrue(columns.contains("sort_order"), "菜单插入应给出 sort_order,否则同级顺序不确定");
|
||||
|
||||
String body = m.group(2);
|
||||
assertTrue(body.contains("'admin_companies'"), "column_key 必须是 admin_companies(前端 menuKey 与权限判定都用它)");
|
||||
assertTrue(body.contains("'account/companies'"), "route_path 必须是 account/companies(与前端路由逐字一致)");
|
||||
assertTrue(body.contains("'admin_group_account'"), "父级应取「账号与权限」分组 admin_group_account");
|
||||
assertMatches(body, "NOT EXISTS\\s*\\(", "菜单插入必须幂等:按 column_key 判存在");
|
||||
assertTrue(body.contains("SELECT"), "菜单插入应为 INSERT ... SELECT ... WHERE NOT EXISTS,裸 VALUES 重跑必重行");
|
||||
}
|
||||
|
||||
/**
|
||||
* 破坏点:迁移不可重跑。MySQL 的 DDL 不进事务 —— V143 若在 NOT NULL 闸门处失败,
|
||||
* 前面的 CREATE TABLE / INSERT / ADD COLUMN 已经落库。按 §8.1 的恢复步骤
|
||||
* (补齐漏行 → flyway repair → 重启)Flyway 会**从第一条语句重跑整个文件**,
|
||||
* 届时非幂等语句依次报 1050 table exists / 1060 duplicate column / 1062 duplicate entry,
|
||||
* 把"补数据后重启"变成"必须手工清库"。
|
||||
*/
|
||||
@Test
|
||||
void migrationIsRerunnableAfterPartialFailure() throws IOException {
|
||||
String sql = statements();
|
||||
assertMatches(sql, "CREATE TABLE IF NOT EXISTS `company`",
|
||||
"建表必须带 IF NOT EXISTS:重跑时表已在库里");
|
||||
assertMatches(sql, "INSERT IGNORE INTO `company`",
|
||||
"初始公司必须 INSERT IGNORE(id 钉死 + 公司名唯一,重复即本次重跑)");
|
||||
assertMatches(sql, "information_schema\\.COLUMNS",
|
||||
"ADD COLUMN 必须先查 information_schema 判存在(对齐 V142 的条件 DDL 写法)");
|
||||
assertMatches(sql, "TABLE_NAME\\s*=\\s*'users'", "存在性检查要按 TABLE_NAME='users' 筛");
|
||||
assertMatches(sql, "COLUMN_NAME\\s*=\\s*'company_id'", "存在性检查要按 COLUMN_NAME='company_id' 筛");
|
||||
assertMatches(sql, "SET\\s+@sql\\s*:=\\s*IF\\s*\\(\\s*@col_exists\\s*=\\s*0",
|
||||
"条件 DDL 必须真的用存在性标志分支:查了 information_schema 却无条件执行 ALTER,重跑照样报 1060");
|
||||
assertMatches(sql, "PREPARE\\s+stmt\\s+FROM", "条件 DDL 要用 PREPARE/EXECUTE 执行");
|
||||
assertMatches(sql, "DEALLOCATE\\s+PREPARE\\s+stmt", "游标语句用完必须 DEALLOCATE,否则同名 stmt 二次 PREPARE 报错");
|
||||
assertMatches(sql, "INSERT INTO `columns`[\\s\\S]*NOT EXISTS\\s*\\(\\s*SELECT",
|
||||
"菜单行必须按 column_key 判存在后再插");
|
||||
}
|
||||
|
||||
/**
|
||||
* 破坏点:文件内没留验证 SQL。上线的人只能凭"启动没报错"判断迁移成功,
|
||||
* 而本迁移最需要核实的三件事(回填有没有漏行、NOT NULL 与 DEFAULT 有没有真落上、
|
||||
* 菜单挂对父级没有)都不体现在启动日志里。
|
||||
*/
|
||||
@Test
|
||||
void migrationShipsPostDeployVerificationSql() throws IOException {
|
||||
String raw = rawMigration();
|
||||
assertTrue(raw.contains("验证 SQL"), "头注释应含「验证 SQL」段(模板第 4 项)");
|
||||
assertTrue(raw.contains("company_id IS NULL"),
|
||||
"验证 SQL 应能查出回填漏行的计数,这是 NOT NULL 闸门之外唯一的复核手段");
|
||||
assertTrue(raw.contains("SHOW COLUMNS FROM `users` LIKE 'company_id'")
|
||||
|| raw.contains("SHOW COLUMNS FROM users LIKE 'company_id'"),
|
||||
"验证 SQL 应核对 company_id 的 Null / Default,DEFAULT 1 被摘没摘一眼可见");
|
||||
assertTrue(raw.contains("admin_companies"), "验证 SQL 应核对「公司管理」菜单行");
|
||||
}
|
||||
|
||||
/**
|
||||
* 破坏点:回滚被写成 Flyway 版本化迁移(例如 V144__rollback_company.sql)放进 src/main/resources/db。
|
||||
* 那样它会在下次启动时被 Flyway 自动执行,静默把 V143 撤销掉,同时打乱版本连续性审计。
|
||||
* 回滚必须是扫描路径之外、由人按顺序执行的补丁脚本。
|
||||
*/
|
||||
@Test
|
||||
void rollbackLivesOutsideFlywayScanPath() throws IOException {
|
||||
Path rollback = ROOT.resolve(ROLLBACK_RELATIVE);
|
||||
assertTrue(Files.isRegularFile(rollback),
|
||||
"回滚脚本应存在于 " + ROLLBACK_RELATIVE + "(Flyway 扫描路径之外),否则事故时无从回退");
|
||||
|
||||
String rb = normalize(stripComments(Files.readString(rollback, StandardCharsets.UTF_8)));
|
||||
assertMatches(rb, "ALTER TABLE `users`\\s+DROP INDEX `idx_users_company_id`", "回滚应删掉索引");
|
||||
assertMatches(rb, "DROP COLUMN `company_id`", "回滚应删掉 users.company_id");
|
||||
assertMatches(rb, "DROP TABLE (IF EXISTS )?`company`", "回滚应删掉 company 表");
|
||||
assertTrue(rb.contains("flyway_schema_history") && rb.contains("143"),
|
||||
"回滚必须清掉 flyway_schema_history 里 V143 的记录,否则重装 jar 时 Flyway 认为已应用而跳过");
|
||||
assertTrue(rb.contains("admin_companies"), "回滚应删掉后台「公司管理」菜单行");
|
||||
|
||||
assertTrue(rawMigration().contains(ROLLBACK_RELATIVE),
|
||||
"V143 头注释的「回滚步骤」必须点名该脚本,否则值班的人找不到它");
|
||||
assertFalse(rawMigration().contains("db/V144"),
|
||||
"回滚不得写成版本化迁移 V144:Flyway 会在下次启动时自动执行它,静默撤销 V143");
|
||||
|
||||
for (Path f : versionFiles()) {
|
||||
String name = f.getFileName().toString().toLowerCase();
|
||||
assertFalse(name.contains("rollback"), "Flyway 扫描路径内不得出现回滚迁移: " + f.getFileName());
|
||||
String ex = normalize(stripComments(Files.readString(f, StandardCharsets.UTF_8)));
|
||||
assertFalse(ex.contains("DROP COLUMN `company_id`"),
|
||||
"扫描路径内的迁移不得撤销 company_id: " + f.getFileName());
|
||||
assertFalse(Pattern.compile("DROP TABLE (IF EXISTS )?`company`").matcher(ex).find(),
|
||||
"扫描路径内的迁移不得删掉 company 表: " + f.getFileName());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 破坏点:docs/migration-inventory.md 的数字没跟着改。
|
||||
* 下一个人按文档里的"取号起点"取号就会撞号(Flyway 启动失败),或以为 V143 还没被占用。
|
||||
*/
|
||||
@Test
|
||||
void inventoryDocTracksTheNewMigration() throws IOException {
|
||||
Path doc = ROOT.resolve("docs/migration-inventory.md");
|
||||
assertTrue(Files.isRegularFile(doc), "盘点文档应存在");
|
||||
String text = Files.readString(doc, StandardCharsets.UTF_8);
|
||||
|
||||
List<Path> files = versionFiles();
|
||||
int maxOnDisk = files.stream().mapToInt(CompanyMigrationV143Test::versionOf).max().orElse(0);
|
||||
|
||||
assertTrue(text.contains(migration().getFileName().toString()),
|
||||
"盘点文档应记录最新迁移文件名 " + migration().getFileName());
|
||||
|
||||
Matcher count = Pattern.compile("版本化迁移文件数:\\*\\*(\\d+)\\*\\*").matcher(text);
|
||||
assertTrue(count.find(), "盘点文档应给出版本化迁移文件数");
|
||||
assertEquals(files.size(), Integer.parseInt(count.group(1)),
|
||||
"文档记录的迁移文件数与磁盘不符");
|
||||
|
||||
Matcher range = Pattern.compile("整数版本范围:\\*\\*V1\\.\\.V(\\d+)\\*\\*").matcher(text);
|
||||
assertTrue(range.find(), "盘点文档应给出整数版本范围");
|
||||
assertEquals(maxOnDisk, Integer.parseInt(range.group(1)),
|
||||
"文档记录的整数版本上界与磁盘不符");
|
||||
|
||||
Matcher next = Pattern.compile("从 \\*\\*V(\\d+)\\*\\* 起取号").matcher(text);
|
||||
assertTrue(next.find(), "盘点文档应给出取号起点");
|
||||
assertEquals(maxOnDisk + 1, Integer.parseInt(next.group(1)),
|
||||
"取号起点必须 = 磁盘最大版本 + 1,否则会撞号或留洞");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user