"""MySQL Connector. Manages interactions with MySQL. """ from collections.abc import Generator from contextlib import contextmanager from sqlalchemy import Engine, create_engine, text from sqlalchemy.orm import DeclarativeBase, Session, sessionmaker from video import config def _create_engine(db_url: str) -> Engine: """Create engine based on config settings.""" db_engine = create_engine( db_url, pool_size=config.SQLALCHEMY_POOL_SIZE, max_overflow=config.SQLALCHEMY_POOL_MAX_OVERFLOW, pool_recycle=config.SQLALCHEMY_POOL_RECYCLE_MS, pool_pre_ping=config.SQLALCHEMY_POOL_PRE_PING, pool_timeout=config.SQLALCHEMY_POOL_TIMEOUT, ) return db_engine _db_engine = _create_engine(config.VIDEO_DB_URL) _db_session = sessionmaker(bind=_db_engine) ar_db_engine = _create_engine(config.AR_DB_URL) ar_database_session = sessionmaker(bind=ar_db_engine) class BaseModel(DeclarativeBase): pass class ArModel(DeclarativeBase): pass @contextmanager def db_session( turn_off_foreign_key_constraint: bool = False, ) -> Generator[Session, None, None]: """Provide a transactional scope around a series of operations. Taken from http://docs.sqlalchemy.org/en/latest/orm/session_basics.html. This handles rollback and closing of session, so there is no need to do that throughout the code. Usage: with db_session() as session: session.execute(query) """ session = _db_session() try: if turn_off_foreign_key_constraint: session.execute(text("SET FOREIGN_KEY_CHECKS = 0;")) yield session session.commit() except Exception: session.rollback() raise finally: if turn_off_foreign_key_constraint: session.execute(text("SET FOREIGN_KEY_CHECKS = 1;")) session.close() @contextmanager def ar_db_session( turn_off_foreign_key_constraint: bool = False, ) -> Generator[Session, None, None]: """Provide transactional scope around series of operations for art_relations. Taken from http://docs.sqlalchemy.org/en/latest/orm/session_basics.html. This handles rollback and closing of session, so there is no need to do that throughout the code. Usage: with ar_database_session() as session: session.execute(query) """ session = ar_database_session() try: if turn_off_foreign_key_constraint: session.execute(text("SET FOREIGN_KEY_CHECKS = 0;")) yield session session.commit() except Exception: session.rollback() raise finally: if turn_off_foreign_key_constraint: session.execute(text("SET FOREIGN_KEY_CHECKS = 1;")) session.close()