def mem_db(do_echo=False): from anchore_engine.db.entities.common import ( get_engine, initialize, do_disconnect, init_thread_session, end_session, ) from anchore_engine.db.entities.upgrade import do_create_tables conn_str = "sqllite://:memory:" config = {"credentials": {"database": {"db_connect": conn_str, "db_echo": do_echo}}} try: logger.info("Initializing connection: {}".format(config)) ret = initialize(localconfig=config) init_thread_session(force_new=True) engine = get_engine() logger.info("Dropping db if found") engine.execute("DROP SCHEMA public CASCADE") engine.execute("CREATE SCHEMA public") engine.execute("GRANT ALL ON SCHEMA public TO postgres") engine.execute("GRANT ALL ON SCHEMA public TO public") # Now ready for anchore init (tables etc) logger.info("Creating tables") do_create_tables() yield ret finally: logger.info("Cleaning up/disconnect") end_session() do_disconnect()
def cls_anchore_db(connection_str=None, do_echo=False): """ Sets up a db connection to an existing db, and fails if not found/present. This is for use in legacy unittest frameworks where it is set once at the class level, not on each function. :return: """ from anchore_engine.db.entities.common import ( get_engine, initialize, do_disconnect, init_thread_session, end_session, ) from anchore_engine.db.entities.upgrade import do_create_tables conn_str = connection_str if connection_str else os.getenv( "ANCHORE_TEST_DB_URL") config = { "credentials": { "database": { "db_connect": conn_str, "db_echo": do_echo } } } try: logger.info("Initializing connection: {}".format(config)) ret = initialize(localconfig=config) init_thread_session(force_new=True) engine = get_engine() logger.info("Dropping db if found") engine.execute("DROP SCHEMA public CASCADE") engine.execute("CREATE SCHEMA public") engine.execute("GRANT ALL ON SCHEMA public TO postgres") engine.execute("GRANT ALL ON SCHEMA public TO public") # Now ready for anchore init (tables etc) logger.info("Creating tables") do_create_tables() yield ret finally: logger.info("Cleaning up/disconnect") end_session() do_disconnect()
def anchore_db() -> ContextManager[bool]: """ Sets up a db connection to an existing db, and fails if not found/present Different from the fixture in test/fixtures.py in that it does not drop existing data upon making a connection :return: True after connection setup (not actual connection object). :rtype: ContextManager[bool] """ conn_str = os.getenv("ANCHORE_TEST_DB_URL") assert conn_str config = {"credentials": {"database": {"db_connect": conn_str}}} try: ret = initialize(localconfig=config) yield ret finally: end_session() do_disconnect()
def disconnect(self): """ Completely tear down the connection to force sqlite to refresh the db :return: """ global ThreadLocalSession, Session, engine end_session() if ThreadLocalSession: ThreadLocalSession.close_all() ThreadLocalSession = None if Session: Session.close_all() Session = None if engine: engine.dispose() engine = None