Skip to content

armgit / peach

Public Imported from GitHub
0

Peach: Local-first video metadata scraper and media manager.

fix(ledger): 删来源时连带清子表,别名合并只拦这次新增的外键违规

longmeidao1e91de0ed0e8
diff --git a/migrations/0039_orphan_source_rows.sql b/migrations/0039_orphan_source_rows.sql
new file mode 100644
index 000000000..00f797e0f
--- /dev/null
+++ b/migrations/0039_orphan_source_rows.sql
@@ -0,0 +1,15 @@
+-- 清掉指向已删来源的子表行。
+--
+-- 关注源与订阅源的删除入口此前只删来源那一行,指望表上的 `ON DELETE CASCADE` /
+-- `SET NULL` 连带处理子表;可服务的连接从不打开 `PRAGMA foreign_keys`,这些声明一次也
+-- 没执行过。删过来源的库因此留着孤儿条目,全库 `foreign_key_check` 不为 0,补别名后继
+-- 合并实体时按这个结果回滚。删除入口现在显式处理子表,这里只补存量。
+--
+-- 迁移在外键打开时运行:删 `follow_item` 会连带删它的播放记录,下面那句只兜住此前就
+-- 已经没有主人的播放记录。
+DELETE FROM follow_item WHERE source_id NOT IN (SELECT id FROM follow_source);
+DELETE FROM follow_playback WHERE follow_item_id NOT IN (SELECT id FROM follow_item);
+
+DELETE FROM feed_item WHERE source_id NOT IN (SELECT id FROM feed_source);
+UPDATE feed_discovery SET source_id=NULL
+ WHERE source_id IS NOT NULL AND source_id NOT IN (SELECT id FROM feed_source);
diff --git a/src/peach/feeds.py b/src/peach/feeds.py
index c161cef7f..3e55fb2ed 100644
--- a/src/peach/feeds.py
+++ b/src/peach/feeds.py
@@ -264,7 +264,15 @@ def entity_following(connection: sqlite3.Connection, entity_id: int) -> bool:
def remove_source(connection: sqlite3.Connection, source_id: int) -> None:
- connection.execute("DELETE FROM feed_source WHERE id=?", (int(source_id),))
+ """删掉一条订阅源,连同它的条目;发现过的作品留着,只断开来源。
+
+ 子表按建表时声明的 `ON DELETE CASCADE` / `SET NULL` 显式处理:连接的
+ `PRAGMA foreign_keys` 是 OFF,库自己不会做。
+ """
+ source_id = int(source_id)
+ connection.execute("DELETE FROM feed_item WHERE source_id=?", (source_id,))
+ connection.execute("UPDATE feed_discovery SET source_id=NULL WHERE source_id=?", (source_id,))
+ connection.execute("DELETE FROM feed_source WHERE id=?", (source_id,))
def set_enabled(connection: sqlite3.Connection, source_id: int, enabled: bool) -> None:
diff --git a/src/peach/follow_store.py b/src/peach/follow_store.py
index 967213573..66896e448 100644
--- a/src/peach/follow_store.py
+++ b/src/peach/follow_store.py
@@ -585,8 +585,17 @@ class FollowStore:
哪张表、要不要连带清理,属于这一层的知识。写成 Web 处理函数里一句裸
DELETE 的话,换存储结构时得去处理函数里找 SQL。
+
+ 条目与播放记录由这里显式删:连接的 `PRAGMA foreign_keys` 是 OFF,表上的
+ `ON DELETE CASCADE` 不会执行。留下的孤儿条目让全库 `foreign_key_check` 不为 0,
+ 补别名后继合并实体时照这个结果回滚,每一次合并都失败。
"""
- self._connect().execute("DELETE FROM follow_source WHERE id=?", (source_id,))
+ connection = self._connect()
+ connection.execute(
+ "DELETE FROM follow_playback WHERE follow_item_id IN"
+ " (SELECT id FROM follow_item WHERE source_id=?)", (source_id,))
+ connection.execute("DELETE FROM follow_item WHERE source_id=?", (source_id,))
+ connection.execute("DELETE FROM follow_source WHERE id=?", (source_id,))
def record_error(self, source_id: int, message: str,
moment: datetime | None = None, *, status: str = "error") -> None:
diff --git a/src/peach/performer_alias_followup.py b/src/peach/performer_alias_followup.py
index b433a2179..502dedb9e 100644
--- a/src/peach/performer_alias_followup.py
+++ b/src/peach/performer_alias_followup.py
@@ -712,7 +712,11 @@ def merge_one_person(contract, entity_id: int, rows: list[dict], batch: str) ->
只在被占用的写法全指向同一条另外的实体时合:指向两条以上,页上的人比账本里多,
那不是一对。保留作品多的一侧;一样多保留页上主名那一侧,再一样保留先登记的。
合并不可逆,先按 `peach-ledger-write` 把账本备到数据库目录,托盘按备份保留规则清退;
- 合并后外键校验不为 0 就抛错让事务回滚。占用行改判成「合并」。
+ 合并后外键校验多出违规就抛错让事务回滚。占用行改判成「合并」。
+
+ 校验比的是合并前后的差:合并之前库里就有的违规不是这次合并造成的。按全库绝对数判
+ 的话,别处一条孤儿行就让所有合并一起回滚——本机曾因一条已删关注源留下的条目,
+ 同一天六次合并全部失败。
"""
taken = [row for row in rows if row["action"] == TAKEN and row["site"] in MERGE_SITES]
owners = {int(row.get("owner") or 0) for row in taken} - {0}
@@ -736,9 +740,11 @@ def merge_one_person(contract, entity_id: int, rows: list[dict], batch: str) ->
with contract.database.write_transaction() as connection:
if _names(connection, source_id) is None or _names(connection, target_id) is None:
return None
+ existing = {tuple(row) for row in connection.execute("PRAGMA foreign_key_check")}
moved = merge_entity(connection, target_id=target_id, source_id=source_id,
source_name=absorbed, alias_source=f"merge:{batch}")
- broken = connection.execute("PRAGMA foreign_key_check").fetchall()
+ broken = [row for row in connection.execute("PRAGMA foreign_key_check")
+ if tuple(row) not in existing]
if broken:
raise RuntimeError(f"合并实体 {source_id} 进 {target_id} 后外键校验有 {len(broken)} 条违规")
contract.cache_bust()
diff --git a/tests/test_feeds.py b/tests/test_feeds.py
index 90f41cb98..a423c4353 100644
--- a/tests/test_feeds.py
+++ b/tests/test_feeds.py
@@ -280,15 +280,16 @@ class ShellBoundaryTest(unittest.TestCase):
self.assertNotIn("feed_item", ASSET_REFERENCE_TABLES)
def test_deleting_a_source_takes_its_items_but_leaves_the_shell(self):
- # 壳是「这个番号还没入库」,它不该随着某个订阅被删而消失。
+ # 壳是「这个番号还没入库」,它不该随着某个订阅被删而消失。连接和服务一样不开
+ # 外键:子表靠 `remove_source` 自己处理,不靠建表时的 CASCADE 声明。
with self.database.write_transaction() as connection:
- connection.execute("PRAGMA foreign_keys=ON")
feeds.remove_source(connection, self._poll_once(connection))
with self.database.read_connection() as connection:
self.assertEqual(connection.execute(
"SELECT count(*) FROM feed_item").fetchone()[0], 0)
- self.assertEqual(connection.execute(
- "SELECT count(*) FROM feed_discovery").fetchone()[0], 2)
+ self.assertEqual(tuple(connection.execute(
+ "SELECT count(*), count(source_id) FROM feed_discovery").fetchone()), (2, 0))
+ self.assertEqual(connection.execute("PRAGMA foreign_key_check").fetchall(), [])
if __name__ == "__main__": # pragma: no cover
diff --git a/tests/test_follow_store.py b/tests/test_follow_store.py
index efc423865..094d0439f 100644
--- a/tests/test_follow_store.py
+++ b/tests/test_follow_store.py
@@ -1047,6 +1047,16 @@ class SourceRemovalTests(_StoreCase):
self.store.remove_source(source_id)
self.assertEqual([row["id"] for row in self.store.sources()], [other])
+ def test_removing_a_source_takes_its_items_and_their_playback(self):
+ source_id = self._source()
+ self.store.record(source_id, _fetch([_candidate("1", "Fiona")]), moment=MOMENT)
+ self.store.record_playback(self.store.items()[0].id, MOMENT)
+ self.store.remove_source(source_id)
+ for table in ("follow_item", "follow_playback"):
+ self.assertEqual(self.connection.execute(
+ f"SELECT count(*) FROM {table}").fetchone()[0], 0, table)
+ self.assertEqual(self.connection.execute("PRAGMA foreign_key_check").fetchall(), [])
+
class PlaybackTests(_StoreCase):
def _item(self):
diff --git a/tests/test_migrations.py b/tests/test_migrations.py
index 55413e55c..66619bf67 100644
--- a/tests/test_migrations.py
+++ b/tests/test_migrations.py
@@ -25,7 +25,7 @@ class MigrationTests(unittest.TestCase):
backup = self.root / "before.db"
done = upgrade(self.db, MIGRATIONS, backup)
self.assertEqual([m.version for m in done],
- ["0000", "0001", "0002", "0003", "0004", "0005", "0006", "0007", "0008", "0009", "0010", "0011", "0012", "0013", "0014", "0015", "0016", "0017", "0018", "0019", "0020", "0021", "0022", "0023", "0024", "0025", "0026", "0027", "0028", "0029", "0030", "0031", "0032", "0033", "0034", "0035", "0036", "0037", "0038"])
+ ["0000", "0001", "0002", "0003", "0004", "0005", "0006", "0007", "0008", "0009", "0010", "0011", "0012", "0013", "0014", "0015", "0016", "0017", "0018", "0019", "0020", "0021", "0022", "0023", "0024", "0025", "0026", "0027", "0028", "0029", "0030", "0031", "0032", "0033", "0034", "0035", "0036", "0037", "0038", "0039"])
self.assertTrue(backup.exists())
con = sqlite3.connect(self.db)
tables = {row[0] for row in con.execute(
@@ -43,7 +43,7 @@ class MigrationTests(unittest.TestCase):
"asset_tag_preference", "asset_search", "follow_playback",
"genre_decision", "asset_subtitle", "task_run", "performer_profile", "code_sample_image",
"schema_migration"} <= tables)
- self.assertEqual(versions, ["0000", "0001", "0002", "0003", "0004", "0005", "0006", "0007", "0008", "0009", "0010", "0011", "0012", "0013", "0014", "0015", "0016", "0017", "0018", "0019", "0020", "0021", "0022", "0023", "0024", "0025", "0026", "0027", "0028", "0029", "0030", "0031", "0032", "0033", "0034", "0035", "0036", "0037", "0038"])
+ self.assertEqual(versions, ["0000", "0001", "0002", "0003", "0004", "0005", "0006", "0007", "0008", "0009", "0010", "0011", "0012", "0013", "0014", "0015", "0016", "0017", "0018", "0019", "0020", "0021", "0022", "0023", "0024", "0025", "0026", "0027", "0028", "0029", "0030", "0031", "0032", "0033", "0034", "0035", "0036", "0037", "0038", "0039"])
self.assertEqual(upgrade(self.db, MIGRATIONS), [])
self.assertEqual(plan(self.db, MIGRATIONS)[1], [])
@@ -324,8 +324,9 @@ class MigrationTests(unittest.TestCase):
base_migrations.mkdir()
for path in sorted(MIGRATIONS.glob("*.sql")):
# 0024 重建 follow_playback,必须与建表的 0022 一起排除;0038 给每张表挂
- # 版本号触发器,被排除的迁移建的表这时还不存在,它也要等到后面一起应用。
- if not path.name.startswith(("0020_", "0021_", "0022_", "0024_", "0038_")):
+ # 版本号触发器、0039 清 follow_playback 的孤儿行,被排除的迁移建的表这时还
+ # 不存在,它们也要等到后面一起应用。
+ if not path.name.startswith(("0020_", "0021_", "0022_", "0024_", "0038_", "0039_")):
shutil.copyfile(path, base_migrations / path.name)
sqlite3.connect(self.db).close()
upgrade(self.db, base_migrations)
@@ -861,5 +862,50 @@ class ExternalRefUniquenessTests(unittest.TestCase):
"SELECT count(*) FROM entity_external_ref").fetchone()[0], 0)
+class OrphanSourceRowsTests(unittest.TestCase):
+ """0039:删来源时没跟着走的子表行被清掉,还有主人的原样留下。"""
+
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.tmp.cleanup)
+ self.root = Path(self.tmp.name).resolve()
+ self.db = self.root / "ledger.db"
+ below = self.root / "below-0039"
+ below.mkdir()
+ for path in sorted(MIGRATIONS.glob("*.sql")):
+ if path.name < "0039":
+ shutil.copyfile(path, below / path.name)
+ sqlite3.connect(self.db).close()
+ upgrade(self.db, below)
+ connection = sqlite3.connect(self.db)
+ # 和服务的连接一样不开外键,才造得出生产上那种孤儿行。
+ connection.executescript("""
+ INSERT INTO follow_source(id,provider,ref,label,url,created_at,updated_at)
+ VALUES(1,'rule34xxx','kept','kept','https://x.test/kept','t','t');
+ INSERT INTO follow_item(id,source_id,external_id,title,release_key,first_seen_at,last_seen_at)
+ VALUES(10,1,'a','kept','a','t','t'), (11,106,'b','orphan','b','t','t');
+ INSERT INTO follow_playback(follow_item_id,play_count) VALUES(10,1),(11,1),(12,1);
+ INSERT INTO feed_source(id,kind,url,created_at) VALUES(1,'javdb_actor','https://j.test/1','t');
+ INSERT INTO feed_item(id,source_id,item_key,first_seen) VALUES(20,1,'k','t'),(21,9,'k','t');
+ INSERT INTO feed_discovery(id,code,source_id,discovered_at)
+ VALUES(30,'ABC-001',1,'t'),(31,'ABC-002',9,'t');
+ """)
+ connection.commit()
+ connection.close()
+
+ def test_rows_of_removed_sources_are_cleared(self):
+ upgrade(self.db, MIGRATIONS)
+ connection = sqlite3.connect(self.db)
+ self.addCleanup(connection.close)
+ self.assertEqual(connection.execute("PRAGMA foreign_key_check").fetchall(), [])
+ self.assertEqual([row[0] for row in connection.execute("SELECT id FROM follow_item")], [10])
+ self.assertEqual([row[0] for row in connection.execute(
+ "SELECT follow_item_id FROM follow_playback")], [10])
+ self.assertEqual([row[0] for row in connection.execute("SELECT id FROM feed_item")], [20])
+ # 发现过的作品是「这个番号还没入库」,不随订阅消失,只断开来源。
+ self.assertEqual(connection.execute(
+ "SELECT id,source_id FROM feed_discovery ORDER BY id").fetchall(), [(30, 1), (31, None)])
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/tests/test_performer_alias_followup.py b/tests/test_performer_alias_followup.py
index e75b2cf40..20c79c71b 100644
--- a/tests/test_performer_alias_followup.py
+++ b/tests/test_performer_alias_followup.py
@@ -365,6 +365,21 @@ class LandingTests(Case):
with self.database.read_connection() as connection:
self.assertEqual(connection.execute("PRAGMA foreign_key_check").fetchall(), [])
+ def test_an_unrelated_orphan_row_does_not_block_a_merge(self):
+ """库里早有一条与实体无关的违规行时,合并照样落;那条行原样留着。"""
+ momoka = self.entity("神山ももか")
+ other = self.entity("雫つむぎ")
+ with self.database.write_transaction(notify=False) as connection:
+ connection.execute(
+ "INSERT INTO follow_item(id,source_id,external_id,title,release_key,"
+ "first_seen_at,last_seen_at) VALUES(1,999,'x','orphan','x',?,?)", (STAMP, STAMP))
+ summary = self.run_followup(momoka)
+ self.assertEqual(summary["merged"]["from"], other)
+ self.assertFalse(self.exists(other))
+ with self.database.read_connection() as connection:
+ self.assertEqual([tuple(row)[:3] for row in connection.execute("PRAGMA foreign_key_check")],
+ [("follow_item", 1, "follow_source")])
+
def exists(self, entity_id: int) -> bool:
with self.database.read_connection() as connection:
return connection.execute("SELECT 1 FROM entity WHERE id=?", (entity_id,)).fetchone() is not None