How to autorun migrations in sqlalchemy 2.0? #1100
Answered
by
zzzeek
jtpavlock
asked this question in
Usage Questions
-
Previously, I used the following code so a user's databases (local sqlite) could be automatically upgraded when a new migration is present. # Config object in my_app,py
def _init_db(self, create_tables: bool = True):
"""Initializes the database.
Args:
create_tables: Whether or not to create and update the db tables.
If doing db migrations manually, e.g. in alembic, this should be False.
"""
db_path = self.config_dir / "library.db"
if not self.engine:
self.engine = create_engine("sqlite:///" + str(db_path))
session_factory.configure(bind=self.engine)
# create and update database tables
if create_tables:
config_path = Path(__file__)
alembic_cfg = alembic.config.Config(
str(config_path.parents[1] / "alembic" / "alembic.ini")
)
alembic_cfg.attributes["configure_logger"] = False
with self.engine.begin() as connection:
alembic_cfg.attributes["connection"] = connection
alembic.command.upgrade(alembic_cfg, "head") # 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 = config.attributes.get("connection", None)
if not connectable:
# only create Engine if we don't have a Connection from the outside
moe_config = Config(init_db=False)
moe_config._init_db(create_tables=False)
connectable = moe_config.engine
# When connectable is already a Connection object, calling
# connect() gives us a *branched connection*.
with connectable.connect() as connection:
context.configure(
connection=connection, target_metadata=target_metadata, render_as_batch=True
)
with context.begin_transaction():
context.run_migrations()
run_migrations_online() But this used "connection branching" which was allowed in 1.4, but has since been deprecated. I'm failing to find an equivalent way of achieving what I want in 2.0, do you have any suggestions? |
Beta Was this translation helpful? Give feedback.
Answered by
zzzeek
Oct 16, 2022
Replies: 1 comment 1 reply
-
yes take a look at the modern example for connection sharing which was modified some time ago to no longer use the deprecated "branch" pattern. |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
jtpavlock
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
yes take a look at the modern example for connection sharing which was modified some time ago to no longer use the deprecated "branch" pattern.