是否可以在sqlalchemy中回滚create_all?

时间:2013-03-26 23:36:06

标签: sql transactions sqlalchemy rollback ddl

根据某些DBMS的THIS问题,可以回滚CREATE TABLE语句。 特别是sqlite是可能的(尽管它没有文档记录)。

所以我的问题是,是否可以在sqlalchemy中回滚create_all? 我试图编写一些测试代码,但似乎不起作用:

>>> engine = create_engine('sqlite:///:memory:')
>>> engine
Engine(sqlite:///:memory:)
>>> Session = sessionmaker(bind=engine)
>>> connection = engine.connect()
>>> session = Session(bind=connection)
>>> engine.table_names()
[]
>>> transaction = connection.begin()
>>> Base = declarative_base()
>>> class Test(Base):
...    __tablename__ = 'TEST'
...    id = Column(Integer, primary_key=True)
...
>>> Base.metadata.bind = engine
>>> Base.metadata.create_all()
>>> engine.table_names()
[u'TEST']
>>> transaction.rollback()
>>> session.close()
>>> connection.close()
>>> engine.table_names()
[u'TEST']

1 个答案:

答案 0 :(得分:4)

  1. 使用Postgresql或SQL Server。 MySQL,Oracle不支持 支持事务DDL。最近版本的SQLite似乎支持事务DDL。然而,Python sqlite3 driver does not

  2. 简单的食谱:

    with engine.begin() as conn:
        metadata.create_all(conn)
    

    如果你在“with:”中引发异常,交易将被回滚。

  3. 想亲眼看看,好的:

    from sqlalchemy import inspect   # need to be running 0.8 for this
    
    with engine.connect() as conn:
       trans = conn.begin()
       metadata.create_all(conn)
       inspector = inspect(conn)
       table_names = inspector.get_table_names()
       trans.rollback()
       inspector = inspect(conn)
       rolled_back_table_names = inspector.get_table_names()
    
  4. 要了解交易范围,建议您阅读http://docs.sqlalchemy.org/en/latest/core/connections.html