File size: 3,019 Bytes
2fd3032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
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()