database.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. from sqlalchemy import create_engine , text
  2. from app.models.base import Base
  3. from sqlalchemy.orm import sessionmaker
  4. from sqlalchemy.ext.declarative import declarative_base
  5. import os
  6. from dotenv import load_dotenv # type: ignore
  7. import logging
  8. from sqlalchemy.exc import SQLAlchemyError
  9. # 配置日志系统 - 检查是否已经配置过,避免重复配置
  10. if not logging.getLogger().handlers:
  11. logging.basicConfig(level=logging.INFO)
  12. # 关闭SQLAlchemy的详细SQL执行日志,只保留错误日志
  13. logging.getLogger('sqlalchemy.engine').setLevel(logging.WARNING)
  14. logger = logging.getLogger(__name__)
  15. # 创建Base类
  16. #Base = declarative_base()
  17. Base.metadata.clear()
  18. # 加载环境变量
  19. load_dotenv("config.env")
  20. # 从环境变量获取数据库连接信息
  21. DB_USER = os.getenv("DB_USER", "postgres")
  22. DB_PASSWORD = os.getenv("DB_PASSWORD", "scau2025")
  23. DB_HOST = os.getenv("DB_HOST", "localhost")
  24. DB_PORT = os.getenv("DB_PORT", "5432")
  25. DB_NAME = os.getenv("DB_NAME", "data_db")
  26. print(DB_USER, DB_PASSWORD, DB_HOST, DB_PORT, DB_NAME)
  27. # 构建数据库连接URL
  28. SQLALCHEMY_DATABASE_URL = f"postgresql://{DB_USER}:{DB_PASSWORD}@{DB_HOST}:{DB_PORT}/{DB_NAME}?options=-c client_encoding=utf8"
  29. def create_database_engine():
  30. """创建并配置数据库引擎"""
  31. try:
  32. engine = create_engine(
  33. SQLALCHEMY_DATABASE_URL,
  34. pool_pre_ping=True,
  35. pool_size=5,
  36. max_overflow=10,
  37. pool_timeout=30,
  38. pool_recycle=1800
  39. )
  40. return engine
  41. except Exception as e:
  42. logger.error(f"创建数据库引擎失败: {str(e)}")
  43. raise
  44. def test_database_connection(engine):
  45. """测试数据库连接"""
  46. try:
  47. with engine.connect() as conn:
  48. logger.info("数据库连接测试成功")
  49. return True
  50. except SQLAlchemyError as e:
  51. logger.error(f"数据库连接测试失败: {str(e)}")
  52. return False
  53. # 创建数据库引擎
  54. engine = create_database_engine()
  55. # 测试数据库连接
  56. if not test_database_connection(engine):
  57. raise Exception("无法连接到数据库,请检查数据库配置")
  58. # 创建会话工厂
  59. SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
  60. def get_db():
  61. """获取数据库会话"""
  62. db = SessionLocal()
  63. try:
  64. yield db
  65. except SQLAlchemyError as e:
  66. logger.error(f"数据库操作错误: {str(e)}")
  67. raise
  68. finally:
  69. db.close()
  70. def execute_sql(sql_statement):
  71. """
  72. 执行原始SQL语句
  73. Args:
  74. sql_statement: 要执行的SQL语句
  75. Returns:
  76. 执行结果
  77. """
  78. try:
  79. with engine.begin() as connection:
  80. result = connection.execute(sql_statement)
  81. return result
  82. except SQLAlchemyError as e:
  83. logger.error(f"执行SQL语句失败: {str(e)}")
  84. raise
  85. # 新增:自动创建数据库表(关键!)
  86. def create_tables():
  87. try:
  88. # ✨ 新增:同时启用 PostGIS 核心和 Raster 扩展
  89. with engine.begin() as conn:
  90. # 启用 PostGIS 核心(矢量)
  91. conn.execute(text("CREATE EXTENSION IF NOT EXISTS postgis;")) # pyright: ignore[reportUndefinedVariable]
  92. # 启用 PostGIS Raster(栅格)
  93. conn.execute(text("CREATE EXTENSION IF NOT EXISTS postgis_raster;")) # pyright: ignore[reportUndefinedVariable]
  94. logger.info("PostGIS 核心及 Raster 扩展已启用(或已存在)")
  95. # 必须导入所有模型,否则 Base 不知道要创建哪些表
  96. # 替换成你项目中实际的模型文件路径(根据你的目录结构调整)
  97. from app.models.orm_models import Base # 确保模型继承自这个 Base
  98. from app.models.vector import VectorData # 导入需要创建的表
  99. #from app.models.raster import RasterData # 补充其他模型
  100. from app.models.county import County
  101. from app.models.farmland import FarmlandData
  102. from app.models.agricultural import AgriculturalData # 假设类名是 Agricultural
  103. from app.models.assessment import Assessment
  104. from app.models.atmo_company import AtmoCompany
  105. from app.models.atmo_sample import AtmoSampleData
  106. from app.models.CropCd_input import CropCdInputData
  107. from app.models.CropCd_output import CropCdOutputData
  108. from app.models.cross_section import CrossSection
  109. from app.models.EffCd_input import EffCdInputData
  110. from app.models.EffCd_output import EffCdOutputData
  111. from app.models.FluxCd_input import FluxCdInputData
  112. from app.models.FluxCd_output import FluxCdOutputData
  113. from app.models.MSM_input import MSMInputData
  114. from app.models.MSM_output import MSMOutputData
  115. from app.models.parameters import Parameters
  116. from app.models.soil import SoilData
  117. from app.models.water_sample import WaterSampleData
  118. # 创建所有表
  119. Base.metadata.create_all(bind=engine)
  120. logger.info("数据库表自动创建成功!")
  121. except ImportError as e:
  122. logger.warning(f"未找到模型文件,可能需要手动创建表:{str(e)}")
  123. except Exception as e:
  124. logger.error(f"创建表失败:{str(e)}")
  125. raise
  126. # 执行建表(在连接测试成功后)
  127. create_tables()