acupedia-api/app/features/admin/services/database_service.py

99 lines
3.6 KiB
Python

from __future__ import annotations
import asyncio
import shlex
from datetime import datetime, timezone
from urllib.parse import urlparse
from fastapi.responses import StreamingResponse
from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.config import settings
class AdminDatabaseService:
def __init__(self, session: AsyncSession) -> None:
self.session = session
async def get_database_info(self) -> dict:
size_res = await self.session.execute(text(
"SELECT pg_size_pretty(pg_database_size(current_database())), "
"pg_database_size(current_database()), "
"version();"
))
row = size_res.fetchone()
size_human = row[0] if row else "Unknown"
size_bytes = row[1] if row else 0
pg_version = row[2].split(",")[0] if row else "PostgreSQL"
tables_res = await self.session.execute(text(
"SELECT schemaname, count(*) as count "
"FROM pg_tables "
"WHERE schemaname NOT IN ('pg_catalog', 'information_schema') "
"GROUP BY schemaname "
"ORDER BY count DESC;"
))
schemas = [{"schema": r[0], "table_count": r[1]} for r in tables_res.fetchall()]
total_tables = sum(s["table_count"] for s in schemas)
u = settings.database_url.replace("postgresql+asyncpg://", "postgresql://")
p = urlparse(u)
db_name = p.path.lstrip("/") or "acupedia_db"
return {
"status": "healthy",
"database_name": db_name,
"host": p.hostname or "localhost",
"port": p.port or 5432,
"size_human": size_human,
"size_bytes": size_bytes,
"total_tables": total_tables,
"schemas": schemas,
"postgres_version": pg_version,
"timestamp": datetime.now(timezone.utc).isoformat(),
}
async def download_database_backup(self, scope: str = "full") -> StreamingResponse:
if scope not in ("full", "content"):
raise ValueError("Invalid scope. Supported: 'full', 'content'.")
u = settings.database_url.replace("postgresql+asyncpg://", "postgresql://")
p = urlparse(u)
pwd = p.password or ""
host = p.hostname or "localhost"
port = str(p.port or 5432)
user = p.username or "db_admin"
db_name = p.path.lstrip("/") or "acupedia_db"
scope_flag = "" if scope == "full" else "-n content"
cmd = (
f"PGPASSWORD={shlex.quote(pwd)} pg_dump "
f"-h {shlex.quote(host)} -p {shlex.quote(port)} -U {shlex.quote(user)} -d {shlex.quote(db_name)} "
f"--clean --if-exists {scope_flag} | gzip -9"
)
timestamp_str = datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S")
filename = f"acupedia_db_backup_{scope}_{timestamp_str}.sql.gz"
async def backup_stream():
proc = await asyncio.create_subprocess_shell(
cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
try:
while True:
chunk = await proc.stdout.read(65536)
if not chunk:
break
yield chunk
finally:
await proc.wait()
return StreamingResponse(
backup_stream(),
media_type="application/gzip",
headers={
"Content-Disposition": f'attachment; filename="{filename}"',
"Cache-Control": "no-cache, no-store, must-revalidate",
}
)