Skip to content

Instantly share code, notes, and snippets.

@vkotovv
Created August 20, 2013 14:08
Show Gist options
  • Star 37 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save vkotovv/6281951 to your computer and use it in GitHub Desktop.
Save vkotovv/6281951 to your computer and use it in GitHub Desktop.
Clear data for all tables via flask-sqlalchemy
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()
@sfsekaran
Copy link

Worked great for me. Thanks!!

@alxvallejo
Copy link

I'm not an expert but why not just..
db.reflect()
db.drop_all()

@Jitsusama
Copy link

Jitsusama commented Feb 15, 2018

@alxvallejo; your commands would delete the tables with the data. @vkotovv gave an example of maintaining the tables while deleting their data.

@ashutosh-sharma
Copy link

ashutosh-sharma commented Feb 16, 2018

this will only truncate the table or it will delete the tables also?

@laalaguer
Copy link

@ashutosh-sharma

Truncate.

db.drop_all() == "DROP TABLE xx"
table.delete() == "TUNCTATE TABLE xx"

@roelzkie15
Copy link

How to bypass IntegrityError when truncating data?

@mchesler613
Copy link

What is the type for the db object?

@bc291
Copy link

bc291 commented Feb 26, 2019

It depends. If using flask_sqlalchemy, then it is: <class 'flask_sqlalchemy.SQLAlchemy'>.

@VidyaKamath
Copy link

Why the order needs to reversed?

@gzcf
Copy link

gzcf commented Aug 17, 2020

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.

@premchalmeti
Copy link

premchalmeti commented Aug 19, 2020

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.

@aaronkurz
Copy link

Thank you! Works like a charm for me!

@Divide-By-0
Copy link

Why not,

    db.drop_all()
    db.create_all()
    db.session.commit()

@mesiriak
Copy link

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?

@NailClaros
Copy link

what is the session datatype?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment