test_db_connection.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. """
  2. 数据库连接测试脚本
  3. 用于测试 .env 文件中的数据库配置是否正确
  4. """
  5. import os
  6. import sys
  7. from pathlib import Path
  8. from dotenv import load_dotenv
  9. import psycopg2
  10. # 添加项目根目录到路径
  11. sys.path.insert(0, str(Path(__file__).parent.parent))
  12. # 加载环境变量
  13. env_path = Path(__file__).parent.parent / '.env'
  14. load_dotenv(dotenv_path=env_path)
  15. def test_connection():
  16. """测试数据库连接"""
  17. print("=" * 60)
  18. print("数据库连接测试")
  19. print("=" * 60)
  20. # 显示配置信息
  21. print(f"\n📋 数据库配置:")
  22. print(f" Host: {os.getenv('DB_HOST', 'localhost')}")
  23. print(f" Port: {os.getenv('DB_PORT', '5432')}")
  24. print(f" Database: {os.getenv('DB_NAME', 'aigcspace')}")
  25. print(f" User: {os.getenv('DB_USER', 'postgres')}")
  26. print(f" Password: {'*' * len(os.getenv('DB_PASSWORD', ''))}")
  27. # 尝试连接
  28. print(f"\n🔌 正在连接数据库...")
  29. try:
  30. conn = psycopg2.connect(
  31. host=os.getenv("DB_HOST", "localhost"),
  32. port=int(os.getenv("DB_PORT", "5432")),
  33. database=os.getenv("DB_NAME", "aigcspace"),
  34. user=os.getenv("DB_USER", "postgres"),
  35. password=os.getenv("DB_PASSWORD", "")
  36. )
  37. print(f"✓ 数据库连接成功!")
  38. # 获取数据库版本
  39. cursor = conn.cursor()
  40. cursor.execute("SELECT version();")
  41. version = cursor.fetchone()[0]
  42. print(f"\n📊 数据库信息:")
  43. print(f" 版本: {version.split(',')[0]}")
  44. # 检查schema是否存在
  45. cursor.execute("""
  46. SELECT schema_name
  47. FROM information_schema.schemata
  48. WHERE schema_name = 'aigcspace';
  49. """)
  50. schema_exists = cursor.fetchone()
  51. if schema_exists:
  52. print(f" ✓ aigcspace schema 存在")
  53. # 检查相关表是否存在
  54. cursor.execute("""
  55. SELECT table_name
  56. FROM information_schema.tables
  57. WHERE table_schema = 'aigcspace'
  58. AND table_name IN ('model', 'model_price', 'toolbox_apps', 'image_translation')
  59. ORDER BY table_name;
  60. """)
  61. tables = cursor.fetchall()
  62. print(f"\n📋 相关表状态:")
  63. required_tables = ['model', 'model_price', 'toolbox_apps', 'image_translation']
  64. existing_tables = [t[0] for t in tables]
  65. for table in required_tables:
  66. if table in existing_tables:
  67. print(f" ✓ {table} - 已存在")
  68. else:
  69. print(f" ✗ {table} - 不存在")
  70. else:
  71. print(f" ✗ aigcspace schema 不存在")
  72. print(f"\n⚠️ 警告: 需要先创建 aigcspace schema")
  73. cursor.close()
  74. conn.close()
  75. print(f"\n" + "=" * 60)
  76. print("✅ 连接测试完成!")
  77. print("=" * 60)
  78. if not schema_exists:
  79. print(f"\n💡 下一步:")
  80. print(f" 1. 创建 schema: CREATE SCHEMA aigcspace;")
  81. print(f" 2. 执行相关表的迁移脚本")
  82. elif 'image_translation' not in existing_tables:
  83. print(f"\n💡 下一步:")
  84. print(f" 执行初始化脚本: python scripts/init_image_translation.py")
  85. else:
  86. print(f"\n💡 提示:")
  87. print(f" image_translation 表已存在,无需重复初始化")
  88. print()
  89. except Exception as e:
  90. print(f"❌ 数据库连接失败!")
  91. print(f"\n错误信息: {e}")
  92. print(f"\n💡 请检查:")
  93. print(f" 1. 数据库服务是否运行")
  94. print(f" 2. .env 文件中的配置是否正确")
  95. print(f" 3. 网络连接是否正常")
  96. print(f" 4. 用户权限是否足够")
  97. print()
  98. sys.exit(1)
  99. if __name__ == "__main__":
  100. try:
  101. test_connection()
  102. except KeyboardInterrupt:
  103. print(f"\n\n⚠️ 用户中断执行")
  104. sys.exit(1)