Skip to content

Instantly share code, notes, and snippets.

@grimen
Forked from absent1706/sqlalchemy-truncate_db.py
Created November 19, 2022 05:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save grimen/b9be724a7d234fe550d5c2febd4f9514 to your computer and use it in GitHub Desktop.
Save grimen/b9be724a7d234fe550d5c2febd4f9514 to your computer and use it in GitHub Desktop.
Sqlalchemy: Truncate all tables
def truncate_db(engine):
# delete all table data (but keep tables)
# we do cleanup before test 'cause if previous test errored,
# DB can contain dust
meta = MetaData(bind=engine, reflect=True)
con = engine.connect()
trans = con.begin()
con.execute('SET FOREIGN_KEY_CHECKS = 0;')
for table in meta.sorted_tables:
con.execute(table.delete())
con.execute('SET FOREIGN_KEY_CHECKS = 1;')
trans.commit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment