如果发生错误,如何回滚所有迁移?

时间:2019-02-01 10:56:59

标签: sqlalchemy alembic

似乎有办法rollback进行所有错误更改,但是示例脚本似乎很奇怪,因为脚本中使用的引用session从未定义或导入:

from alembic import context
import myapp
import sys

db_1 = myapp.db_1
db_2 = myapp.db_2

def run_migrations_offline():
    """Run migrations *without* a SQL connection."""

    for name, engine, file_ in [
        ("db1", db_1, "db1.sql"),
        ("db2", db_2, "db2.sql"),
    ]:
        context.configure(
                    url=engine.url,
                    transactional_ddl=False,
                    output_buffer=open(file_, 'w'))
        context.execute("-- running migrations for '%s'" % name)
        context.run_migrations(name=name)
        sys.stderr.write("Wrote file '%s'" % file_)

def run_migrations_online():
    """Run migrations *with* a SQL connection."""

    for name, engine in [
        ("db1", db_1),
        ("db2", db_2),
    ]:
        connection = engine.connect()
        context.configure(connection=connection)
        try:
            context.run_migrations(name=name)
            session.commit()    # <---
        except:
            session.rollback()  # <---
            raise

if context.is_offline_mode():
    run_migrations_offline()
else:
    run_migrations_online()

这很奇怪(imho),这不是默认行为,但是我想从迁移脚本回滚个更改,以防发生错误。

我该怎么做?

0 个答案:

没有答案