import traceback
from contextlib import contextmanager

from sqlmodel import create_engine, Session

from fastapi_dream_core.application_dependencies.application_dependencies_abc import ApplicationDependenciesABC
from fastapi_dream_core.utils import logger


class DatabaseSQLModel(ApplicationDependenciesABC):

    def __init__(self, db_url: str, echo_queries: bool = False) -> None:
        self._engine = create_engine(db_url, echo=echo_queries)

    def readiness(self) -> bool:
        with Session(self._engine) as session:
            try:
                database_status = session.connection().connection.is_valid
                logger.debug(f"DatabaseSQLModel.readiness = {database_status}")
                return True

            except Exception:
                traceback.print_exc()
                return False

    @contextmanager
    def session(self) -> Session:
        with Session(self._engine) as session:
            try:
                yield session
            except Exception:
                logger.exception("Session rollback because of exception")
                session.rollback()
                raise
            finally:
                session.close()

    def __str__(self):
        return "DatabaseSQLModel"

sqlmodel.create_engine fastapi_dream_core.utils.logger.exception fastapi_dream_core.utils.logger.debug sqlmodel.Session traceback.print_exc
[((408, 448), 'sqlmodel.create_engine', 'create_engine', (['db_url'], {'echo': 'echo_queries'}), '(db_url, echo=echo_queries)\n', (421, 448), False, 'from sqlmodel import create_engine, Session\n'), ((496, 517), 'sqlmodel.Session', 'Session', (['self._engine'], {}), '(self._engine)\n', (503, 517), False, 'from sqlmodel import create_engine, Session\n'), ((896, 917), 'sqlmodel.Session', 'Session', (['self._engine'], {}), '(self._engine)\n', (903, 917), False, 'from sqlmodel import create_engine, Session\n'), ((638, 701), 'fastapi_dream_core.utils.logger.debug', 'logger.debug', (['f"""DatabaseSQLModel.readiness = {database_status}"""'], {}), "(f'DatabaseSQLModel.readiness = {database_status}')\n", (650, 701), False, 'from fastapi_dream_core.utils import logger\n'), ((777, 798), 'traceback.print_exc', 'traceback.print_exc', ([], {}), '()\n', (796, 798), False, 'import traceback\n'), ((1023, 1080), 'fastapi_dream_core.utils.logger.exception', 'logger.exception', (['"""Session rollback because of exception"""'], {}), "('Session rollback because of exception')\n", (1039, 1080), False, 'from fastapi_dream_core.utils import logger\n')]