41 lines
1.1 KiB
Python
41 lines
1.1 KiB
Python
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
|
|
from sqlalchemy.orm import declarative_base
|
|
|
|
|
|
Base = declarative_base()
|
|
|
|
engine = None
|
|
AsyncSessionLocal = None
|
|
|
|
|
|
async def init_database(connection_string):
|
|
"""راهاندازی اولیه دیتابیس PostgreSQL به صورت Async"""
|
|
global engine, AsyncSessionLocal
|
|
|
|
|
|
engine = create_async_engine(
|
|
connection_string,
|
|
echo=True, # برای دیباگ
|
|
future=True,
|
|
pool_pre_ping=True,
|
|
pool_recycle=300
|
|
)
|
|
|
|
AsyncSessionLocal = async_sessionmaker(
|
|
engine,
|
|
class_=AsyncSession,
|
|
expire_on_commit=False
|
|
)
|
|
|
|
print("✅ PostgreSQL Async database initialized successfully")
|
|
|
|
async def get_session() -> AsyncSession:
|
|
if not AsyncSessionLocal:
|
|
raise Exception("Database not initialized. Call init_database() first.")
|
|
|
|
return AsyncSessionLocal()
|
|
|
|
async def close_database():
|
|
if engine:
|
|
await engine.dispose()
|
|
print("✅ Database connections closed") |