统一连接到新的数据库到openproject api 下

This commit is contained in:
2026-02-11 11:00:44 +08:00
parent eb45e4aaa5
commit f5069a5606
5 changed files with 41 additions and 54 deletions

View File

@@ -18,7 +18,12 @@ class Database:
"""Initialize the connection pool."""
# Use provided db_name, or the one from constructor, or default from config
target_db_name = db_name or self.db_name
conn_string = postgresql_info.get_pgconn_string(db_name=target_db_name)
# Get connection string, handling default case where target_db_name might be None
if target_db_name:
conn_string = postgresql_info.get_pgconn_string(db_name=target_db_name)
else:
conn_string = postgresql_info.get_pgconn_string()
try:
self.pool = psycopg_pool.AsyncConnectionPool(

View File

@@ -1,7 +1,6 @@
from fastapi import APIRouter, Depends, HTTPException, Query, Body
from fastapi import APIRouter, Depends, HTTPException, Query
from typing import Optional
from psycopg import AsyncConnection
from pydantic import BaseModel
from .database import get_database_instance
from .scada_info import ScadaRepository
@@ -10,10 +9,6 @@ from .scheme import SchemeRepository
router = APIRouter()
class DatabaseConfig(BaseModel):
db_name: str
# 创建支持数据库选择的连接依赖函数
async def get_database_connection(
db_name: Optional[str] = Query(
@@ -26,26 +21,6 @@ async def get_database_connection(
yield conn
@router.post("/postgres/open-database")
async def open_database(config: DatabaseConfig):
"""
尝试连接指定数据库,如果成功则返回成功消息
"""
try:
instance = await get_database_instance(config.db_name)
# 尝试获取连接并执行简单查询以验证连接
async with instance.get_connection() as conn:
async with conn.cursor() as cur:
await cur.execute("SELECT 1")
await cur.fetchone()
return {"success": True, "message": f"Successfully connected to database: {config.db_name}"}
except Exception as e:
raise HTTPException(
status_code=500, detail=f"Failed to connect to database {config.db_name}: {str(e)}"
)
@router.get("/scada-info")
async def get_scada_info_with_connection(
conn: AsyncConnection = Depends(get_database_connection),