62 lines
1.8 KiB
Python
62 lines
1.8 KiB
Python
"""SQLite 数据库连接与初始化(分库)
|
||
|
||
- assets.db :Provider / Asset / VPSDetail / DomainDetail / AIAccount
|
||
- metrics.db:MetricPoint / ServerInfo / SecurityCheck / EventLog
|
||
"""
|
||
|
||
from pathlib import Path
|
||
from typing import Generator
|
||
|
||
from sqlmodel import Session, SQLModel, create_engine
|
||
|
||
BASE_DIR = Path(__file__).resolve().parent.parent
|
||
DATA_DIR = BASE_DIR / "data"
|
||
DATA_DIR.mkdir(parents=True, exist_ok=True)
|
||
|
||
ASSETS_DB_URL = f"sqlite:///{DATA_DIR / 'assets.db'}"
|
||
METRICS_DB_URL = f"sqlite:///{DATA_DIR / 'metrics.db'}"
|
||
|
||
assets_engine = create_engine(
|
||
ASSETS_DB_URL, echo=False, connect_args={"check_same_thread": False}
|
||
)
|
||
metrics_engine = create_engine(
|
||
METRICS_DB_URL, echo=False, connect_args={"check_same_thread": False}
|
||
)
|
||
|
||
# 兼容旧代码:默认 engine 指向资产库
|
||
engine = assets_engine
|
||
|
||
|
||
def init_db() -> None:
|
||
"""分库建表(幂等,可重复调用)"""
|
||
from app.models.asset import AIAccount, Asset, DomainDetail, VPSDetail # noqa: F401
|
||
from app.models.monitor import ( # noqa: F401
|
||
EventLog,
|
||
MetricPoint,
|
||
SecurityCheck,
|
||
ServerInfo,
|
||
)
|
||
from app.models.provider import Provider # noqa: F401
|
||
|
||
asset_models = [Provider, Asset, VPSDetail, DomainDetail, AIAccount]
|
||
metric_models = [MetricPoint, ServerInfo, SecurityCheck, EventLog]
|
||
|
||
SQLModel.metadata.create_all(
|
||
assets_engine, tables=[m.__table__ for m in asset_models]
|
||
)
|
||
SQLModel.metadata.create_all(
|
||
metrics_engine, tables=[m.__table__ for m in metric_models]
|
||
)
|
||
|
||
|
||
def get_session() -> Generator[Session, None, None]:
|
||
"""资产库会话(默认)"""
|
||
with Session(assets_engine) as session:
|
||
yield session
|
||
|
||
|
||
def get_metrics_session() -> Generator[Session, None, None]:
|
||
"""监控 / 日志库会话"""
|
||
with Session(metrics_engine) as session:
|
||
yield session
|