4

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!

Andrei
  • 71
  • 1
  • 3

2 Answers2

5

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.)

amit kumar
  • 20,438
  • 23
  • 90
  • 126
Leftium
  • 16,497
  • 6
  • 64
  • 99
  • In my use case, I needed to re-populate my database (using db_wizard_populate.py) after changes in schema. For this, one does not have to `drop()`, but `truncate()`. – amit kumar Jun 06 '11 at 03:53
0

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".

Chris Johnson
  • 20,650
  • 6
  • 81
  • 80