from __future__ import annotations from sqlalchemy import text from sqlalchemy.ext.asyncio import AsyncSession async def acquire_user_credit_lock(db: AsyncSession, user_id: str) -> None: """PostgreSQL 事务级用户锁;SQLite 调试环境无需额外锁。""" bind = db.get_bind() dialect_name = bind.dialect.name if bind is not None else "" if dialect_name == "postgresql": await db.execute( text("SELECT pg_advisory_xact_lock(hashtextextended(:lock_key, 0))"), {"lock_key": f"credit:{user_id}"}, )