-
Notifications
You must be signed in to change notification settings - Fork 3
/
database.py
45 lines (37 loc) · 1.52 KB
/
database.py
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
from typing import AsyncIterator
import sqlalchemy as sa
import sqlalchemy.ext.asyncio as saa
from sqlalchemy import orm
from app import config
settings = config.get_settings()
# echo: if True, the Engine will log all statements as well as a repr() of their
# parameter lists to the default log handler, which defaults to sys.stdout for output.
#
# hide_parameters: Boolean, when set to True, SQL statement parameters will not be
# displayed in INFO logging nor will they be formatted into the string representation
# of StatementError objects.
#
# future=True: Use the 2.0 style Engine and Connection API.
engine = saa.create_async_engine(
settings.db_uri,
echo=settings.db_echo,
hide_parameters=settings.db_hide_params,
future=True,
)
# https://alembic.sqlalchemy.org/en/latest/naming.html
convention = {
"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",
}
mapper_registry = orm.registry(sa.MetaData(naming_convention=convention))
async def get_db() -> AsyncIterator[saa.AsyncSession]:
# https://docs.sqlalchemy.org/en/14/orm/extensions/asyncio.html#preventing-implicit-io-when-using-asyncsession
# expire_on_commit=False will prevent attributes from being expired after commit
async_session = saa.AsyncSession(engine, expire_on_commit=False)
try:
yield async_session
finally:
await async_session.close()