def reflect_table(engine, klass): """Inspect and reflect objects""" try: meta = MetaData() meta.reflect(bind=engine) except OperationalError as e: raise DatabaseError(error=e.orig.args[1], code=e.orig.args[0]) # Try to reflect from any of the supported tables table = None for tb in klass.tables(): if tb in meta.tables: table = meta.tables[tb] break if table is None: raise DatabaseError(error="Invalid schema. Table not found", code="-1") # Map table schema into klass mapper(klass, table, column_prefix=klass.column_prefix()) return table
def close_database_session(session): """Close connection with the database""" try: session.close() except OperationalError as e: raise DatabaseError(error=e.orig.args[1], code=e.orig.args[0])
def create_database_session(engine): """Connect to the database""" try: Session = sessionmaker(bind=engine) return Session() except OperationalError as e: raise DatabaseError(error=e.orig.args[1], code=e.orig.args[0])
def __init__(self, user, password, database, host='localhost', port='3306'): self._engine = self.build_engine(user, password, database, host, port) self._Session = sessionmaker(bind=self._engine) try: self.__create_schema(self._engine) except OperationalError as e: raise DatabaseError(error=e.orig.args[1], code=e.orig.args[0])
def execute(cls, engine, query): try: conn = engine.connect() conn.execute(query) except (OperationalError, ProgrammingError, InternalError) as e: code = e.orig.args[0] if isinstance(e, ProgrammingError) and code == 1007: # Query for creating database failed because it exists raise DatabaseExists(error=e.orig.args[1], code=code) else: raise DatabaseError(error=e.orig.args[1], code=code)
def test_message(self): """Make sure that prints the correct error""" e = DatabaseError(error="Unknown database 'mydb'", code=1049) self.assertEqual("Unknown database 'mydb' (err: 1049)", str(e))
def execute(cls, engine, query): try: conn = engine.connect() conn.execute(query) except (OperationalError, ProgrammingError) as e: raise DatabaseError(error=e.orig.args[1], code=e.orig.args[0])
def build_engine(cls, user, password, database, host='localhost', port='3306'): try: return create_database_engine(user, password, database, host, port) except OperationalError as e: raise DatabaseError(error=e.orig.args[1], code=e.orig.args[0])