Spaces:
Paused
Paused
Download Discordbot/database/db_manager.py from QwertOs/DiscordBot: direct link, hf CLI and curl.
- Browser
- Download file 3.02 kB
-
https://huggingface.co/spaces/QwertOs/DiscordBot/resolve/main/Discordbot/database/db_manager.py
- Command line
-
hf download hf://spaces/QwertOs/DiscordBot/Discordbot/database/db_manager.py
-
curl -L -o db_manager.py https://huggingface.co/spaces/QwertOs/DiscordBot/resolve/main/Discordbot/database/db_manager.py
3.02 kB
| import aiosqlite | |
| import structlog | |
| import os | |
| from config import settings | |
| logger = structlog.get_logger() | |
| class DatabaseManager: | |
| """数据库管理器,处理 SQLite 连接和表初始化""" | |
| def __init__(self): | |
| self.db_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), "bot.db") | |
| self.connection = None | |
| async def create_pool(self) -> aiosqlite.Connection: | |
| """创建数据库连接(SQLite 使用单连接)""" | |
| try: | |
| self.connection = await aiosqlite.connect(self.db_path) | |
| # 启用外键支持 | |
| await self.connection.execute("PRAGMA foreign_keys = ON") | |
| # 设置 WAL 模式以提高并发性能 | |
| await self.connection.execute("PRAGMA journal_mode = WAL") | |
| logger.info(f"SQLite 数据库连接成功: {self.db_path}") | |
| return self.connection | |
| except Exception as e: | |
| logger.error(f"创建数据库连接失败: {e}", exc_info=True) | |
| raise | |
| async def init_tables(self): | |
| """初始化数据库表""" | |
| if not self.connection: | |
| raise Exception("数据库连接未初始化") | |
| # 创建工单表 | |
| await self.connection.execute(""" | |
| CREATE TABLE IF NOT EXISTS tickets ( | |
| ticket_id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| user_id INTEGER NOT NULL, | |
| channel_id INTEGER NOT NULL UNIQUE, | |
| type TEXT NOT NULL, | |
| status TEXT DEFAULT 'open', | |
| created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, | |
| closed_at TIMESTAMP, | |
| closed_by INTEGER, | |
| reason TEXT | |
| ) | |
| """) | |
| # 创建用户验证表(为未来的 verification cog 准备) | |
| await self.connection.execute(""" | |
| CREATE TABLE IF NOT EXISTS user_verifications ( | |
| user_id INTEGER PRIMARY KEY, | |
| verified BOOLEAN DEFAULT 0, | |
| verified_at TIMESTAMP, | |
| verification_code TEXT, | |
| attempts INTEGER DEFAULT 0 | |
| ) | |
| """) | |
| # 创建用户等级表(为未来的 leveling cog 准备) | |
| await self.connection.execute(""" | |
| CREATE TABLE IF NOT EXISTS user_levels ( | |
| user_id INTEGER PRIMARY KEY, | |
| level INTEGER DEFAULT 1, | |
| experience INTEGER DEFAULT 0, | |
| messages_sent INTEGER DEFAULT 0, | |
| last_message_time TIMESTAMP | |
| ) | |
| """) | |
| await self.connection.commit() | |
| logger.info("数据库表初始化完成") | |
| async def close(self): | |
| """关闭数据库连接""" | |
| if self.connection: | |
| await self.connection.close() | |
| logger.info("数据库连接已关闭") | |
| # 全局数据库管理器实例 | |
| db_manager = DatabaseManager() | |