| 42 | |
| 43 | |
| 44 | class SQLiteDatabase(BaseDatabase): |
| 45 | def __init__(self, db_path: str) -> None: |
| 46 | self.db_path = db_path |
| 47 | self.DATABASE_URL = f"sqlite+aiosqlite:///{db_path}" |
| 48 | self.inited = False |
| 49 | super().__init__() |
| 50 | |
| 51 | async def initialize(self) -> None: |
| 52 | """Initialize the database by creating tables if they do not exist.""" |
| 53 | async with self.engine.begin() as conn: |
| 54 | await conn.run_sync(SQLModel.metadata.create_all) |
| 55 | await conn.execute(text("PRAGMA journal_mode=WAL")) |
| 56 | await conn.execute(text("PRAGMA busy_timeout=30000")) |
| 57 | await conn.execute(text("PRAGMA synchronous=NORMAL")) |
| 58 | await conn.execute(text("PRAGMA cache_size=20000")) |
| 59 | await conn.execute(text("PRAGMA temp_store=MEMORY")) |
| 60 | await conn.execute(text("PRAGMA mmap_size=134217728")) |
| 61 | await conn.execute(text("PRAGMA optimize")) |
| 62 | # 确保 personas 表有 folder_id、sort_order、skills 列(前向兼容) |
| 63 | await self._ensure_persona_folder_columns(conn) |
| 64 | await self._ensure_persona_skills_column(conn) |
| 65 | await self._ensure_persona_custom_error_message_column(conn) |
| 66 | await self._ensure_platform_message_history_checkpoint_column(conn) |
| 67 | await conn.commit() |
| 68 | |
| 69 | async def _ensure_persona_folder_columns(self, conn) -> None: |
| 70 | """确保 personas 表有 folder_id 和 sort_order 列。 |
| 71 | |
| 72 | 这是为了支持旧版数据库的平滑升级。新版数据库通过 SQLModel |
| 73 | 的 metadata.create_all 自动创建这些列。 |
| 74 | """ |
| 75 | result = await conn.execute(text("PRAGMA table_info(personas)")) |
| 76 | columns = {row[1] for row in result.fetchall()} |
| 77 | |
| 78 | if "folder_id" not in columns: |
| 79 | await conn.execute( |
| 80 | text( |
| 81 | "ALTER TABLE personas ADD COLUMN folder_id VARCHAR(36) DEFAULT NULL" |
| 82 | ) |
| 83 | ) |
| 84 | if "sort_order" not in columns: |
| 85 | await conn.execute( |
| 86 | text("ALTER TABLE personas ADD COLUMN sort_order INTEGER DEFAULT 0") |
| 87 | ) |
| 88 | |
| 89 | async def _ensure_persona_skills_column(self, conn) -> None: |
| 90 | """确保 personas 表有 skills 列。 |
| 91 | |
| 92 | 这是为了支持旧版数据库的平滑升级。新版数据库通过 SQLModel |
| 93 | 的 metadata.create_all 自动创建这些列。 |
| 94 | """ |
| 95 | result = await conn.execute(text("PRAGMA table_info(personas)")) |
| 96 | columns = {row[1] for row in result.fetchall()} |
| 97 | |
| 98 | if "skills" not in columns: |
| 99 | await conn.execute(text("ALTER TABLE personas ADD COLUMN skills JSON")) |
| 100 | |
| 101 | async def _ensure_persona_custom_error_message_column(self, conn) -> None: |
no outgoing calls