Files
AgentScript/agent/backend/app/store/db_connection_store.py
T

215 lines
7.4 KiB
Python
Raw Normal View History

"""
数据库连接存储层
================
【功能说明】数据库连接配置的持久化(SQLite),支持增删改查。
【安全设计】密码用简单加密存储(XOR + base64),前端返回脱敏值。
【实现思路】DatabaseConnectionStore 抽象 + SqliteDatabaseConnectionStore 实现。
"""
from __future__ import annotations
import base64
import sqlite3
import uuid
from abc import ABC, abstractmethod
from datetime import datetime
from pathlib import Path
from typing import Optional
from app.schemas.database import (
DatabaseConnection,
DatabaseConnectionCreate,
DatabaseConnectionUpdate,
)
from app.store.sqlite_util import open_connection
# 简易加密密钥(本地场景,够用;生产建议用密钥管理服务)
_XOR_KEY = b"agent_db_key_2026"
def _encrypt(text: str) -> str:
"""简易 XOR + base64 加密(本地场景防止明文存储)。"""
if not text:
return ""
data = text.encode("utf-8")
encrypted = bytes(b ^ _XOR_KEY[i % len(_XOR_KEY)] for i, b in enumerate(data))
return base64.b64encode(encrypted).decode("ascii")
def _decrypt(token: str) -> str:
"""解密。"""
if not token:
return ""
try:
encrypted = base64.b64decode(token.encode("ascii"))
decrypted = bytes(b ^ _XOR_KEY[i % len(_XOR_KEY)] for i, b in enumerate(encrypted))
return decrypted.decode("utf-8")
except Exception: # noqa: BLE001
return ""
class DatabaseConnectionStore(ABC):
"""数据库连接配置存储抽象"""
@abstractmethod
def create(self, payload: DatabaseConnectionCreate) -> DatabaseConnection: ...
@abstractmethod
def get(self, config_id: str) -> Optional[DatabaseConnection]: ...
@abstractmethod
def get_with_password(self, config_id: str) -> Optional[dict]: ...
@abstractmethod
def list_all(self) -> list[DatabaseConnection]: ...
@abstractmethod
def update(
self, config_id: str, payload: DatabaseConnectionUpdate
) -> Optional[DatabaseConnection]: ...
@abstractmethod
def delete(self, config_id: str) -> bool: ...
class SqliteDatabaseConnectionStore(DatabaseConnectionStore):
"""SQLite 实现"""
def __init__(self, db_path: Path) -> None:
self._db_path = Path(db_path)
self._db_path.parent.mkdir(parents=True, exist_ok=True)
self._init_schema()
def _connect(self):
"""
获取一个短连接(用完自动提交/回滚并关闭)。
【修复】原先 `with sqlite3.connect(...)` 只提交不关闭,连接泄漏到 GC。
改为委托 app.store.sqlite_util.open_connection,语义不变、额外保证 close。
"""
return open_connection(self._db_path)
def _init_schema(self) -> None:
ddl = """
CREATE TABLE IF NOT EXISTS db_connection (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
db_type TEXT NOT NULL,
host TEXT DEFAULT 'localhost',
port INTEGER DEFAULT 3306,
database TEXT NOT NULL,
username TEXT DEFAULT '',
password TEXT DEFAULT '',
description TEXT DEFAULT '',
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
);
"""
with self._connect() as conn:
conn.execute(ddl)
conn.commit()
@staticmethod
def _row_to_entity(row: sqlite3.Row, mask_password: bool = True) -> DatabaseConnection:
pwd = "******" if mask_password else _decrypt(row["password"] or "")
return DatabaseConnection(
id=row["id"],
name=row["name"],
db_type=row["db_type"],
host=row["host"] or "localhost",
port=row["port"] or 3306,
database=row["database"],
username=row["username"] or "",
password=pwd,
description=row["description"] or "",
created_at=datetime.fromisoformat(row["created_at"]),
updated_at=datetime.fromisoformat(row["updated_at"]),
)
def create(self, payload: DatabaseConnectionCreate) -> DatabaseConnection:
config_id = f"db_{uuid.uuid4().hex[:12]}"
now = datetime.now().astimezone().isoformat(timespec="seconds")
with self._connect() as conn:
conn.execute(
"""INSERT INTO db_connection
(id, name, db_type, host, port, database, username, password, description, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
(
config_id,
payload.name,
payload.db_type,
payload.host,
payload.port,
payload.database,
payload.username,
_encrypt(payload.password),
payload.description,
now,
now,
),
)
conn.commit()
created = self.get(config_id)
if created is None:
raise RuntimeError(f"连接配置创建后回读失败:{config_id}")
return created
def get(self, config_id: str) -> Optional[DatabaseConnection]:
with self._connect() as conn:
row = conn.execute(
"SELECT * FROM db_connection WHERE id = ?", (config_id,)
).fetchone()
return self._row_to_entity(row) if row else None
def get_with_password(self, config_id: str) -> Optional[dict]:
"""返回含真实密码的连接信息(供引擎使用,不暴露给前端)。"""
with self._connect() as conn:
row = conn.execute(
"SELECT * FROM db_connection WHERE id = ?", (config_id,)
).fetchone()
if not row:
return None
return {
"id": row["id"],
"name": row["name"],
"db_type": row["db_type"],
"host": row["host"] or "localhost",
"port": row["port"] or 3306,
"database": row["database"],
"username": row["username"] or "",
"password": _decrypt(row["password"] or ""),
}
def list_all(self) -> list[DatabaseConnection]:
with self._connect() as conn:
rows = conn.execute(
"SELECT * FROM db_connection ORDER BY created_at DESC"
).fetchall()
return [self._row_to_entity(r) for r in rows]
def update(
self, config_id: str, payload: DatabaseConnectionUpdate
) -> Optional[DatabaseConnection]:
existing = self.get(config_id)
if existing is None:
return None
changes = payload.model_dump(exclude_none=True)
if not changes:
return existing
if "password" in changes:
changes["password"] = _encrypt(changes["password"])
changes["updated_at"] = datetime.now().astimezone().isoformat(timespec="seconds")
set_clause = ", ".join(f"{k} = ?" for k in changes)
values = list(changes.values()) + [config_id]
with self._connect() as conn:
conn.execute(f"UPDATE db_connection SET {set_clause} WHERE id = ?", values)
conn.commit()
return self.get(config_id)
def delete(self, config_id: str) -> bool:
with self._connect() as conn:
cursor = conn.execute("DELETE FROM db_connection WHERE id = ?", (config_id,))
conn.commit()
return cursor.rowcount > 0