-
Notifications
You must be signed in to change notification settings - Fork 5
Alembic Latest Revision IDs
When we create a new database using SQLAlchemy, we use either one of the values to stamp the database with the latest version: LATEST_POSTGRES_VERSION
and LATEST_SQLITE_VERSION
. They are automatically updated when a new migration file is generated. For this update, a post-hook function is used (under migrations/env.py module):
@write_hooks.register("update_latest_revision")
def update_latest_revision(filename, options):
with open(filename) as file_:
lines = file_.readlines()
# Load json file
json_file_path = os.path.join(MIGRATIONS_DIRECTORY, "latest_revisions.json")
with open(json_file_path, "r") as json_file:
data = json.load(json_file)
for line in lines:
# If line has revision variable, i.e. revision = "bcff0ccb4fbd", remove new line
# character and quote marks, split line into two parts: ('', 'bcff0ccb4fbd'), obtain the
# second element
if line.startswith("revision = "):
split_tokens = line.replace("\n", "").replace('"', "").split("revision = ")
revision_id = split_tokens[1]
if "postgres_versions" in filename:
data["LATEST_POSTGRES_VERSION"] = revision_id
else:
data["LATEST_SQLITE_VERSION"] = revision_id
# Dump updated json
with open(json_file_path, "w") as json_file:
json.dump(data, json_file, indent=4)
It does basic text processing. It finds the line which starts with revision =
and takes the revision_id
from that line. Then, it updates the corresponding key in JSON (LATEST_POSTGRES_VERSION
if it's a migration script for Postgres, LATEST_SQLITE_VERSION
if it's a migration script for SQLite).
We created this script because we had troubles when we initialised a database using SQLAlchemy. We forgot to update the revision id. Alembic tried to upgrade the database even though the database was in the latest version (SQLAlchemy uses the model classes, and they are always updated). So, instead of manually updating the revision IDs for each migration, we used this approach.