Apply Black formatter to the entire codebase for consistent code style. Co-Authored-By: Claude (glm-5) <noreply@anthropic.com>
102 lines
2.7 KiB
Python
102 lines
2.7 KiB
Python
"""
|
||
DAO 基类
|
||
|
||
提供数据访问对象的通用方法和辅助函数
|
||
"""
|
||
|
||
from typing import Optional
|
||
from config.schema import DatabaseType
|
||
from db.base_connection import BaseDatabaseConnection
|
||
from db.connection import get_connection
|
||
from db.table_name_converter import TableNameConverter
|
||
|
||
|
||
class BaseDAO:
|
||
"""数据访问对象基类"""
|
||
|
||
def __init__(self):
|
||
"""初始化 DAO"""
|
||
self.db: Optional[BaseDatabaseConnection] = None
|
||
# 从配置文件加载数据库类型
|
||
from config.loader import ConfigLoader
|
||
|
||
app_config = ConfigLoader.load()
|
||
self._db_type = app_config.database.db_type
|
||
|
||
def __enter__(self):
|
||
"""进入上下文管理器,建立数据库连接"""
|
||
self.db = get_connection()
|
||
self.db.connect()
|
||
return self
|
||
|
||
def __exit__(self, exc_type, exc_val, exc_tb):
|
||
"""退出上下文管理器,关闭数据库连接"""
|
||
if self.db:
|
||
self.db.disconnect()
|
||
|
||
def close(self):
|
||
"""关闭数据库连接"""
|
||
if self.db:
|
||
self.db.disconnect()
|
||
|
||
def _convert_sql(self, sql: str) -> str:
|
||
"""
|
||
根据当前数据库类型转换 SQL 语句中的表名
|
||
|
||
Args:
|
||
sql: 原始 SQL 语句(SQL Server 格式)
|
||
|
||
Returns:
|
||
转换后的 SQL 语句
|
||
"""
|
||
if self._db_type == DatabaseType.MYSQL:
|
||
# SQL Server → MySQL
|
||
return TableNameConverter.convert_sql(sql, "mysql")
|
||
return sql
|
||
|
||
def _get_placeholder(self) -> str:
|
||
"""
|
||
获取当前数据库类型的参数占位符
|
||
|
||
Returns:
|
||
SQL Server 返回 "?",MySQL 返回 "%s"
|
||
"""
|
||
if self._db_type == DatabaseType.MYSQL:
|
||
return "%s"
|
||
return "?"
|
||
|
||
def _build_placeholders(self, count: int) -> str:
|
||
"""
|
||
构建参数占位符字符串
|
||
|
||
Args:
|
||
count: 占位符数量
|
||
|
||
Returns:
|
||
占位符字符串,如 "?, ?, ?" 或 "%s, %s, %s"
|
||
"""
|
||
placeholder = self._get_placeholder()
|
||
return ", ".join([placeholder for _ in range(count)])
|
||
|
||
def _build_in_clause_placeholders(self, count: int) -> str:
|
||
"""
|
||
构建 IN 子句的参数占位符字符串
|
||
|
||
Args:
|
||
count: 占位符数量
|
||
|
||
Returns:
|
||
IN 子句占位符字符串,如 "?, ?, ?" 或 "%s, %s, %s"
|
||
"""
|
||
placeholder = self._get_placeholder()
|
||
return ", ".join([placeholder for _ in range(count)])
|
||
|
||
def _get_connection(self):
|
||
"""
|
||
获取数据库连接
|
||
|
||
Returns:
|
||
数据库连接对象
|
||
"""
|
||
return get_connection()
|