It seems there is a way to rollback all changes on error but the example script seems odd because the reference session
, used in the script, is never defined or imported:
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()
It's very weird (imho) that this is no default behavior but I want to rollback every change from a migration script in case an error occurs.
How can I do that?