Skip to content

fix:修改了老版本和新版本的数据库兼容问题,修改了批量获取历史记录时要进行n次检测的问题 - #10

Merged
SXP-Simon merged 7 commits into
masterfrom
quick_image_creation
Jan 23, 2026
Merged

fix:修改了老版本和新版本的数据库兼容问题,修改了批量获取历史记录时要进行n次检测的问题#10
SXP-Simon merged 7 commits into
masterfrom
quick_image_creation

Conversation

@Li-shi-ling

@Li-shi-ling Li-shi-ling commented Jan 23, 2026

Copy link
Copy Markdown
Collaborator

运行示例
数据库兼容问题是在init_db里面加入了表的key检测,会自动删除老库生新表

新的init_db代码

    async def init_db(self):
        """初始化数据库,创建所有定义的表"""
        # 必须显式导入模型类,确保它们被注册到 SQLModel.metadata 中
        from ..models.tables import (  # noqa: F401
            LoveDailyRef,
            MessageOwnerIndex,
            UserCooldown,
        )

        # 1. 创建表
        async with self.engine.begin() as conn:
            await conn.run_sync(SQLModel.metadata.create_all)

            def _needs_refresh(sync_conn):
                inspector = inspect(sync_conn)
                if "user_cooldown" not in inspector.get_table_names():
                    return True
                existing_columns = {col["name"] for col in inspector.get_columns("user_cooldown")}
                required_columns = set(UserCooldown.__table__.columns.keys())
                if existing_columns != required_columns:
                    return True
                return False

            needs_refresh = await conn.run_sync(_needs_refresh)
            if needs_refresh:
                await conn.run_sync(lambda sync_conn: UserCooldown.__table__.drop(sync_conn, checkfirst=True))
                await conn.run_sync(lambda sync_conn: UserCooldown.__table__.create(sync_conn, checkfirst=True))

        # 2. SQLite 优化 PRAGMA
        async with self.engine.connect() as conn:
            await conn.execute(text("PRAGMA journal_mode=WAL"))
            await conn.execute(text("PRAGMA synchronous=NORMAL"))
            await conn.execute(text("PRAGMA cache_size=-20000"))
            await conn.execute(text("PRAGMA temp_store=MEMORY"))
            await conn.execute(text("PRAGMA mmap_size=134217728"))

            # 确认表名正确
            await conn.execute(
                text("CREATE INDEX IF NOT EXISTS idx_message_id ON message_owner_index(message_id)")
            )

            await conn.execute(text("PRAGMA optimize"))

今日人设图可以正常运行
学习接口也可以正常运行
f84e2813b18e356f24d2a57cb1ba77b4

@sourcery-ai

sourcery-ai Bot commented Jan 23, 2026

Copy link
Copy Markdown

Reviewer's Guide

Updates database initialization for backward-compatible schema refresh, optimizes bulk history backfill to avoid per-message DB lookups and duplicates, and parallelizes avatar downloads in the renderer for better performance, plus a minor UX tweak to the history retrieval command output.

Sequence diagram for optimized history backfill and batch message_id existence check

sequenceDiagram
    actor User
    participant Bot as MessageHandler
    participant Repo as Repository
    participant DB as Database

    User->>Bot: backfill_from_history(group_id, messages)
    Bot->>Bot: sort messages by time
    Bot->>Bot: collect all_msg_ids from messages
    Bot->>Repo: filter_existing_message_ids(all_msg_ids)
    Repo->>DB: get_session()
    Repo->>DB: select(MessageOwnerIndex.message_id).where(message_id.in_(all_msg_ids))
    DB-->>Repo: existing message_id rows
    Repo-->>Bot: existed_msg_ids set

    Bot->>Bot: init seen_msg_ids set
    loop for each msg in sorted_messages
        Bot->>Bot: validate date and extract msg_id
        alt msg_id already in seen_msg_ids
            Bot->>Bot: skip duplicated input message
        else msg_id not in seen_msg_ids
            Bot->>Bot: add msg_id to seen_msg_ids
            alt msg_id in existed_msg_ids
                Bot->>Bot: update group_last_time
                Bot->>Bot: continue (skip DB lookup)
            else msg_id not in existed_msg_ids
                Bot->>Repo: get_message_owner(msg_id)
                Repo->>DB: query MessageOwnerIndex by msg_id
                DB-->>Repo: owner or None
                Repo-->>Bot: owner or None
                Bot->>Bot: process message, update history and topic
            end
        end
    end
Loading

Updated class diagram for database, repository, handler, and renderer changes

