"""MySQL Connector. Manages interactions with MySQL for ows_product_configuration database. """ from contextlib import contextmanager import functools from oto import response from sqlalchemy import create_engine from sqlalchemy import exc from sqlalchemy import pool from sqlalchemy.orm import declarative_base from sqlalchemy.orm import sessionmaker from product_configuration import config from product_configuration.connectors.sentry import sentry_client def _create_engine(db_url, pool_class): """Create engine based on config settings. Args: db_url (str): DB connection string pool_class (object): SQLAlchemy DB pool class Returns: Engine: SQLAlchemy DB connection engine """ if pool_class == pool.QueuePool: return create_engine( db_url, poolclass=pool_class, pool_size=config.POOL_SIZE, max_overflow=config.POOL_MAX_OVERFLOW, pool_recycle=config.POOL_RECYCLE_MS, pool_pre_ping=config.POOL_PRE_PING) return create_engine(db_url, poolclass=pool_class) # please don't use the following private variables directly; # use db_session _db_engine = _create_engine(config.DB_CONNECTION_URL, config.DB_POOLCLASS) _db_session = sessionmaker(_db_engine) BaseModel = declarative_base() @contextmanager def db_session(): """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: yield session session.commit() except Exception: session.rollback() raise finally: session.close() def wrap_db_errors(function): """Decorate the given function with logic to handle SQLAlcehmy errors. If a SQLAlchemy exception is thrown, it will be caught and logged and the function will return a fatal response. Args: function (function): the function to decorate Returns: function: function decorated with error-handling logic """ @functools.wraps(function) def call_function_with_error_handling(*args, **kwargs): try: function_return = function(*args, **kwargs) except exc.SQLAlchemyError as exception: sentry_client.capture_exception(exception) return response.create_fatal_response() return function_return return call_function_with_error_handling