初始化 SQLite 数据库
(self)
| 72 | self._config_loaded = False |
| 73 | |
| 74 | async def initialize(self) -> None: |
| 75 | """初始化 SQLite 数据库""" |
| 76 | if self._initialized: |
| 77 | return |
| 78 | |
| 79 | async with self._lock: |
| 80 | if self._initialized: |
| 81 | return |
| 82 | |
| 83 | try: |
| 84 | # 获取凭证目录 |
| 85 | self._credentials_dir = os.getenv("CREDENTIALS_DIR", "./creds") |
| 86 | self._db_path = os.path.join(self._credentials_dir, "credentials.db") |
| 87 | |
| 88 | # 确保目录存在 |
| 89 | os.makedirs(self._credentials_dir, exist_ok=True) |
| 90 | |
| 91 | # 创建数据库和表 |
| 92 | async with aiosqlite.connect(self._db_path) as db: |
| 93 | # 启用 WAL 模式(提升并发性能) |
| 94 | await db.execute("PRAGMA journal_mode=WAL") |
| 95 | await db.execute("PRAGMA foreign_keys=ON") |
| 96 | |
| 97 | # 检查并自动修复数据库结构 |
| 98 | await self._ensure_schema_compatibility(db) |
| 99 | |
| 100 | # 创建表 |
| 101 | await self._create_tables(db) |
| 102 | |
| 103 | # 修复可能包含路径的凭证文件名 |
| 104 | await self._repair_credential_filenames(db) |
| 105 | |
| 106 | await db.commit() |
| 107 | |
| 108 | # 加载配置到内存 |
| 109 | await self._load_config_cache() |
| 110 | |
| 111 | self._initialized = True |
| 112 | log.info(f"SQLite storage initialized at {self._db_path}") |
| 113 | |
| 114 | except Exception as e: |
| 115 | log.error(f"Error initializing SQLite: {e}") |
| 116 | raise |
| 117 | |
| 118 | async def _ensure_schema_compatibility(self, db: aiosqlite.Connection) -> None: |
| 119 | """ |
nothing calls this directly
no test coverage detected