Repository navigation
Expand file tree
/
Copy pathdatabase.py
More file actions
84 lines (67 loc) Β· 2.06 KB
/
Copy pathdatabase.py
File metadata and controls
84 lines (67 loc) Β· 2.06 KB
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
"""Database engine, session factories, and base declarative model."""
from collections.abc import AsyncGenerator, Generator
from typing import Any
from sqlalchemy import MetaData, create_engine
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from sqlalchemy.orm import DeclarativeBase, Session, sessionmaker
from app.core.config import get_settings
settings = get_settings()
NAMING_CONVENTION: dict[str, str] = {
"ix": "ix_%(column_0_label)s",
"uq": "uq_%(table_name)s_%(column_0_name)s",
"ck": "ck_%(table_name)s_%(constraint_name)s",
"fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
"pk": "pk_%(table_name)s",
}
class Base(DeclarativeBase):
metadata = MetaData(naming_convention=NAMING_CONVENTION)
def to_dict(self) -> dict[str, Any]:
return {c.name: getattr(self, c.name) for c in self.__table__.columns}
async_engine = create_async_engine(
settings.database_url,
echo=settings.app_debug and not settings.is_production,
pool_pre_ping=True,
pool_size=10,
max_overflow=20,
pool_recycle=3600,
)
AsyncSessionLocal = async_sessionmaker(
bind=async_engine,
class_=AsyncSession,
expire_on_commit=False,
autoflush=False,
autocommit=False,
)
sync_engine = create_engine(
settings.database_url_sync,
echo=False,
pool_pre_ping=True,
pool_size=10,
max_overflow=20,
pool_recycle=3600,
)
SyncSessionLocal = sessionmaker(
bind=sync_engine,
class_=Session,
expire_on_commit=False,
autoflush=False,
autocommit=False,
)
async def get_db() -> AsyncGenerator[AsyncSession, None]:
async with AsyncSessionLocal() as session:
try:
yield session
await session.commit()
except Exception:
await session.rollback()
raise
def get_sync_db() -> Generator[Session, None, None]:
session = SyncSessionLocal()
try:
yield session
session.commit()
except Exception:
session.rollback()
raise
finally:
session.close()