-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatabase.py
77 lines (59 loc) · 1.85 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
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
import logging
from contextlib import asynccontextmanager
import asyncpg
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, AsyncEngine, AsyncConnection
from sqlalchemy.ext.asyncio import async_sessionmaker
from config import Config
def get_db_engine(database_url: str) -> AsyncEngine:
"""
Creates a SQLAlchemy session for the specified database URL.
:param database_url: The URL of the database to connect to.
:return: A tuple containing an instance of SQLAlchemy Session and an Engine object.
"""
try:
logging.info('trying to connect to database')
async_engine = create_async_engine(
database_url,
future=True,
# echo=True
)
logging.info(f"Connected to database successfully")
return async_engine
except SQLAlchemyError as e:
logging.error(f"Error connecting to database: {str(e)}")
raise e
def async_session_generator():
engine = get_db_engine(
Config.SQLALCHEMY_DATABASE_URI
)
return async_sessionmaker(
engine,
class_=AsyncSession
)
@asynccontextmanager
async def get_session() -> AsyncSession:
try:
async_session = async_session_generator()
async with async_session() as session:
yield session
except:
await session.rollback()
raise
finally:
await session.close()
@asynccontextmanager
async def get_connection() -> AsyncConnection:
engine = get_db_engine(
Config.SQLALCHEMY_DATABASE_URI
)
try:
async with engine.connect() as connect:
yield connect
finally:
await connect.close()
async def connect() -> asyncpg.connection.Connection:
conn = await asyncpg.connect(
dsn=Config.ASYNCPG_CONNECTION_URI
)
return conn