PostgreSQL 数据库管理器
| 14 | |
| 15 | |
| 16 | class PSQLManager: |
| 17 | """PostgreSQL 数据库管理器""" |
| 18 | |
| 19 | # 状态字段常量 |
| 20 | STATE_FIELDS = { |
| 21 | "error_codes", |
| 22 | "error_messages", |
| 23 | "disabled", |
| 24 | "last_success", |
| 25 | "user_email", |
| 26 | "model_cooldowns", |
| 27 | "preview", |
| 28 | "tier", |
| 29 | "enable_credit", |
| 30 | } |
| 31 | |
| 32 | def __init__(self): |
| 33 | self._dsn: Optional[str] = None |
| 34 | self._pool: Optional[asyncpg.Pool] = None |
| 35 | self._initialized = False |
| 36 | self._lock = asyncio.Lock() |
| 37 | |
| 38 | # 内存配置缓存 |
| 39 | self._config_cache: Dict[str, Any] = {} |
| 40 | self._config_loaded = False |
| 41 | |
| 42 | async def initialize(self) -> None: |
| 43 | """初始化 PostgreSQL 数据库""" |
| 44 | if self._initialized: |
| 45 | return |
| 46 | |
| 47 | async with self._lock: |
| 48 | if self._initialized: |
| 49 | return |
| 50 | |
| 51 | try: |
| 52 | self._dsn = os.getenv("POSTGRESQL_URI", "") |
| 53 | if not self._dsn: |
| 54 | raise RuntimeError("POSTGRESQL_URI environment variable is not set") |
| 55 | |
| 56 | self._pool = await asyncpg.create_pool(self._dsn, min_size=2, max_size=10) |
| 57 | |
| 58 | async with self._pool.acquire() as conn: |
| 59 | await self._create_tables(conn) |
| 60 | await self._ensure_schema_compatibility(conn) |
| 61 | |
| 62 | await self._load_config_cache() |
| 63 | |
| 64 | self._initialized = True |
| 65 | log.info("PostgreSQL storage initialized") |
| 66 | |
| 67 | except Exception as e: |
| 68 | log.error(f"Error initializing PostgreSQL: {e}") |
| 69 | if self._pool: |
| 70 | await self._pool.close() |
| 71 | self._pool = None |
| 72 | raise |
| 73 |