SQLAlchemy, clear database content but don't drop the schema

社会主义新天地 提交于 2019-11-28 16:58:23

I asked about the same thing on the SQLAlchemy Google group, and I got a recipe that appears to work well (all my tables are emptied). See the thread for reference.

My code (excerpt) looks like this:

import contextlib
from sqlalchemy import MetaData

meta = MetaData()

with contextlib.closing(engine.connect()) as con:
    trans = con.begin()
    for table in reversed(meta.sorted_tables):
        con.execute(table.delete())
    trans.commit()

Edit: I modified the code to delete tables in reverse order; supposedly this should ensure that children are deleted before parents.

For PostgreSQL using TRUNCATE:

with contextlib.closing(engine.connect()) as con:
    trans = con.begin()
    con.execute('TRUNCATE {} RESTART IDENTITY;'.format(
        ','.join(table.name 
                 for table in reversed(Base.metadata.sorted_tables))))
    trans.commit()

Note: RESTART IDENTITY; ensures that all sequences are reset as well. However, this is slower than the DELETE recipe by @aknuds1 by 50%.

Another recipe is to drop all tables first and then recreate them. This is slower by another 50%:

Base.metadata.drop_all(bind=engine)
Base.metadata.create_all(bind=engine)

How about using truncate:

TRUNCATE [ TABLE ] name [, ...]

(http://www.postgresql.org/docs/8.4/static/sql-truncate.html)

This will delete all the records in the table, but leave the schema in tact.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!