classDiagram
    class Database {
        +engine
        +init_db() async
    }

    class UserCooldown {
        +user_id: str
        +group_id: str
        +created_at
        +updated_at
    }

    class MessageOwnerIndex {
        +message_id: str
        +user_id: str
        +group_id: str
        +created_at
    }

    class Repository {
        +db: Database
        +check_and_update_cooldown(user_id: str, group_id: str) async
        +batch_backfill(group_id: str, messages: list[dict]) async
        +filter_existing_message_ids(message_ids: list[str]) async set~str~
        +get_message_owner(message_id: str) async
    }

    class MessageHandler {
        +repo: Repository
        +backfill_from_history(group_id: str, messages: list[dict]) async
        +retrieve_historical_records(event: AiocqhttpMessageEvent) async
    }

    class Renderer {
        +theme_manager
        +env
        +render(data: dict, theme_name: str) async str
    }

    Database o-- UserCooldown
    Database o-- MessageOwnerIndex
    Repository --> Database
    MessageHandler --> Repository
    MessageHandler --> Renderer

    note for Database "init_db creates tables, checks user_cooldown schema, recreates if mismatched, applies SQLite PRAGMA and index creation"
    note for Repository "filter_existing_message_ids performs a single batched SELECT of existing message_id values"
    note for MessageHandler "backfill_from_history now batch-checks existing messages and deduplicates by message_id"
    note for Renderer "render uses shared _fetch_avatar and asyncio.gather to parallelize avatar downloads"
Loading

Class diagram for init_db schema compatibility logic

classDiagram
    class Database {
        +engine
        +init_db() async
        -_needs_refresh(sync_conn) bool
    }

    class SQLModelMetadata {
        +create_all(bind)
    }

    class Inspector {
        +get_table_names() list~str~
        +get_columns(table_name: str) list
    }

    class UserCooldown {
        +__table__
    }

    class Table {
        +columns: dict
        +drop(bind, checkfirst: bool)
        +create(bind, checkfirst: bool)
    }

    Database --> SQLModelMetadata : uses
    Database --> Inspector : uses
    Database --> UserCooldown : manages schema
    UserCooldown --> Table : has

    note for Database "init_db creates all tables, inspects user_cooldown, and drops/recreates the table when columns do not match the model, ensuring compatibility between old and new schemas"
Loading

File-Level Changes

Change Details Files
Make database initialization compatible with old/new versions of the UserCooldown table and ensure index creation on message_owner_index.
  • After creating all tables, inspect the existing user_cooldown table and compare its columns to the model definition.
  • If the table is missing or its columns do not match, drop and recreate only the user_cooldown table.
  • Run SQLite PRAGMA optimizations in a separate connection after schema setup.
  • Ensure the idx_message_id index is created on message_owner_index(message_id) with a simplified CREATE INDEX statement.
src/persistence/database.py
Parallelize avatar fetching in the visual renderer to avoid sequential HTTP calls and improve performance.
  • Refactor main avatar handling to use a local async helper _fetch_avatar that wraps HTTP fetch and base64 encoding with a default fallback.
  • Change deep_dive evidence dialogue avatar processing to collect HTTP fetch tasks and run them with asyncio.gather for parallel downloads.
  • Skip dialogues that already have base64 avatars or missing user_id, and backfill avatar_url with fetch results or the default avatar.
  • Keep subsequent template loading and rendering logic unchanged apart from comments.
src/visual/renderer.py
Optimize historical backfill by deduplicating message_ids and switching from per-message existence checks to a single batch query.
  • Add a new repository method filter_existing_message_ids to select existing MessageOwnerIndex.message_id values in bulk using an IN query.
  • In backfill_from_history, pre-collect all message_ids from the sorted history and call filter_existing_message_ids once to get the set of existing IDs.
  • Introduce a seen_msg_ids set to deduplicate messages within the input list itself before processing.
  • Replace the per-message get_message_owner call with a membership check against the pre-fetched existed_msg_ids set and maintain existing group_last_time update behavior.
  • Minor formatting fix to the topic threshold condition for readability.
src/persistence/repo.py
src/handlers/message_handler.py
Fix cooldown query predicate construction for better correctness/compatibility.
  • Wrap the UserCooldown.user_id and group_id equality filters in an and_() expression when building the select statement.
  • Keep the rest of the cooldown update logic unchanged.
src/persistence/repo.py
Adjust user-facing message when starting history retrieval.
  • Change the plain text feedback when starting to retrieve historical records to include a coffee cup marker for better UX.
  • Leave the rest of the command handling logic as-is.
main.py

Possibly linked issues

  • #[Bug]在调用插件 astrbot_plugin_love_formula 的处理函数 cmd_love_profile 时出现异常: The PR detects and recreates an outdated user_cooldown table, fixing the missing group_id column crash reported.

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 2 issues, and left some high level feedback:

  • In renderer.render, _fetch_avatar is defined inside the main-avatar if avatar_url and avatar_url.startswith("http") block but is later used for deep_dive avatars unconditionally, which will raise a NameError when avatar_url is absent or not http; move _fetch_avatar to a broader scope so it’s always defined.
  • In backfill_from_history, all_msg_ids are converted to str before calling filter_existing_message_ids, but later comparisons use the raw msg_id (possibly int) against existed_msg_ids (set of str), so normalize msg_id to string before membership checks to ensure deduplication works correctly.
  • The new _needs_refresh logic in init_db drops and recreates the user_cooldown table whenever the column set changes, which may cause unintended data loss; consider a more targeted migration (e.g., ALTER TABLE) or at least narrowing the condition to only expected schema changes.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In `renderer.render`, `_fetch_avatar` is defined inside the main-avatar `if avatar_url and avatar_url.startswith("http")` block but is later used for deep_dive avatars unconditionally, which will raise a NameError when `avatar_url` is absent or not http; move `_fetch_avatar` to a broader scope so it’s always defined.
