You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
38 lines
892 B
38 lines
892 B
|
2 months ago
|
"""
|
||
|
|
AmazingData 数据服务平台 - 数据库配置
|
||
|
|
"""
|
||
|
|
|
||
|
|
from sqlalchemy import create_engine
|
||
|
|
from sqlalchemy.ext.declarative import declarative_base
|
||
|
|
from sqlalchemy.orm import sessionmaker
|
||
|
|
from backend.config import settings
|
||
|
|
|
||
|
|
# 创建数据库引擎
|
||
|
|
engine = create_engine(
|
||
|
|
settings.DATABASE_URL,
|
||
|
|
pool_pre_ping=True,
|
||
|
|
pool_recycle=3600,
|
||
|
|
echo=settings.DEBUG
|
||
|
|
)
|
||
|
|
|
||
|
|
# 创建会话工厂
|
||
|
|
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||
|
|
|
||
|
|
# 创建基类
|
||
|
|
Base = declarative_base()
|
||
|
|
|
||
|
|
|
||
|
|
def get_db():
|
||
|
|
"""获取数据库会话(用于依赖注入)"""
|
||
|
|
db = SessionLocal()
|
||
|
|
try:
|
||
|
|
yield db
|
||
|
|
finally:
|
||
|
|
db.close()
|
||
|
|
|
||
|
|
|
||
|
|
def init_db():
|
||
|
|
"""初始化数据库(创建所有表)"""
|
||
|
|
from backend.models import tables # 导入所有表模型
|
||
|
|
Base.metadata.create_all(bind=engine)
|
||
|
|
print("Database tables created successfully!")
|