-
-
Save vkotovv/6281951 to your computer and use it in GitHub Desktop.
def clear_data(session): | |
meta = db.metadata | |
for table in reversed(meta.sorted_tables): | |
print 'Clear table %s' % table | |
session.execute(table.delete()) | |
session.commit() |
I'm not an expert but why not just..
db.reflect()
db.drop_all()
@alxvallejo; your commands would delete the tables with the data. @vkotovv gave an example of maintaining the tables while deleting their data.
this will only truncate the table or it will delete the tables also?
How to bypass IntegrityError when truncating data?
What is the type for the db object?
It depends. If using flask_sqlalchemy, then it is: <class 'flask_sqlalchemy.SQLAlchemy'>.
Why the order needs to reversed?
sorted_tables returns a list of tables sorted in order of foreign key dependency. reversed
ensure that children are deleted before parents to avoid foreign key violation.
How to bypass IntegrityError when truncating data?
I use a small script like below,
https://gist.github.com/premchalmeti/6aa70c12103025645542a481e6f55a07
Explicitly mention the tables having foreign key then concrete classes.
Thank you! Works like a charm for me!
Why not,
db.drop_all()
db.create_all()
db.session.commit()
Why not,
db.drop_all() db.create_all() db.session.commit()
It will spend a lot of time if u doing some like that often. For example, u can use author's code in tests, where u need to clear all tables after commits. Imagine u have 30-40 tests. How much time it will spend?
what is the session datatype?
@NailClaros In case you need to call the clear_data function by passing the session_datatype, you can use:
clear_data(db.session)
Worked great for me. Thanks!!