42 lines
1.1 KiB
Python
42 lines
1.1 KiB
Python
import uuid
|
|
from datetime import datetime
|
|
|
|
from sqlalchemy import String, Text, DateTime, Integer, ForeignKey, JSON, Enum as SAEnum
|
|
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker, AsyncSession
|
|
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship
|
|
|
|
|
|
class Base(DeclarativeBase):
|
|
pass
|
|
|
|
|
|
def gen_uuid():
|
|
return str(uuid.uuid4())
|
|
|
|
|
|
engine = None
|
|
async_session_maker: async_sessionmaker[AsyncSession] | None = None
|
|
|
|
|
|
async def init_db(database_url: str):
|
|
global engine, async_session_maker
|
|
|
|
engine = create_async_engine(
|
|
database_url,
|
|
echo=False,
|
|
pool_size=20,
|
|
max_overflow=10,
|
|
pool_pre_ping=True,
|
|
)
|
|
async_session_maker = async_sessionmaker(engine, expire_on_commit=False)
|
|
|
|
async with engine.begin() as conn:
|
|
await conn.run_sync(Base.metadata.create_all)
|
|
|
|
|
|
async def get_session() -> AsyncSession:
|
|
if async_session_maker is None:
|
|
raise RuntimeError("Database not initialized")
|
|
async with async_session_maker() as session:
|
|
yield session
|