generated from coulomb/repo-seed
Start Core Hub FastAPI replacement foundation
This commit is contained in:
36
src/core_hub/db.py
Normal file
36
src/core_hub/db.py
Normal file
@@ -0,0 +1,36 @@
|
||||
from collections.abc import AsyncIterator
|
||||
from functools import lru_cache
|
||||
|
||||
from sqlalchemy.ext.asyncio import (
|
||||
AsyncEngine,
|
||||
AsyncSession,
|
||||
async_sessionmaker,
|
||||
create_async_engine,
|
||||
)
|
||||
from sqlalchemy.orm import DeclarativeBase
|
||||
|
||||
from .config import get_settings
|
||||
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
pass
|
||||
|
||||
|
||||
def make_engine(database_url: str) -> AsyncEngine:
|
||||
return create_async_engine(database_url, pool_pre_ping=True)
|
||||
|
||||
|
||||
@lru_cache
|
||||
def get_engine() -> AsyncEngine:
|
||||
return make_engine(get_settings().database_url)
|
||||
|
||||
|
||||
@lru_cache
|
||||
def get_sessionmaker() -> async_sessionmaker[AsyncSession]:
|
||||
return async_sessionmaker(get_engine(), expire_on_commit=False)
|
||||
|
||||
|
||||
async def session_scope() -> AsyncIterator[AsyncSession]:
|
||||
async_session = get_sessionmaker()
|
||||
async with async_session() as session:
|
||||
yield session
|
||||
Reference in New Issue
Block a user