123 lines
4.1 KiB
Python
123 lines
4.1 KiB
Python
"""
|
||
Database connection and session management
|
||
"""
|
||
from sqlalchemy import text
|
||
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
|
||
from sqlalchemy.orm import declarative_base
|
||
from app.config import settings
|
||
import logging
|
||
|
||
logger = logging.getLogger(__name__)
|
||
|
||
# Create async engine
|
||
engine = create_async_engine(
|
||
settings.database_url,
|
||
echo=False, # Set to True for SQL query logging
|
||
pool_size=settings.database_pool_size,
|
||
max_overflow=settings.database_max_overflow,
|
||
pool_pre_ping=True, # Verify connections before using
|
||
)
|
||
|
||
# Create async session factory
|
||
AsyncSessionLocal = async_sessionmaker(
|
||
engine,
|
||
class_=AsyncSession,
|
||
expire_on_commit=False,
|
||
autocommit=False,
|
||
autoflush=False,
|
||
)
|
||
|
||
# Base class for ORM models
|
||
Base = declarative_base()
|
||
|
||
|
||
async def get_db() -> AsyncSession:
|
||
"""
|
||
Dependency function for FastAPI to get database sessions
|
||
|
||
Usage:
|
||
@app.get("/items")
|
||
async def read_items(db: AsyncSession = Depends(get_db)):
|
||
...
|
||
"""
|
||
async with AsyncSessionLocal() as session:
|
||
try:
|
||
yield session
|
||
await session.commit()
|
||
except Exception:
|
||
await session.rollback()
|
||
raise
|
||
finally:
|
||
await session.close()
|
||
|
||
|
||
async def init_db():
|
||
"""Initialize database - create all tables"""
|
||
from app.models.db import (
|
||
CelestialBody,
|
||
Position,
|
||
Resource,
|
||
StaticData,
|
||
NasaCache,
|
||
)
|
||
|
||
async with engine.begin() as conn:
|
||
# Create all tables
|
||
await conn.run_sync(Base.metadata.create_all)
|
||
|
||
logger.info("Database tables created successfully")
|
||
|
||
|
||
SERIAL_PKEYS_SQL = text("""
|
||
SELECT c.oid::regclass::text AS table_ref,
|
||
quote_ident(a.attname) AS column_ref,
|
||
to_regclass(pg_get_serial_sequence(c.oid::regclass::text, a.attname))::text AS seq_ref
|
||
FROM pg_class c
|
||
JOIN pg_namespace n ON n.oid = c.relnamespace
|
||
JOIN pg_constraint pk ON pk.conrelid = c.oid AND pk.contype = 'p'
|
||
JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum = pk.conkey[1]
|
||
WHERE n.nspname = current_schema()
|
||
AND c.relkind = 'r'
|
||
AND cardinality(pk.conkey) = 1
|
||
AND to_regclass(pg_get_serial_sequence(c.oid::regclass::text, a.attname)) IS NOT NULL
|
||
ORDER BY 1
|
||
""")
|
||
|
||
|
||
async def sync_sequences() -> list[str]:
|
||
"""把落后的自增序列追到 MAX(id),返回被修正的表。
|
||
|
||
库里的数据不少是从 dump / Navicat 脚本导入的,那些 INSERT 自带显式 id,序列不会
|
||
跟着涨(init_db.sql 还把 menus_id_seq 钉在 10)。序列一旦落在 MAX(id) 后面,任何
|
||
一条不带 id 的 INSERT 都会撞 duplicate key ... Key (id)=(N) already exists;服务器
|
||
上启动预置就是把后端撞崩在这上面的。只在序列确实落后时才 setval,正常库不动它。
|
||
"""
|
||
fixed: list[str] = []
|
||
try:
|
||
async with engine.begin() as conn:
|
||
rows = (await conn.execute(SERIAL_PKEYS_SQL)).all()
|
||
for table_ref, column_ref, seq_ref in rows:
|
||
# 三段名字都是 Postgres 自己引用的(regclass / quote_ident),可直接拼接
|
||
max_id, next_id = (await conn.execute(text(
|
||
f"SELECT (SELECT COALESCE(MAX({column_ref}), 0) FROM {table_ref}), "
|
||
f"(SELECT last_value + is_called::int FROM {seq_ref})"
|
||
))).one()
|
||
if next_id <= max_id:
|
||
await conn.execute(
|
||
text("SELECT setval(CAST(:seq AS regclass), CAST(:next_id AS bigint), false)"),
|
||
{"seq": seq_ref, "next_id": max_id + 1},
|
||
)
|
||
fixed.append(f"{table_ref}->{max_id + 1}")
|
||
except Exception as e:
|
||
# 对齐序列只是修历史数据,失败不该拦住启动
|
||
logger.warning(f"! Sequence sync skipped: {e}")
|
||
if fixed:
|
||
logger.warning(f"✓ Sequences resynced: {', '.join(fixed)}")
|
||
return fixed
|
||
|
||
|
||
async def close_db():
|
||
"""Close database connections"""
|
||
await engine.dispose()
|
||
logger.info("Database connections closed")
|