fix(XZH-21): 版本历史旧行回退以 notes.version 为上界,不存在版本号 404;回收站列表与恢复同口径

- NotesController#contentAt:去掉 coalesce 到 notes.version-1 的兜底;旧口径锚点仅在 N <= notes.version 时解析,越界一律 404(B1)
- LibraryController#/{kind}/trash:接受 TrashService 全部 kind,planner 三类按 kind 过滤
- 测试:ApiIntegrationTest 新增回收站 kind 等价、旧库历史、缺失版本、列表 kind 用例;UpgradePathTest 覆盖 V17→V18 读取/恢复与三条旧行
This commit is contained in:
xzh committed 2026-11-12 00:02:19 +08:00
1 parent bd8264b8cf
commit 3df4afab7b
4 files changed
+394 -12

No files matched your search

@@ -160,13 +160,19 @@ public class LibraryController {
+ " where id=? and deleted_at is null", id);
}
/** 回收站列表只覆盖知识库类模块;RSS/提示词/工作流/收集箱用 /admin-tools/trash。 */
/**
* 回收站列表:接受 TrashService 的全部 kind,与 restore/purge 及 /admin-tools/trash 的 kind 集合一致,
* 不再出现「列表 404、恢复 204」的两套口径。
*/
@GetMapping("/{kind}/trash")
public List<Map<String, Object>> trashList(@PathVariable String kind,
@RequestParam(defaultValue = "0") @Min(0) int offset) {
checkKind(kind);
return db.queryForList("select id," + TrashService.titleColumn(kind) + " as title"
+ ",deleted_at from " + kind + " where deleted_at is not null order by deleted_at desc,id limit 100 offset ?", offset);
var spec = TrashService.spec(kind);
return db.queryForList("select id," + spec.name() + " as title"
+ ",deleted_at from " + spec.table()
+ (TrashService.isPlanner(kind) ? " where kind=? and deleted_at is not null" : " where deleted_at is not null")
+ " order by deleted_at desc,id limit 100 offset ?",
TrashService.isPlanner(kind) ? new Object[]{kind, offset} : new Object[]{offset});
}
/**
@@ -188,18 +188,28 @@ public class NotesController {
/**
* 某个版本号对应的「保存前内容」。新旧口径在库里的编号规则不同:
* 新口径行 version=N 就是第 N 版保存前;旧口径行 version=N 是第 N 版保存前、第 N+1 版的内容,
* 所以旧行只在「≤ N 的最大旧版本号」这一次被使用——旧库升级后最高版本的保存前内容正好在这一行。
* 所以旧行只在「≤ N 的最大旧版本号」这一点被使用,且 N 不超过当前版本号——旧库升级后
* history/{当前版本} 落在最高旧行,即当前版本自身的保存前内容。
* 旧行不会压过更新的新快照(新快照优先),新保存的快照也不会被旧行顶替。读取与恢复共用这一份映射。
* 没有任何行能对应 N 时返回 404,绝不兜底到当前内容或某个固定旧行。
* 旧行回退必须有上界:只有 N ≤ 该笔记的当前版本号(即历史能覆盖到的最大 N)时才解析,否则任意大的 N
* 都会被 max(≤N) 映射到同一个旧行(第三轮测试阻断项 B1:history/9 → 200 返回 v1)。
* 上界用 notes.version 而不是「最高旧版本号」:V18 前的触发器写入 0 起始的旧行,升级时用户恰好看不到
* 当前版本的保存前内容,用最高旧版本号会把 history/{当前版本} 一刀切成 404。
*/
private Map<String, Object> contentAt(UUID noteId, long version) {
// 1) 同号行(新口径优先);2) 否则取旧口径锚点行:≤ N 的最大旧版本号,旧库没有更高版本的旧行时就是最高一版
// 1) 同号行(新口径优先)
var row = db.queryForList("select * from note_history where note_id=? and version=?"
+ " order by legacy_versioning limit 1", noteId, version).stream().findFirst();
if (row.isEmpty() && version > 0)
row = db.queryForList("select * from note_history where note_id=? and version=(select coalesce("
+ " (select max(l.version) from note_history l where l.note_id=? and l.legacy_versioning and l.version<=?),"
+ " (select n.version-1 from notes n where n.id=?))) and legacy_versioning", noteId, noteId, version, noteId)
.stream().findFirst();
+ " order by legacy_versioning limit 1", noteId, version).stream().findFirst();
// 2) 旧口径锚点行:≤ N 的最大旧版本号,且 N 不得超过该笔记的当前版本号(否则一律 404)
if (row.isEmpty() && version > 0) {
var noteVersion = db.queryForList("select version from notes where id=?", Long.class, noteId).stream().findFirst();
if (noteVersion.isPresent() && version <= noteVersion.get())
row = db.queryForList("select note_id,version,title,body,category,folder,tags,star,legacy_versioning from note_history"
+ " where note_id=?::uuid and legacy_versioning and version=(select max(version) from note_history"
+ " where note_id=?::uuid and legacy_versioning and version<=?)::bigint", noteId, noteId, version)
.stream().findFirst();
}
return row.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "版本不存在"));
}
@@ -35,6 +35,7 @@ class ApiIntegrationTest {
@BeforeEach
void clean() {
db.update("delete from inbox_items");
db.update("delete from workspace_notifications");
db.update("delete from planner_items");
db.update("delete from workspace_tags");
db.update("delete from workspace_flows");
@@ -898,4 +899,164 @@ class ApiIntegrationTest {
mvc.perform(get("/api/v1/notes/" + id + "/history/2").session(session))
.andExpect(jsonPath("$.category").value("设计灵感"));
}
/**
* XZH-21 回归:回收站里每个 kind 都必须两套路由等价(/admin-tools/trash 与 /library/{kind}/trash),
* 前端不传 kind 的方法由 /admin-tools/trash/kinds 给出;列表每行只有一条记录(同 id 不重复),
* summary.trash 与全部列表行数一致。回归第二轮测试报告的「重复行 / 恢复 404」。
*/
@Test
void trashKindsCoverEveryModuleAndRoutesStayEquivalent() throws Exception {
var session = login();
List<Map<String, Object>> kinds = json.readValue(mvc.perform(get("/api/v1/admin-tools/trash/kinds").session(session))
.andExpect(status().isOk()).andReturn().getResponse().getContentAsByteArray(), List.class);
List<String> kindIds = kinds.stream().map(k -> (String) k.get("kind")).toList();
assertEquals(List.of("notes", "blogs", "bookmarks", "assets", "tasks", "events", "snippets", "rss", "prompts", "flows", "inbox"),
kindIds);
for (Map<String, Object> kind : kinds) {
boolean planner = (Boolean) kind.get("planner");
assertEquals(planner, List.of("tasks", "events", "snippets").contains(kind.get("kind")), "planner 标记错误");
}
// 清理:清空回收站,让本用例的计数从 0 开始
mvc.perform(delete("/api/v1/admin-tools/trash").session(session).with(csrf())).andExpect(status().isOk());
String url = "https://example.org/trash-kinds-" + System.nanoTime();
String bookmark = json.readTree(mvc.perform(post("/api/v1/bookmarks").session(session).with(csrf())
.contentType("application/json").content(json.writeValueAsBytes(Map.of(
"title", "路由书签", "url", url, "description", "", "category", "设计工具"))))
.andExpect(status().isCreated()).andReturn().getResponse().getContentAsByteArray()).get("id").asText();
// 先采集(已删除的书签不能被采集),再分别删除:书签直接删除,收集项删除
String item = json.readTree(mvc.perform(post("/api/v1/inbox/bookmarks/" + bookmark).session(session).with(csrf()))
.andExpect(status().isOk()).andReturn().getResponse().getContentAsByteArray()).get("id").asText();
mvc.perform(delete("/api/v1/bookmarks/" + bookmark).session(session).with(csrf()))
.andExpect(status().isNoContent());
mvc.perform(delete("/api/v1/inbox/" + item).session(session).with(csrf())).andExpect(status().isNoContent());
var rows = json.readTree(mvc.perform(get("/api/v1/admin-tools/trash").session(session))
.andExpect(status().isOk()).andReturn().getResponse().getContentAsByteArray());
var ids = new java.util.LinkedHashSet<String>();
for (var row : rows) {
assertTrue(ids.add(row.get("kind").asText() + ":" + row.get("id").asText()), "回收站列表出现重复行");
assertTrue(kindIds.contains(row.get("kind").asText()), "出现未知 kind:" + row.get("kind").asText());
}
assertEquals(2, ids.size());
mvc.perform(get("/api/v1/admin-tools/summary").session(session))
.andExpect(jsonPath("$.trash").value(2));
// 两套路由对同一条记录等价:用 /admin-tools 恢复,用 /library 永久删除
mvc.perform(post("/api/v1/admin-tools/trash/bookmarks/" + bookmark).session(session).with(csrf()))
.andExpect(status().isNoContent());
mvc.perform(get("/api/v1/bookmarks/" + bookmark).session(session)).andExpect(status().isOk());
mvc.perform(post("/api/v1/admin-tools/trash/inbox/" + item).session(session).with(csrf()))
.andExpect(status().isNoContent());
mvc.perform(get("/api/v1/inbox/" + item).session(session)).andExpect(jsonPath("$.id").value(item));
mvc.perform(delete("/api/v1/bookmarks/" + bookmark).session(session).with(csrf()))
.andExpect(status().isNoContent());
mvc.perform(delete("/api/v1/admin-tools/trash/bookmarks/" + bookmark).session(session).with(csrf()))
.andExpect(status().isNoContent());
mvc.perform(post("/api/v1/library/bookmarks/trash/" + bookmark).session(session).with(csrf()))
.andExpect(status().isNotFound());
}
/**
* XZH-21 回归:开发环境的库已经按旧版 V1–V17 建过,V18 加了列但升级前写入的 note_history 行是
* 「旧口径」且 LegacyVersioning 标记不会自动出现(只有真正跑过 V18 的 update 才会有)。读历史不能 500、
* 不能空,恢复也不能写回错位的内容。这条按 FE 的真实调用补充。
*/
@Test
void legacyHistoryReadAndRestoreSupportPartialMarks() throws Exception {
var session = login();
var input = new java.util.HashMap<String, Object>(Map.of(
"title", "旧库笔记", "body", "n0", "category", "技术笔记", "tag", "", "version", 0));
String id = json.readTree(mvc.perform(post("/api/v1/notes").session(session).with(csrf())
.contentType("application/json").content(json.writeValueAsBytes(input)))
.andExpect(status().isCreated()).andReturn().getResponse().getContentAsByteArray()).get("id").asText();
// 模拟升级前写入的旧口径历史:0=第一版保存前(n0),1=第二版保存前(n1),笔记当前是第 2 版(n2)
db.update("delete from note_history where note_id=?", java.util.UUID.fromString(id));
db.update("insert into note_history(note_id,version,title,body,category,folder,tags,star,legacy_versioning)"
+ " values (?,0,'旧库笔记','n0','技术笔记','默认文件夹','',false,true),"
+ " (?,1,'旧库笔记','n1','技术笔记','默认文件夹','',false,true)", java.util.UUID.fromString(id), java.util.UUID.fromString(id));
db.update("update notes set body='n2',version=2 where id=?", java.util.UUID.fromString(id));
// 与前端 NoteHistory.vue 一致:列表取首条的 version 再点「恢复」
var list = json.readTree(mvc.perform(get("/api/v1/notes/" + id + "/history").session(session))
.andExpect(status().isOk()).andReturn().getResponse().getContentAsByteArray());
assertTrue(list.size() >= 1);
long newest = list.get(0).get("version").asLong();
assertEquals(1, newest, "旧库的最近一版历史(第 1 版保存前 = n1)");
mvc.perform(get("/api/v1/notes/" + id + "/history/" + newest).session(session))
.andExpect(status().isOk()).andExpect(jsonPath("$.body").value("n1"));
// 与升级前一致的语义:旧口径 history/2 是第 2 版保存前 = n1(旧库没有更新历史)
mvc.perform(get("/api/v1/notes/" + id + "/history/2").session(session))
.andExpect(status().isOk()).andExpect(jsonPath("$.body").value("n1"));
mvc.perform(post("/api/v1/notes/" + id + "/history/2").session(session).with(csrf())
.contentType("application/json").content("{}"))
.andExpect(status().isOk()).andExpect(jsonPath("$.body").value("n1"));
}
/** XZH-21 回归:不存在的版本号返回 404(不能兜底成当前内容),恢复同理。 */
@Test
void missingHistoryVersionIsNotFoundForReadAndRestore() throws Exception {
var session = login();
var input = new java.util.HashMap<String, Object>(Map.of(
"title", "缺版本", "body", "v0", "category", "技术笔记", "tag", "", "version", 0));
String id = json.readTree(mvc.perform(post("/api/v1/notes").session(session).with(csrf())
.contentType("application/json").content(json.writeValueAsBytes(input)))
.andExpect(status().isCreated()).andReturn().getResponse().getContentAsByteArray()).get("id").asText();
input.put("body", "v1");
mvc.perform(put("/api/v1/notes/" + id).session(session).with(csrf())
.contentType("application/json").content(json.writeValueAsBytes(input))).andExpect(status().isOk());
mvc.perform(get("/api/v1/notes/" + id + "/history/9").session(session)).andExpect(status().isNotFound());
mvc.perform(post("/api/v1/notes/" + id + "/history/9").session(session).with(csrf())
.contentType("application/json").content("{}")).andExpect(status().isNotFound());
}
/**
* XZH-21 回归(第三轮补充问题):/library/{kind}/trash 列表与恢复/永久删除接受同一组 kind。
* 之前列表对 rss/prompts/flows/inbox 抛 404,而恢复是 204,「两套路由等价」在列表这一侧不成立。
*/
@Test
void libraryTrashListAcceptsEveryTrashKind() throws Exception {
var session = login();
long stamp = System.nanoTime();
String day = java.time.LocalDate.now().plusDays(5).toString();
String task = json.readTree(mvc.perform(post("/api/v1/planner/tasks").session(session).with(csrf())
.contentType("application/json").content(json.writeValueAsBytes(Map.of(
"title", "列表-待办-" + stamp, "body", ""))))
.andExpect(status().isCreated()).andReturn().getResponse().getContentAsByteArray()).get("id").asText();
String event = json.readTree(mvc.perform(post("/api/v1/planner/events").session(session).with(csrf())
.contentType("application/json").content(json.writeValueAsBytes(Map.of(
"title", "列表-日程-" + stamp, "body", "", "starts_at", day + "T07:30"))))
.andExpect(status().isCreated()).andReturn().getResponse().getContentAsByteArray()).get("id").asText();
mvc.perform(delete("/api/v1/planner/tasks/" + task).session(session).with(csrf())).andExpect(status().isNoContent());
mvc.perform(delete("/api/v1/planner/events/" + event).session(session).with(csrf())).andExpect(status().isNoContent());
for (String kind : List.of("notes", "blogs", "bookmarks", "assets", "tasks", "rss", "prompts", "flows", "inbox")) {
var rows = json.readTree(mvc.perform(get("/api/v1/library/" + kind + "/trash").session(session))
.andExpect(status().isOk()).andReturn().getResponse().getContentAsByteArray());
assertTrue(rows.isArray(), kind + " 列表不是数组");
}
// planner 共用一张表,列表必须按 kind 过滤
var tasks = json.readTree(mvc.perform(get("/api/v1/library/tasks/trash").session(session))
.andExpect(status().isOk()).andReturn().getResponse().getContentAsByteArray());
assertEquals(List.of("列表-待办-" + stamp), tasks.findValuesAsText("title"));
var events = json.readTree(mvc.perform(get("/api/v1/library/events/trash").session(session))
.andExpect(status().isOk()).andReturn().getResponse().getContentAsByteArray());
assertEquals(List.of("列表-日程-" + stamp), events.findValuesAsText("title"));
// 未知 kind 仍然是 404
mvc.perform(get("/api/v1/library/unknown/trash").session(session)).andExpect(status().isNotFound());
}
/** XZH-21 回归:/library 的删除通知要写对模块名(笔记不能写成"素材")。 */
@Test
void libraryTrashNoticeUsesModuleLabel() throws Exception {
var session = login();
String id = json.readTree(mvc.perform(post("/api/v1/notes").session(session).with(csrf())
.contentType("application/json").content(json.writeValueAsBytes(Map.of(
"title", "通知文案笔记", "body", "内容", "category", "技术笔记", "tag", ""))))
.andExpect(status().isCreated()).andReturn().getResponse().getContentAsByteArray()).get("id").asText();
// 知识库列表的「移入回收站」走批量接口
mvc.perform(post("/api/v1/library/notes/batch").session(session).with(csrf()).contentType("application/json")
.content(json.writeValueAsBytes(Map.of("action", "trash", "ids", List.of(id))))).andExpect(status().isNoContent());
mvc.perform(get("/api/v1/admin-tools/notifications").session(session))
.andExpect(jsonPath("$[0].title").value(org.hamcrest.Matchers.containsString("已删除笔记「通知文案笔记」")));
}
}
@@ -0,0 +1,205 @@
package com.myspace;
import static org.junit.jupiter.api.Assertions.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.UUID;
import org.flywaydb.core.Flyway;
import org.junit.jupiter.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.test.web.servlet.MockMvc;
/**
* XZH-21 回归:升级路径。既有测试类都在「全新的库」上由 Flyway 一次建到最新,覆盖不到
* 「已经在 V17 上跑过的库用新代码启动」这条路径——第二轮测试报告正是在这里报出升级后版本历史 500。
*
* <p>本类用独立库(TEST_UPGRADE_DB_URL,默认 myspace_upgrade_test,每次删表重建):
* <ol>
* <li>只迁移到 V17,写入旧口径数据(note_history 里没有 legacy_versioning 列);
* <li>再迁移到全部版本,断言列已补上、旧行标记为 true 并保留原有 version 编号;
* <li>迁移后再迁移一次(幂等);
* <li>应用启动后经接口读取并恢复旧口径历史:不能 500,内容必须是该版本保存前的内容。
* </ol>
* 第 4 步是 XZH-21 第三轮发现的缺口:升级后 history/{n} 对旧行取到了「下一版」的内容,恢复会写回错误内容。
*/
@SpringBootTest(
properties = {
"spring.datasource.url=${TEST_UPGRADE_DB_URL:jdbc:postgresql://localhost:55432/myspace_upgrade_test}",
"spring.datasource.username=${TEST_DB_USER:myspace}",
"spring.datasource.password=${TEST_DB_PASSWORD:}",
"app.admin-password=integration-test-password",
"app.storage=target/test-assets"
})
@AutoConfigureMockMvc
class UpgradePathTest {
static final String URL = System.getenv("TEST_UPGRADE_DB_URL");
static final String USER = value("TEST_DB_USER", "myspace");
static final String PASSWORD = value("TEST_DB_PASSWORD", "");
static String value(String name, String fallback) {
String v = System.getenv(name);
return v == null || v.isBlank() ? fallback : v;
}
static final String BASE = URL != null ? URL : "jdbc:postgresql://localhost:55432/myspace_upgrade_test";
static String db;
@Autowired MockMvc mvc;
@Autowired com.fasterxml.jackson.databind.ObjectMapper json;
@Autowired JdbcTemplate jdbc;
static Flyway flyway(String url) {
return Flyway.configure().dataSource(url, USER, PASSWORD).cleanDisabled(false).load();
}
/** Spring 容器启动时会把库迁到最新;建库/清空必须放在启动之后、测试之前。 */
@BeforeEach
void prepare() throws Exception {
String admin = BASE.replaceFirst("/[^/]*$", "/postgres");
// 库不存在时创建;权限不足时请先手工 create database
try (Connection c = DriverManager.getConnection(admin, USER, PASSWORD); Statement s = c.createStatement()) {
s.execute("create database " + BASE.substring(BASE.lastIndexOf('/') + 1));
} catch (java.sql.SQLException exists) {
// already exists
}
db = BASE;
flyway(db).clean();
}
@Test
void upgradeFromV17KeepsOldHistoryReadable() throws Exception {
Flyway v17 = Flyway.configure().dataSource(db, USER, PASSWORD)
.target("17").cleanDisabled(true).load();
v17.migrate();
assertEquals("17", flyway(db).info().current().getVersion().getVersion());
// 旧口径数据:note_history 有 0/1 两行、没有 legacy_versioning 列,笔记版本为 2
UUID id = UUID.randomUUID();
try (Connection c = DriverManager.getConnection(db, USER, PASSWORD); Statement s = c.createStatement()) {
s.execute("insert into notes(id,title,body,category,version) values ('" + id
+ "','old','v2','技术笔记',2)");
s.execute("insert into note_history(note_id,version,title,body,category,folder,tags,star) values ('" + id
+ "',0,'old','orig','技术笔记','默认文件夹','',false),('" + id
+ "',1,'old','v1','技术笔记','默认文件夹','',false)");
}
Flyway upgrade = flyway(db);
upgrade.migrate();
// 幂等:再次执行不应再应用任何脚本
assertEquals(0, upgrade.migrate().migrationsExecuted);
try (Connection c = DriverManager.getConnection(db, USER, PASSWORD); Statement s = c.createStatement()) {
var column = s.executeQuery("select count(*) from information_schema.columns where table_name='note_history'"
+ " and column_name='legacy_versioning'");
column.next();
assertEquals(1, column.getInt(1), "升级后缺少 legacy_versioning 列");
var rows = s.executeQuery("select version,legacy_versioning from note_history where note_id='" + id
+ "' order by version");
var flags = new StringBuilder();
while (rows.next()) flags.append(rows.getInt(1)).append(':').append(rows.getBoolean(2)).append(' ');
assertEquals("0:true 1:true ", flags.toString(), "旧行必须标记为旧口径并保留原编号");
var latest = s.executeQuery("select version from flyway_schema_history where success order by installed_rank desc limit 1");
latest.next();
assertEquals("18", latest.getString(1));
}
if (jdbc.queryForObject("select count(*) from app_user", Integer.class) == 0)
jdbc.update("insert into app_user values (1,'admin',?)",
new org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder().encode("integration-test-password"));
// 应用启动后:旧口径行(0=原始, 1=v1,笔记版本 2)读回的是各自保存前的内容,不串到下一版
MockHttpSession session = (MockHttpSession) mvc.perform(
org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post("/api/v1/auth/login")
.with(org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf())
.param("username", "admin").param("password", "integration-test-password"))
.andExpect(org.springframework.test.web.servlet.result.MockMvcResultMatchers.status().isOk())
.andReturn().getRequest().getSession();
historyBody(session, id, 1, "v1");
historyBody(session, id, 0, "orig");
// 与升级前一致的语义:history/{n} 是「第 n 版保存前」的内容。旧库最高版本是 2,因此唯一可读的是 history/2 = v1
historyBody(session, id, 2, "v1");
// 恢复 history/2 必须回到 v1,不能被「版本号 ≥ n 的最新一行」顶替成 v2
mvc.perform(org.springframework.test.web.servlet.request.MockMvcRequestBuilders
.post("/api/v1/notes/" + id + "/history/2").session(session)
.with(org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf())
.contentType(MediaType.APPLICATION_JSON).content("{}"))
.andExpect(org.springframework.test.web.servlet.result.MockMvcResultMatchers.status().isOk())
.andExpect(org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath("$.body").value("v1"));
// 第三轮阻断 B1:旧库上 n 大于所有旧行版本号时必须 404,不能回落成某个旧快照(读取与恢复都算)
mvc.perform(org.springframework.test.web.servlet.request.MockMvcRequestBuilders
.get("/api/v1/notes/" + id + "/history/9").session(session))
.andExpect(org.springframework.test.web.servlet.result.MockMvcResultMatchers.status().isNotFound());
mvc.perform(org.springframework.test.web.servlet.request.MockMvcRequestBuilders
.post("/api/v1/notes/" + id + "/history/9").session(session)
.with(org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf())
.contentType(MediaType.APPLICATION_JSON).content("{}"))
.andExpect(org.springframework.test.web.servlet.result.MockMvcResultMatchers.status().isNotFound());
assertEquals(3, jdbc.queryForObject("select version from notes where id=?::uuid", Integer.class, id),
"恢复不存在的版本不能改动笔记版本");
assertEquals("v1", jdbc.queryForObject("select body from notes where id=?::uuid", String.class, id));
}
/**
* 旧库有 0/1/2 三条旧行、笔记 version=3(第三轮报告「残留风险」):读取与恢复都要落在「≤ n 的最大旧行」,
* 大于旧行最大版本号的 n 一律 404。
*/
@Test
void upgradeWithThreeLegacyRowsResolvesEachVersionOnce() throws Exception {
Flyway.configure().dataSource(db, USER, PASSWORD).target("17").cleanDisabled(true).load().migrate();
UUID id = UUID.randomUUID();
UUID note2 = UUID.randomUUID();
try (Connection c = DriverManager.getConnection(db, USER, PASSWORD); Statement s = c.createStatement()) {
s.execute("insert into notes(id,title,body,category,version) values ('" + id
+ "','old','v3','技术笔记',3),('" + note2 + "','old2','v3','技术笔记',3)");
for (String n : new String[] {id.toString(), note2.toString()})
s.execute("insert into note_history(note_id,version,title,body,category,folder,tags,star) values ('" + n
+ "',0,'old','orig','技术笔记','默认文件夹','',false),('" + n
+ "',1,'old','v1','技术笔记','默认文件夹','',false),('" + n
+ "',2,'old','v2','技术笔记','默认文件夹','',false)");
}
flyway(db).migrate();
if (jdbc.queryForObject("select count(*) from app_user", Integer.class) == 0)
jdbc.update("insert into app_user values (1,'admin',?)",
new org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder().encode("integration-test-password"));
MockHttpSession session = (MockHttpSession) mvc.perform(
org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post("/api/v1/auth/login")
.with(org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf())
.param("username", "admin").param("password", "integration-test-password"))
.andExpect(org.springframework.test.web.servlet.result.MockMvcResultMatchers.status().isOk())
.andReturn().getRequest().getSession();
historyBody(session, id, 0, "orig");
historyBody(session, id, 1, "v1");
historyBody(session, id, 2, "v2");
historyBody(session, id, 3, "v2");
for (long n : new long[] {4, 9}) {
mvc.perform(org.springframework.test.web.servlet.request.MockMvcRequestBuilders
.get("/api/v1/notes/" + id + "/history/" + n).session(session))
.andExpect(org.springframework.test.web.servlet.result.MockMvcResultMatchers.status().isNotFound());
mvc.perform(org.springframework.test.web.servlet.request.MockMvcRequestBuilders
.post("/api/v1/notes/" + id + "/history/" + n).session(session)
.with(org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf())
.contentType(MediaType.APPLICATION_JSON).content("{}"))
.andExpect(org.springframework.test.web.servlet.result.MockMvcResultMatchers.status().isNotFound());
}
// 恢复 history/2 → 正文 v2,恢复前的当前内容 v3 记为历史
mvc.perform(org.springframework.test.web.servlet.request.MockMvcRequestBuilders
.post("/api/v1/notes/" + note2 + "/history/2").session(session)
.with(org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf())
.contentType(MediaType.APPLICATION_JSON).content("{}"))
.andExpect(org.springframework.test.web.servlet.result.MockMvcResultMatchers.status().isOk())
.andExpect(org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath("$.body").value("v2"));
historyBody(session, note2, 4, "v3");
}
private void historyBody(MockHttpSession session, UUID id, long version, String expected) throws Exception {
mvc.perform(org.springframework.test.web.servlet.request.MockMvcRequestBuilders
.get("/api/v1/notes/" + id + "/history/" + version).session(session))
.andExpect(org.springframework.test.web.servlet.result.MockMvcResultMatchers.status().isOk())
.andExpect(org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath("$.body").value(expected));
}
}