Files
Tunnel/app/core/database.py
2025-12-12 10:57:31 +08:00

59 lines
1.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from sqlalchemy import create_engine, text, MetaData
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import QueuePool
from .config import settings
# Railway数据库引擎账号表
railway_engine = create_engine(
settings.RAILWAY_DATABASE_URL,
poolclass=QueuePool,
pool_pre_ping=True,
echo=False,
pool_size=20,
max_overflow=30,
pool_timeout=60,
pool_recycle=3600,
pool_reset_on_return='commit'
)
# Tunnel数据库引擎业务数据表
tunnel_engine = create_engine(
settings.TUNNEL_DATABASE_URL,
poolclass=QueuePool,
pool_pre_ping=True,
echo=False,
pool_size=100,
max_overflow=200,
pool_timeout=60,
pool_recycle=3600,
pool_reset_on_return='commit'
)
RailwaySessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=railway_engine)
TunnelSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=tunnel_engine)
RailwayBase = declarative_base()
TunnelBase = declarative_base()
def get_railway_db():
"""Railway数据库依赖注入"""
db = RailwaySessionLocal()
try:
yield db
finally:
db.close()
def get_tunnel_db():
"""Tunnel数据库依赖注入"""
db = TunnelSessionLocal()
try:
yield db
finally:
db.close()
def init_db():
"""初始化数据库"""
RailwayBase.metadata.create_all(bind=railway_engine)
TunnelBase.metadata.create_all(bind=tunnel_engine)