- In `backfill_from_history`, `all_msg_ids` are converted to `str` before calling `filter_existing_message_ids`, but later comparisons use the raw `msg_id` (possibly int) against `existed_msg_ids` (set of str), so normalize `msg_id` to string before membership checks to ensure deduplication works correctly.
- The new `_needs_refresh` logic in `init_db` drops and recreates the `user_cooldown` table whenever the column set changes, which may cause unintended data loss; consider a more targeted migration (e.g., ALTER TABLE) or at least narrowing the condition to only expected schema changes.

## Individual Comments

### Comment 1
<location> `src/visual/renderer.py:39-48` </location>
<code_context>
+                async def _fetch_avatar(url: str) -> str:
</code_context>

<issue_to_address>
**issue (bug_risk):** _fetch_avatar is only defined when main avatar_url is http, but used unconditionally for deep_dive avatars

If `avatar_url` is missing or not an HTTP URL, `_fetch_avatar` will be undefined when the deep_dive avatars are processed, leading to a runtime `NameError`. Define `_fetch_avatar` once in a broader scope (e.g., at the start of the `async with aiohttp.ClientSession()` block or as a private method) so it’s always available before use.
</issue_to_address>

### Comment 2
<location> `src/visual/renderer.py:61-62` </location>
<code_context>
-                        if dialog.get("avatar_url") and dialog["avatar_url"].startswith(
-                            "data:"
-                        ):
+                        # 跳过已经是 base64 或无 uid 的
+                        if dialog.get("avatar_url", "").startswith("data:") or not uid:
                             continue
-
</code_context>

<issue_to_address>
**question (bug_risk):** Dialogs without uid no longer get DEFAULT_AVATAR assigned

Previously, `not uid` dialogs explicitly had `dialog["avatar_url"] = DEFAULT_AVATAR` in the `else` branch. Now they’re skipped via `if ... or not uid: continue`, so they keep whatever `avatar_url` they had (possibly empty/missing). If you still want a default avatar when `uid` is missing, you’ll need to preserve that explicit `DEFAULT_AVATAR` assignment for `not uid` cases.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread src/visual/renderer.py Outdated
Comment thread src/visual/renderer.py
@SXP-Simon

Copy link
Copy Markdown
Owner

LGTM

其他的问题根据 AI review 建议改改

@Li-shi-ling

Li-shi-ling commented Jan 23, 2026

Copy link
Copy Markdown
Collaborator Author

LGTM

其他的问题根据 AI review 建议改改

批量过滤哪里,表里面就是str,所以转变为str然后查没问题,这ai看代码不看全的
表的结构message_id为str类型

class MessageOwnerIndex(SQLModel, table=True):
    """消息归属索引,用于将后续的 Reaction 归因到具体的发送者"""

    __tablename__ = "message_owner_index"
    __table_args__ = {"extend_existing": True}

    message_id: str = Field(primary_key=True)
    user_id: str
    group_id: str
    timestamp: float  # 时间戳

message_id在表里面查

        # 提前收集 message_id,并批量查询已存在的 message
        all_msg_ids = [
            str(m.get("message_id"))
            for m in sorted_messages
            if m.get("message_id")
        ]
        existed_msg_ids = await self.repo.filter_existing_message_ids(all_msg_ids)

新增加的数据库查重函数

    async def filter_existing_message_ids(
            self, message_ids: list[str]
    ) -> set[str]:
        """
        批量查询已存在的 message_id
        返回:已存在的 message_id 集合
        """
        if not message_ids:
            return set()

        async with self.db.get_session() as session:
            message_id_col = cast(ColumnElement[str], MessageOwnerIndex.message_id)
            stmt = select(MessageOwnerIndex.message_id).where(
                message_id_col.in_(message_ids)
            )
            result = await session.execute(stmt)
            return {row[0] for row in result.all()}

去重和判断是否在表里面的逻辑

            msg_id = str(msg.get("message_id", ""))
            if not msg_id:
                continue

            # message_id 去重
            if msg_id in seen_msg_ids:
                continue
            seen_msg_ids.add(msg_id)

            # 使用批量查询结果判断是否已存在
            if msg_id in existed_msg_ids:
                group_last_time = msg_time
                continue

老表清理那里,老表没有群聊id字段迁移到新表甚至有可能会导致新表出现奇怪的问题

头像异步函数哪里确实有问题,我把函数定义移出去了,现在覆盖所有代码了

@SXP-Simon SXP-Simon left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@SXP-Simon
SXP-Simon merged commit 53d163a into master Jan 23, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants