SQLAlchemy, clear database content but don't drop the schema

后端 未结 3 1578
梦毁少年i
梦毁少年i 2020-12-13 00:01

I\'m developing a Pylons app which is based on exisitng database, so I\'m using reflection. I have an SQL file with the schema that I used to create my test database. That\'

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-13 00:08

    For PostgreSQL using TRUNCATE:

    with contextlib.closing(engine.connect()) as con:
        trans = con.begin()
        con.execute('TRUNCATE {} RESTART IDENTITY;'.format(
            ','.join(table.name 
                     for table in reversed(Base.metadata.sorted_tables))))
        trans.commit()
    

    Note: RESTART IDENTITY; ensures that all sequences are reset as well. However, this is slower than the DELETE recipe by @aknuds1 by 50%.

    Another recipe is to drop all tables first and then recreate them. This is slower by another 50%:

    Base.metadata.drop_all(bind=engine)
    Base.metadata.create_all(bind=engine)
    

提交回复
热议问题