Web2py: delete all tables in a database in one expression?

I was wondering if web2py offers any way to delete all tables at once without specifying each table to be deleted?

Thanks in advance!

+4
source share
2 answers

db.tables() returns a list with the names of all tables in the db database

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 does not automatically perform DAL changes, for example, from the command line interface.)

+5
source

There is one problem in the previous answer: if you use more than one database, you can accidentally drop tables from the wrong database 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 application to another, it’s too easy to edit a link to db and not another. If db_two has tables with names corresponding to some tables in db_one, you may delete the table in the wrong database. It’s 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() 

"Do not repeat yourself."

0
source

Source: https://habr.com/ru/post/1334752/


All Articles