SQLAlchemy,清除数据库内容但不删除架构 [英] SQLAlchemy, clear database content but don't drop the schema

查看:31
本文介绍了SQLAlchemy,清除数据库内容但不删除架构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个基于现有数据库的 Pylons 应用程序,所以我正在使用反射.我有一个 SQL 文件,其中包含用于创建测试数据库的架构.这就是为什么我不能简单地使用 drop_allcreate_all.

I'm developing a Pylons app which is based on exisitng database, so I'm using reflection. I have an SQL file with the schema that I used to create my test database. That's why I can't simply use drop_all and create_all.

我想写一些单元测试,每次测试后我都面临清除数据库内容的问题.我只想擦除所有数据但保持表格完好无损.这可能吗?

I would like to write some unit tests and I faced the problem of clearing the database content after each test. I just want to erase all the data but leave the tables intact. Is this possible?

该应用程序使用 Postgres,这也是测试时必须使用的.

The application uses Postgres and this is what has to be used also for the tests.

推荐答案

我在 SQLAlchemy Google 小组中询问了同样的问题,我得到了一个看起来运行良好的配方(我所有的表都被清空了).请参阅线程以供参考.

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

我修改了代码以相反的顺序删除表;据说这应该确保在父母之前删除孩子.

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

这篇关于SQLAlchemy,清除数据库内容但不删除架构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