3

根据某些 DBMS 的这个问题,可以回滚 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']
4

1 回答 1

4
  1. 使用 Postgresql 或 SQL Server。MySQL、Oracle支持事务 DDL。最新版本的 SQLite 似乎确实支持事务性 DDL。但是Python sqlite3 驱动程序没有

  2. 简单的食谱:

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

    如果您在“with:”中引发异常,事务将被回滚。

  3. 想自己看,OK:

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

要了解事务范围,我建议您阅读http://docs.sqlalchemy.org/en/latest/core/connections.html

于 2013-03-29T14:28:44.873 回答