Initial commit

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
hughhuang(黄健铭)andClaude Sonnet 4.5 committed 2026-01-16 16:01:39 +08:00
commit 4ecf7b351d
143 files changed
+24156

No files matched your search

+97
View File
@@ -0,0 +1,97 @@
"""
Database connection and operations module
"""
import pymysql
from typing import Optional, Dict, List, Any
from contextlib import contextmanager
from ..core.config import DatabaseConfig
class DatabaseManager:
"""Database connection manager"""
def __init__(self, config: DatabaseConfig):
self.config = config
self._connection = None
def connect(self):
"""Establish database connection"""
self._connection = pymysql.connect(
host=self.config.host,
port=self.config.port,
user=self.config.user,
password=self.config.password,
database=self.config.database,
charset=self.config.charset,
cursorclass=pymysql.cursors.DictCursor
)
return self._connection
def close(self):
"""Close database connection"""
if self._connection:
self._connection.close()
self._connection = None
@contextmanager
def get_connection(self):
"""Get database connection context manager"""
conn = self.connect()
try:
yield conn
finally:
conn.close()
@contextmanager
def get_cursor(self):
"""Get database cursor context manager"""
with self.get_connection() as conn:
cursor = conn.cursor()
try:
yield cursor
conn.commit()
except Exception:
conn.rollback()
raise
finally:
cursor.close()
def execute_query(self, sql: str, params: Optional[tuple] = None) -> List[Dict]:
"""Execute SELECT query"""
with self.get_cursor() as cursor:
cursor.execute(sql, params)
return cursor.fetchall()
def execute_update(self, sql: str, params: Optional[tuple] = None) -> int:
"""Execute INSERT/UPDATE/DELETE query"""
with self.get_cursor() as cursor:
affected_rows = cursor.execute(sql, params)
return affected_rows
def execute_many(self, sql: str, params_list: List[tuple]) -> int:
"""Execute batch INSERT/UPDATE"""
with self.get_cursor() as cursor:
affected_rows = cursor.executemany(sql, params_list)
return affected_rows
def init_schema(self, schema_file: str):
"""Initialize database schema from SQL file"""
with open(schema_file, 'r', encoding='utf-8') as f:
schema_sql = f.read()
# Split by semicolon and execute each statement
statements = [s.strip() for s in schema_sql.split(';') if s.strip()]
with self.get_connection() as conn:
cursor = conn.cursor()
try:
for statement in statements:
if statement:
cursor.execute(statement)
conn.commit()
except Exception as e:
conn.rollback()
raise Exception(f"Failed to initialize schema: {e}")
finally:
cursor.close()