aboutsummaryrefslogtreecommitdiff
path: root/webmentions_ssg/migrations/env.py
diff options
context:
space:
mode:
authorDennis Fink2026-10-27 23:16:27 +0100
committerDennis Fink2026-10-27 23:18:45 +0100
commit17ab56a3c7d3dbb3d66edf380ab637a61cefe50c (patch)
tree1626e3e1d402a6614a1cec4c2c6719d301f39bac /webmentions_ssg/migrations/env.py
parent5afb245d13b91047d68d7b7343245c41b6460953 (diff)
downloadwebmentions-ssg-17ab56a3c7d3dbb3d66edf380ab637a61cefe50c.tar.gz
webmentions-ssg-17ab56a3c7d3dbb3d66edf380ab637a61cefe50c.zip
feat(core): add database CLI
Make database initialization and upgrades explicit so new installations cannot silently modify an existing or unversioned schema. Keep Flask-Migrate commands available separately and package the migration environment with the application for reliable deployment.
Diffstat (limited to 'webmentions_ssg/migrations/env.py')
-rw-r--r--webmentions_ssg/migrations/env.py105
1 files changed, 105 insertions, 0 deletions
diff --git a/webmentions_ssg/migrations/env.py b/webmentions_ssg/migrations/env.py
new file mode 100644
index 0000000..e2e0ec9
--- /dev/null
+++ b/webmentions_ssg/migrations/env.py
@@ -0,0 +1,105 @@
+# SPDX-FileCopyrightText: 2026 Dennis Fink <me+coding@dennisfink.me>
+#
+# SPDX-License-Identifier: BSD-3-Clause
+
+import logging
+
+from alembic import context
+from flask import current_app
+
+# this is the Alembic Config object, which provides
+# access to the values within the .ini file in use.
+config = context.config
+
+# Flask already configures application logging.
+# Do not let Alembic replace existing logging handlers,
+# including pytest's log capture handler.
+logger = logging.getLogger("alembic.env")
+
+
+def get_engine():
+ return current_app.extensions["migrate"].db.engine
+
+
+def get_engine_url():
+ try:
+ return get_engine().url.render_as_string(hide_password=False).replace("%", "%%")
+ except AttributeError:
+ return str(get_engine().url).replace("%", "%%")
+
+
+# add your model's MetaData object here
+# for 'autogenerate' support
+# from myapp import mymodel
+# target_metadata = mymodel.Base.metadata
+config.set_main_option("sqlalchemy.url", get_engine_url())
+target_db = current_app.extensions["migrate"].db
+
+# other values from the config, defined by the needs of env.py,
+# can be acquired:
+# my_important_option = config.get_main_option("my_important_option")
+# ... etc.
+
+
+def get_metadata():
+ if hasattr(target_db, "metadatas"):
+ return target_db.metadatas[None]
+ return target_db.metadata
+
+
+def run_migrations_offline():
+ """Run migrations in 'offline' mode.
+
+ This configures the context with just a URL
+ and not an Engine, though an Engine is acceptable
+ here as well. By skipping the Engine creation
+ we don't even need a DBAPI to be available.
+
+ Calls to context.execute() here emit the given string to the
+ script output.
+
+ """
+ url = config.get_main_option("sqlalchemy.url")
+ context.configure(url=url, target_metadata=get_metadata(), literal_binds=True)
+
+ with context.begin_transaction():
+ context.run_migrations()
+
+
+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.
+
+ """
+
+ # this callback is used to prevent an auto-migration from being generated
+ # when there are no changes to the schema
+ # reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html
+ def process_revision_directives(context, revision, directives):
+ if getattr(config.cmd_opts, "autogenerate", False):
+ script = directives[0]
+ if script.upgrade_ops.is_empty():
+ directives[:] = []
+ logger.info("No changes in schema detected.")
+
+ conf_args = current_app.extensions["migrate"].configure_args
+ if conf_args.get("process_revision_directives") is None:
+ conf_args["process_revision_directives"] = process_revision_directives
+
+ connectable = get_engine()
+
+ with connectable.connect() as connection:
+ context.configure(
+ connection=connection, target_metadata=get_metadata(), **conf_args
+ )
+
+ with context.begin_transaction():
+ context.run_migrations()
+
+
+if context.is_offline_mode():
+ run_migrations_offline()
+else:
+ run_migrations_online()