I was wondering if web2py offers any way to drop all tables at once, without having to specify each table to be deleted?
Thanks in advance!
db.tables()
returns a list with the names of all tables in the database db
So you can do:
for table_name in db.tables():
db[table_name].drop()
db.commit()
(The final db.commit()
is only necessary if Web2Py isn't committing your DAL changes automatically, for example from the command line interface.)
The previous answer has one problem -- if you are using more than one database, you could accidentally drop tables from the wrong DB if you make a cut-and-paste error. Example --
for table_name in db_one.tables():
db_two[table_name].drop()
If you copy code from one model or app to another, it is too easy to edit one db reference and not the other. If db_two has tables with names matching some tables in db_one, you could drop a table in the wrong database. Better to write a trivial function that takes db as a parameter --
def dropdb(thedb):
for table_name in thedb.tables():
thedb[table_name].drop()
"Don't repeat yourself".