diff --git a/blog/bp/blog/ghost/ghost_sync.py b/blog/bp/blog/ghost/ghost_sync.py index 20c8435..a1717dd 100644 --- a/blog/bp/blog/ghost/ghost_sync.py +++ b/blog/bp/blog/ghost/ghost_sync.py @@ -185,9 +185,11 @@ async def _upsert_post(sess: AsyncSession, gp: Dict[str, Any], author_map: Dict[ obj.user_id = user_id await sess.flush() - # Rebuild post_authors + post_tags inside no_autoflush to prevent - # premature INSERT from query-invoked autoflush. - async with sess.no_autoflush: + # Rebuild post_authors + post_tags with synchronize_session to keep + # identity map consistent and prevent autoflush IntegrityError. + old_autoflush = sess.autoflush + sess.autoflush = False + try: # Delete + re-add post_authors (dedup for Ghost duplicate authors) await sess.execute( delete(PostAuthor).where(PostAuthor.post_id == obj.id), @@ -212,7 +214,9 @@ async def _upsert_post(sess: AsyncSession, gp: Dict[str, Any], author_map: Dict[ seen_tags.add(tt.id) sess.add(PostTag(post_id=obj.id, tag_id=tt.id, sort_order=idx)) - await sess.flush() + await sess.flush() + finally: + sess.autoflush = old_autoflush # Auto-create PageConfig for pages if obj.is_page: