File size: 966 Bytes
8b3905d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Async database session factory."""

from __future__ import annotations

import os

from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from sqlalchemy.pool import NullPool

from database.models import Base

DATABASE_URL = os.getenv(
    "DATABASE_URL",
    "postgresql+asyncpg://sentinel:sentinel@localhost:5432/sentinelai",
)

_connect_args: dict = {}
if "postgresql" in DATABASE_URL and "asyncpg" in DATABASE_URL:
    _connect_args["timeout"] = float(os.getenv("DB_CONNECT_TIMEOUT_SEC", "10"))

engine = create_async_engine(
    DATABASE_URL,
    echo=False,
    poolclass=NullPool,
    connect_args=_connect_args or {},
)

async_session_factory = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)


async def init_db() -> None:
    if os.getenv("SKIP_DB", "").lower() in {"1", "true", "yes"}:
        return
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.create_all)