Exemplo n.º 1
0
def clear_db():
    db = SessionLocal()
    models = [
        cls for name, cls in base.__dict__.items()
        if isinstance(cls, type) and name != "Base"
    ]
    model_table_names = [m.__tablename__ for m in models]
    model_table_names.append("alembic_version")
    # Drop records from the static tables
    for model in models:
        try:
            if model.__tablename__ == "user":  # leave the superuser
                db.query(model).filter(model.id > 1).delete()
            else:
                db.query(model).delete()
            # print(f'Deleted {n} {model.__name__}s')
            db.commit()
        except Exception as e:
            print(f"Failed to delete {model}s")
            print(e)
            db.rollback()

    # Drop the dynamically created interface tables
    metadata = MetaData()
    metadata.bind = engine
    metadata.reflect(bind=engine)
    all_tables = metadata.tables
    for name, table in all_tables.items():
        if name not in model_table_names:
            table.drop()
Exemplo n.º 2
0
def get_db() -> Generator:
    try:
        db = SessionLocal()
        yield db
    finally:
        try:
            db.commit()
        except exc.SQLAlchemyError:
            db.rollback()
            backend_logger.error("ERROR DB COMMIT", exc_info=True)
        db.close()
Exemplo n.º 3
0
def get_db() -> Generator:
    try:
        db = SessionLocal()
        yield db
    except Exception as e:
        print(str(e))
        traceback.print_exc()
        db.rollback()
    finally:
        db.commit()
        db.close()
Exemplo n.º 4
0
def create_licenses_task(licenses: List[Dict[str, str]]) -> List[Dict[str, str]]:
    db = SessionLocal()
    objs_in = [
        schemas.LicenseCreate(name=license["name"], url=license["url"])
        for license in licenses
    ]
    try:
        licenses_db = crud.license.create_multi(
            db=db,
            objs_in=objs_in,
        )
        return jsonable_encoder(licenses_db)
    except IntegrityError:
        db.rollback()
        licenses_db = [
            crud.license.create(db=db, obj_in=obj_in, merge=True) for obj_in in objs_in
        ]
        return jsonable_encoder((licenses_db))
    finally:
        db.close()