-
Notifications
You must be signed in to change notification settings - Fork 65
Expand file tree
/
Copy pathdatabase.py
More file actions
67 lines (56 loc) · 2.05 KB
/
database.py
File metadata and controls
67 lines (56 loc) · 2.05 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
from collections.abc import AsyncGenerator
from fastapi.exceptions import ResponseValidationError
from rotoger import get_logger
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
from app.config import settings as global_settings
logger = get_logger()
engine = create_async_engine(
global_settings.asyncpg_url.unicode_string(),
future=True,
echo=True,
)
test_engine = create_async_engine(
global_settings.test_asyncpg_url.unicode_string(),
future=True,
echo=False,
)
# expire_on_commit=False will prevent attributes from being expired
# after commit.
AsyncSessionFactory = async_sessionmaker(
engine,
autoflush=False,
expire_on_commit=False,
)
TestAsyncSessionFactory = async_sessionmaker(
test_engine,
autoflush=False,
expire_on_commit=False,
)
# Dependency
async def get_db() -> AsyncGenerator:
async with AsyncSessionFactory() as session:
try:
yield session
await session.commit()
except SQLAlchemyError:
# Re-raise SQLAlchemy errors to be handled by the global handler
raise
except Exception as ex:
# Only log actual database-related issues, not response validation
if not isinstance(ex, ResponseValidationError):
await logger.aerror(f"Database-related error: {repr(ex)}")
raise # Re-raise to be handled by appropriate handlers
async def get_test_db() -> AsyncGenerator:
async with TestAsyncSessionFactory() as session:
try:
yield session
await session.commit()
except SQLAlchemyError:
# Re-raise SQLAlchemy errors to be handled by the global handler
raise
except Exception as ex:
# Only log actual database-related issues, not response validation
if not isinstance(ex, ResponseValidationError):
await logger.aerror(f"Database-related error: {repr(ex)}")
raise # Re-raise to be handled by appropriate handlers