alembic_version Table Not Persisting Revision After Programmatic Migration #1638
-
I’m running Alembic migrations programmatically using EnvironmentContext because Details: What Works: During the migration, both a direct SQL query and What Doesn’t Work: On the next run, MigrationContext.get_current_revision() returns None, indicating the revision wasn’t persisted. Key Observations:
After the script ends, querying the table shows it’s empty:
Alembic logs Code Snippet: def alembic_upgrade():
global prod_url, config
log.info("Attempting database upgrade")
engine = create_engine(prod_url)
try:
with engine.connect() as conn:
script = ScriptDirectory.from_config(config)
mc = MigrationContext.configure(conn)
head_rev = script.get_current_head()
current_rev = mc.get_current_revision()
if current_rev == head_rev:
log.info("Database is up to date, skipping upgrade")
return
def do_upgrade(revision, context):
log.info(f"do_upgrade revision: {revision}")
log.info(f"do_upgrade head_revision: {head_rev}")
return script._upgrade_revs("head", revision)
env = EnvironmentContext(config, script)
env.configure(
connection=conn,
target_metadata=target_metadata, # Defined elsewhere
fn=do_upgrade,
dialect_opts={"paramstyle": "named"}
)
with env.begin_transaction():
env.run_migrations()
# aiiiiii
with conn.execute(text("SELECT version_num FROM alembic_version")) as result:
rows = result.fetchall()
log.info(f"alembic_version after migration: {rows}")
# iiiiiia
after_rev = MigrationContext.configure(conn).get_current_revision()
log.info(f"Database upgraded from {current_rev} to {after_rev}")
except Exception as e:
log.error(f"Error during database upgrade: {e}")
raise e
finally:
engine.dispose() Logs:
Questions: Is there a better way to run migrations programmatically that retains script control post-migration, avoiding EnvironmentContext? Could this relate to MariaDB transaction handling, given the "non-transactional DDL" assumption? Additional Notes: Schema changes persist, but alembic_version updates do not. Any help or suggestions would be greatly appreciated! |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
yes add a |
Beta Was this translation helpful? Give feedback.
-
|
Beta Was this translation helpful? Give feedback.
yes add a
conn.commit()
call after all the database work is done , otherwise transaction is not committed here