105 lines
2.9 KiB
Python
105 lines
2.9 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
简化数据库初始化脚本
|
|
直接创建表结构,假设数据库已存在
|
|
"""
|
|
import asyncio
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
# 添加项目根目录到Python路径
|
|
sys.path.insert(0, str(Path(__file__).parent))
|
|
|
|
from sqlalchemy import text
|
|
from app.database import engine, Base, AsyncSessionLocal
|
|
from loguru import logger
|
|
|
|
|
|
async def init_tables():
|
|
"""初始化数据库表"""
|
|
logger.info("正在初始化数据库表...")
|
|
|
|
try:
|
|
# 尝试创建表
|
|
async with engine.begin() as conn:
|
|
logger.info("尝试创建数据库表...")
|
|
await conn.run_sync(Base.metadata.create_all)
|
|
logger.info("✅ 数据库表创建成功")
|
|
|
|
# 显示创建的表
|
|
async with engine.connect() as conn:
|
|
result = await conn.execute(
|
|
text("""
|
|
SELECT table_name
|
|
FROM information_schema.tables
|
|
WHERE table_schema = 'public'
|
|
ORDER BY table_name
|
|
""")
|
|
)
|
|
|
|
tables = result.fetchall()
|
|
if tables:
|
|
logger.info("\n已创建的表:")
|
|
for table in tables:
|
|
logger.info(f" - {table[0]}")
|
|
else:
|
|
logger.warning("未找到任何表")
|
|
|
|
except Exception as e:
|
|
logger.error(f"初始化表失败: {e}")
|
|
logger.warning("请检查:")
|
|
logger.warning("1. 数据库服务是否运行")
|
|
logger.warning("2. 数据库 deeprisk_db 是否存在")
|
|
logger.warning("3. 用户名和密码是否正确")
|
|
raise
|
|
|
|
|
|
async def test_connection():
|
|
"""测试数据库连接"""
|
|
logger.info("正在测试数据库连接...")
|
|
|
|
try:
|
|
async with engine.connect() as conn:
|
|
result = await conn.execute(text("SELECT 1 as test"))
|
|
row = result.fetchone()
|
|
if row and row[0] == 1:
|
|
logger.info("✅ 数据库连接成功")
|
|
return True
|
|
else:
|
|
logger.error("❌ 数据库连接测试失败")
|
|
return False
|
|
except Exception as e:
|
|
logger.error(f"❌ 数据库连接失败: {e}")
|
|
return False
|
|
|
|
|
|
async def main():
|
|
"""主函数"""
|
|
logger.info("=" * 60)
|
|
logger.info("DeepRisk 数据库初始化 (简化版)")
|
|
logger.info("=" * 60)
|
|
|
|
# 测试连接
|
|
if not await test_connection():
|
|
logger.error("数据库连接失败,退出初始化")
|
|
sys.exit(1)
|
|
|
|
try:
|
|
# 初始化表结构
|
|
await init_tables()
|
|
|
|
logger.info("=" * 60)
|
|
logger.info("✅ 数据库初始化完成!")
|
|
logger.info("=" * 60)
|
|
|
|
except Exception as e:
|
|
logger.error(f"数据库初始化失败: {e}")
|
|
sys.exit(1)
|
|
|
|
finally:
|
|
await engine.dispose()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
asyncio.run(main())
|