refactor(db): 移除 MongoDB 相关代码
从数据库模块中移除了所有与 MongoDB 相关的代码,包括连接逻辑、`get_db` 函数和 `DBWrapper` 代理类。 项目将统一使用 SQLAlchemy 作为唯一的数据库接口,此更改旨在简化代码库并消除不再需要的依赖。 BREAKING CHANGE: 全局 MongoDB 实例 `memory_db` 和 `get_db` 函数已被移除。所有数据库交互现在都应通过 SQLAlchemy 会话进行。
This commit is contained in:
committed by
Windpicker-owo
parent
350388d116
commit
b2e3c883b4
@@ -1,6 +1,4 @@
|
||||
import os
|
||||
from pymongo import MongoClient
|
||||
from pymongo.database import Database
|
||||
from rich.traceback import install
|
||||
from src.common.logger import get_logger
|
||||
|
||||
@@ -10,8 +8,6 @@ from src.common.database.sqlalchemy_models import get_engine, get_db_session
|
||||
|
||||
install(extra_lines=3)
|
||||
|
||||
_client = None
|
||||
_db = None
|
||||
_sql_engine = None
|
||||
|
||||
logger = get_logger("database")
|
||||
@@ -64,43 +60,6 @@ class SQLAlchemyTransaction:
|
||||
db = DatabaseProxy()
|
||||
|
||||
|
||||
def __create_database_instance():
|
||||
uri = os.getenv("MONGODB_URI")
|
||||
host = os.getenv("MONGODB_HOST", "127.0.0.1")
|
||||
port = int(os.getenv("MONGODB_PORT", "27017"))
|
||||
# db_name 变量在创建连接时不需要,在获取数据库实例时才使用
|
||||
username = os.getenv("MONGODB_USERNAME")
|
||||
password = os.getenv("MONGODB_PASSWORD")
|
||||
auth_source = os.getenv("MONGODB_AUTH_SOURCE")
|
||||
|
||||
if uri:
|
||||
# 支持标准mongodb://和mongodb+srv://连接字符串
|
||||
if uri.startswith(("mongodb://", "mongodb+srv://")):
|
||||
return MongoClient(uri)
|
||||
else:
|
||||
raise ValueError(
|
||||
"Invalid MongoDB URI format. URI must start with 'mongodb://' or 'mongodb+srv://'. "
|
||||
"For MongoDB Atlas, use 'mongodb+srv://' format. "
|
||||
"See: https://www.mongodb.com/docs/manual/reference/connection-string/"
|
||||
)
|
||||
|
||||
if username and password:
|
||||
# 如果有用户名和密码,使用认证连接
|
||||
return MongoClient(host, port, username=username, password=password, authSource=auth_source)
|
||||
|
||||
# 否则使用无认证连接
|
||||
return MongoClient(host, port)
|
||||
|
||||
|
||||
def get_db():
|
||||
"""获取MongoDB连接实例,延迟初始化。"""
|
||||
global _client, _db
|
||||
if _client is None:
|
||||
_client = __create_database_instance()
|
||||
_db = _client[os.getenv("DATABASE_NAME", "MegBot")]
|
||||
return _db
|
||||
|
||||
|
||||
async def initialize_sql_database(database_config):
|
||||
"""
|
||||
根据配置初始化SQL数据库连接(SQLAlchemy版本)
|
||||
@@ -141,17 +100,3 @@ async def initialize_sql_database(database_config):
|
||||
except Exception as e:
|
||||
logger.error(f"初始化SQL数据库失败: {e}")
|
||||
return None
|
||||
|
||||
|
||||
class DBWrapper:
|
||||
"""数据库代理类,保持接口兼容性同时实现懒加载。"""
|
||||
|
||||
def __getattr__(self, name):
|
||||
return getattr(get_db(), name)
|
||||
|
||||
def __getitem__(self, key):
|
||||
return get_db()[key] # type: ignore
|
||||
|
||||
|
||||
# 全局MongoDB数据库访问点
|
||||
memory_db: Database = DBWrapper() # type: ignore
|
||||
|
||||
Reference in New Issue
Block a user