def db_DropEverything(): _engine = get_engine() conn = _engine.connect() # the transaction only applies if the DB supports # transactional DDL, i.e. Postgresql, MS SQL Server trans = conn.begin() inspector = reflection.Inspector.from_engine(_engine) # gather all data first before dropping anything. # some DBs lock after things have been dropped in # a transaction. metadata = MetaData() tbs = [] all_fks = [] for table_name in inspector.get_table_names(): fks = [] for fk in inspector.get_foreign_keys(table_name): if not fk["name"]: continue fks.append(ForeignKeyConstraint((), (), name=fk["name"])) t = Table(table_name, metadata, *fks) tbs.append(t) all_fks.extend(fks) for fkc in all_fks: conn.execute(DropConstraint(fkc)) for table in tbs: conn.execute(DropTable(table)) trans.commit()
def override_get_db(): try: _engine = get_engine() logger.info(f"----- ADD DB {Base.metadata}-------") TestingSessionLocal = sessionmaker( autocommit=False, autoflush=False, bind=_engine ) db = TestingSessionLocal() yield db finally: db.close()
def db() -> Generator: _engine = get_engine() logger.info("-----GENERATE DB------") _engine = get_engine() TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=_engine) yield TestingSessionLocal()
def clean_db(): _engine = get_engine() db_DropEverything() Base.metadata.create_all(bind=_engine)