File size: 1,684 Bytes
f78efc5
 
 
d4356af
f78efc5
 
d4356af
f78efc5
 
 
 
 
 
 
 
d4356af
f78efc5
 
 
 
 
d4356af
f78efc5
 
d4356af
f78efc5
d4356af
f78efc5
 
 
 
 
d4356af
 
 
 
 
 
 
 
 
 
 
 
 
f78efc5
 
d4356af
f78efc5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d4356af
f78efc5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
from sqlalchemy.orm import declarative_base
from ..core.config import settings
from sqlalchemy import text
import contextlib

# Create async engine
async_engine = create_async_engine(
    settings.DATABASE_URL,
    echo=True,
    future=True,
    pool_pre_ping=True
)

# Create async session factory
async_session_maker = async_sessionmaker(
    bind=async_engine,
    class_=AsyncSession,
    expire_on_commit=False
)

# Declarative base for models
Base = declarative_base()

# FastAPI dependency for DB access
async def get_db():
    async with async_session_maker() as session:
        try:
            yield session
        finally:
            await session.close()

# Verify DB connection
async def verify_connection():
    async with async_session_maker() as session:
        try:
            await session.execute(text("SELECT 1"))
        except Exception as e:
            raise ConnectionError(f"Database connection verification failed: {str(e)}")

# Init DB (called during app startup)
async def init_db():
    await verify_connection()

# Optional: Custom DB access class
class Database:
    def __init__(self):
        self._session_factory = async_session_maker

    @contextlib.asynccontextmanager
    async def session(self):
        session = self._session_factory()
        try:
            yield session
            await session.commit()
        except:
            await session.rollback()
            raise
        finally:
            await session.close()

    async def get_session(self):
        return self._session_factory()

# Singleton DB instance
db = Database()