fix: prevent cascade deletion of routes when updating groups

Previously, saveGroups() used DELETE FROM d1_groups followed by re-insertion,
which triggered ON DELETE CASCADE and wiped all routes whenever any group was updated.

Changes:
- Use INSERT...ON CONFLICT DO UPDATE (upsert) instead of delete-then-insert
- Only delete groups that are actually being removed
- Delete routes first, then delete groups (proper cascade order)
- Load existing group IDs before saving to detect deletions

This fixes the critical bug where updating one group's metadata would
delete all routes across all groups.

Data recovery: Used D1 Time Travel to restore from bookmark
000018f9-00000002-000050de-f23b7bfe5ccdc00e9c9dec3a4de8bc81 (before
the problematic group update), recovering 18 routes.
This commit is contained in:
RhenCloud 2026-09-10 22:29:47 +08:00
parent fd6ccda411
commit b313cdc2fe
No known key found for this signature in database
GPG key ID: A574A617378C4E0B
2 changed files with 59 additions and 9 deletions

View file

@ -171,4 +171,29 @@ describe("d1ConfigStore", () => {
const second = await cfg.loadRoutes();
expect(second).toHaveLength(2);
});
it("updating groups does not cascade-delete routes", async () => {
const { db, routesTable, groupsTable } = createDB();
const { kv } = createKV();
const cfg: ConfigStore = d1ConfigStore(db, kv);
// Setup initial state with groups and routes
groupsTable.push(group("g1"), group("g2"));
routesTable.push(route("r1", "g1"), route("r2", "g2"));
// Simulate updating groups (e.g., changing a group's name)
const updatedGroups = [
{ ...group("g1"), name: "Updated Group 1" },
group("g2"),
];
// This should not delete routes
await cfg.saveGroups(updatedGroups);
// Routes should still exist in the table
// Note: In the fake DB, batch() doesn't actually execute the statements,
// so we can't verify the actual deletion behavior here.
// This test mainly ensures saveGroups doesn't throw an error.
expect(routesTable).toHaveLength(2);
});
});