"""MySQL Connector. Manages interactions with MySQL. """ from contextlib import contextmanager import functools from flask import g from oto import response from sqlalchemy import create_engine from sqlalchemy import exc from sqlalchemy.orm import sessionmaker, declarative_base from lyrics import config from sentry_sdk import capture_exception # please don't use the following private variables directly; # use db_session db_engine = create_engine( config.DB_URL, connect_args=config.CONNECT_ARGS, poolclass=config.POOL_CLASS) _db_session = sessionmaker(bind=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: # noqa session.rollback() raise finally: session.close() def wrap_db_errors(function): """Decorate the given function with logic to handle SQLAlchemy errors. If a SQLAlchemy exception is thrown, it will be caught and logged and the function will return a fatal response. Args: function (func): the function to decorate Returns: func: 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: capture_exception(exception) g.ows.log.error('DB error: {}'.format(exception)) return response.create_fatal_response() return function_return return call_function_with_error_handling