49 lines
1.7 KiB
Python
49 lines
1.7 KiB
Python
import asyncio
|
|
|
|
from sqlalchemy import CursorResult
|
|
from tenacity import retry, stop_after_attempt, wait_exponential
|
|
|
|
from src.db.database import Database
|
|
from src.logging.get_logger import get_logger
|
|
from src.system_var import environment
|
|
|
|
logger = get_logger(__name__)
|
|
|
|
|
|
class AsyncDatabase(Database):
|
|
"""データベース非同期操作クラス"""
|
|
|
|
def __init__(self, username: str, password: str, host: str, port: int, schema: str) -> None:
|
|
super().__init__(username, password, host, port, schema)
|
|
|
|
@classmethod
|
|
def get_instance(cls):
|
|
return cls(
|
|
username=environment.DB_USERNAME,
|
|
password=environment.DB_PASSWORD,
|
|
host=environment.DB_HOST,
|
|
port=environment.DB_PORT,
|
|
schema=environment.DB_SCHEMA
|
|
)
|
|
|
|
@retry(
|
|
wait=wait_exponential(
|
|
multiplier=environment.DB_CONNECTION_RETRY_INTERVAL_INIT,
|
|
min=environment.DB_CONNECTION_RETRY_INTERVAL_MIN_SECONDS,
|
|
max=environment.DB_CONNECTION_RETRY_INTERVAL_MAX_SECONDS
|
|
),
|
|
stop=stop_after_attempt(environment.DB_CONNECTION_MAX_RETRY_ATTEMPT))
|
|
async def connect(self):
|
|
await asyncio.get_event_loop().run_in_executor(None, super().connect)
|
|
|
|
async def execute_select(self, select_query: str, parameters=None) -> list[dict]:
|
|
res = await asyncio.get_event_loop().run_in_executor(None, super().execute_select, select_query, parameters)
|
|
return res
|
|
|
|
async def execute(self, query: str, parameters=None) -> CursorResult:
|
|
res = await asyncio.get_event_loop().run_in_executor(None, super().execute, query, parameters)
|
|
return res
|
|
|
|
async def disconnect(self):
|
|
await asyncio.get_event_loop().run_in_executor(None, super().disconnect)
|