97 lines
3.0 KiB
Python
97 lines
3.0 KiB
Python
"""
|
|||
|
|
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()
|