Run each migration in a separate transaction #1126
-
Is there a way to run each migration in a seperate transaction? I am using Postgres, and I am trying to set up something like this with auto-migrations. script.py.mako """${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}
# revision identifiers, used by Alembic.
revision = ${repr(up_revision)}
down_revision = ${repr(down_revision)}
branch_labels = ${repr(branch_labels)}
depends_on = ${repr(depends_on)}
def upgrade():
with context.begin_transaction():
${upgrades if upgrades else "pass"}
def downgrade():
with context.begin_transaction():
${downgrades if downgrades else "pass"} env.py def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
connectable = engine_from_config(
config.get_section(config.config_ini_section),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
with connectable.connect() as connection:
context.configure(connection=connection, target_metadata=target_metadata)
# >>>> removed the transaction block here
context.run_migrations() A couple things. This feels a bit hacky, and I am just wondering if there is a better way to do it. Also, the mako template doesn't seem to add extra whitespace inside of the context manager. example revision def upgrade():
with context.begin_transaction():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('transaction',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('amount', sa.Numeric(), nullable=True),
sa.PrimaryKeyConstraint('id', name=op.f('pk_transaction'))
)
# ### end Alembic commands ###
def downgrade():
with context.begin_transaction():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('transaction')
# ### end Alembic commands ### |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
hi, |
Beta Was this translation helpful? Give feedback.
-
absolutely, you can set transaction_per_migration for this.
Right...indentation is not part of what it renders, if you wanted to do that you'd break it into separate methods. |
Beta Was this translation helpful? Give feedback.
absolutely, you can set transaction_per_migration for this.
Right...indentation is not part of what it renders, if you wanted to do that you'd break it into separate methods.