From: m-aciek Date: Mon, 13 May 2019 21:12:10 +0000 (+0200) Subject: Add database freshness check cookbook recipe X-Git-Tag: rel_1_0_11~15 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=b96cae78855c1207cd976df0ac9f9fc17c08c9d7;p=thirdparty%2Fsqlalchemy%2Falembic.git Add database freshness check cookbook recipe Change-Id: Iefeaadefafa286dbdb50d3034549284ee31f6623 Fixes: #559 Closes: #560 Co-authored-by: Mike Bayer (cherry picked from commit 81a595598f352b4f93cdf849df7d96ab3b1fc8af) --- diff --git a/docs/build/cookbook.rst b/docs/build/cookbook.rst index 4ace79e8..ebaee5ef 100644 --- a/docs/build/cookbook.rst +++ b/docs/build/cookbook.rst @@ -1047,3 +1047,35 @@ Output:: op.create_index('property_name_users_id', 'user_properties', ['property_name', 'users_id'], unique=True) # ### end Alembic commands ### +Test current database revision is at head(s) +============================================ + +A recipe to determine if a database schema is up to date in terms of applying +Alembic migrations. May be useful for test or installation suites to +determine if the target database is up to date. Makes use of the +:meth:`.MigrationContext.get_current_heads` as well as +:meth:`.ScriptDirectory.get_heads` methods so that it accommodates for a +branched revision tree:: + + + from alembic import config, script + from alembic.runtime import migration + from sqlalchemy import engine + + + def check_current_head(alembic_cfg, connectable): + # type: (config.Config, engine.Engine) -> bool + directory = script.ScriptDirectory.from_config(alembic_cfg) + with connectable.begin() as connection: + context = migration.MigrationContext.configure(connection) + return set(context.get_current_heads()) == set(directory.get_heads()) + + e = engine.create_engine("mysql://scott:tiger@localhost/test", echo=True) + cfg = config.Config("alembic.ini") + print(check_current_head(cfg, e)) + +.. seealso:: + + :meth:`.MigrationContext.get_current_heads` + + :meth:`.ScriptDirectory.get_heads`