dashboard-nanobot/backend/core/database.py

68 lines
1.9 KiB
Python
Raw Normal View History

2026-03-09 04:53:15 +00:00
from sqlalchemy import inspect, text
2026-04-13 10:10:25 +00:00
from sqlmodel import Session, create_engine
2026-03-01 16:26:03 +00:00
2026-03-14 07:44:11 +00:00
from core.settings import (
DATABASE_ECHO,
DATABASE_MAX_OVERFLOW,
DATABASE_POOL_RECYCLE,
DATABASE_POOL_SIZE,
DATABASE_POOL_TIMEOUT,
DATABASE_URL,
)
2026-03-01 16:26:03 +00:00
2026-03-14 07:44:11 +00:00
_engine_kwargs = {
"echo": DATABASE_ECHO,
2026-04-02 04:14:08 +00:00
"pool_pre_ping": True,
"pool_size": DATABASE_POOL_SIZE,
"max_overflow": DATABASE_MAX_OVERFLOW,
"pool_timeout": DATABASE_POOL_TIMEOUT,
"pool_recycle": DATABASE_POOL_RECYCLE,
2026-03-14 07:44:11 +00:00
}
engine = create_engine(DATABASE_URL, **_engine_kwargs)
2026-03-01 16:26:03 +00:00
2026-03-17 19:52:50 +00:00
BOT_INSTANCE_TABLE = "bot_instance"
BOT_MESSAGE_TABLE = "bot_message"
BOT_IMAGE_TABLE = "bot_image"
BOT_REQUEST_USAGE_TABLE = "bot_request_usage"
BOT_ACTIVITY_EVENT_TABLE = "bot_activity_event"
2026-04-03 15:00:08 +00:00
SYS_LOGIN_LOG_TABLE = "sys_login_log"
2026-03-17 19:52:50 +00:00
SYS_SETTING_TABLE = "sys_setting"
2026-04-13 10:10:25 +00:00
REQUIRED_TABLES = (
BOT_INSTANCE_TABLE,
BOT_MESSAGE_TABLE,
BOT_IMAGE_TABLE,
BOT_REQUEST_USAGE_TABLE,
BOT_ACTIVITY_EVENT_TABLE,
SYS_LOGIN_LOG_TABLE,
SYS_SETTING_TABLE,
"skill_market_item",
"bot_skill_install",
"topic_topic",
"topic_item",
)
2026-03-13 06:40:54 +00:00
2026-04-13 10:10:25 +00:00
def _validate_required_tables() -> None:
2026-04-02 04:40:17 +00:00
inspector = inspect(engine)
2026-04-13 10:10:25 +00:00
missing = [table_name for table_name in REQUIRED_TABLES if not inspector.has_table(table_name)]
if missing:
raise RuntimeError(
"Database schema is not initialized. "
f"Missing tables: {', '.join(missing)}. "
"Run scripts/init-full-db.sh or apply scripts/sql/create-tables.sql before starting the backend."
)
2026-03-01 16:26:03 +00:00
def init_database() -> None:
2026-04-13 10:10:25 +00:00
with engine.connect() as conn:
conn.execute(text("SELECT 1"))
_validate_required_tables()
2026-05-20 06:02:13 +00:00
from services.platform_system_settings_service import validate_required_system_settings
with Session(engine) as session:
validate_required_system_settings(session)
2026-03-01 16:26:03 +00:00
def get_session():
with Session(engine) as session:
yield session