Add migration support with Alembic; implement migration scripts and configuration

This commit is contained in:
Mabe
2026-09-23 20:47:58 -07:00
parent c3ce9b88a2
commit 12485792d2
8 changed files with 357 additions and 1 deletions
+1
View File
@@ -0,0 +1 @@
Generic single-database configuration.
+67
View File
@@ -0,0 +1,67 @@
import os
from alembic.config import Config
from alembic.script import ScriptDirectory
from alembic.runtime.migration import MigrationContext
from alembic import command
from sqlalchemy import create_engine
from alembic import command
from dotenv import load_dotenv
import logging
#Logging
logging.basicConfig(
filename='app.log', # Log to a file
level=logging.DEBUG, # Log everything (DEBUG and above)
format='%(asctime)s %(levelname)s %(message)s'
)
logging.info('Application started')
try:
logging.debug('Debug info here')
except Exception as e:
logging.exception('An error occurred')
load_dotenv()
db_name = os.getenv("DB_NAME")
db_psswd = os.getenv("DB_PASSWORD")
db_user = os.getenv("DB_USER")
db_port = os.getenv("DB_PORT") or "3306"
db_host = os.getenv("DB_HOST")
if db_host == None:
os._exit(1)
engine_url = f"mariadb+mariadbconnector://{db_user}:{db_psswd}@{db_host}:{db_port}/{db_name}"
base_dir = os.path.dirname(__file__)
ini_path = os.path.join(base_dir, "..", "alembic.ini")
alembic_cfg = Config(ini_path)
alembic_cfg.set_section_option(alembic_cfg.config_ini_section, "sqlalchemy.url", engine_url)
script = ScriptDirectory.from_config(alembic_cfg)
engine = create_engine(engine_url)
def check_db():
with engine.connect() as conn:
context = MigrationContext.configure(conn)
current_rev = context.get_current_revision()
head_rev = script.get_current_head()
if current_rev != head_rev:
command.upgrade(alembic_cfg, "head")
return False
def auto_lookup():
command.revision(alembic_cfg, message="add tables and rows", autogenerate=True)
script = ScriptDirectory.from_config(alembic_cfg)
head_rev = script.get_revision(script.get_current_head())
with open(head_rev.path) as f:
content = f.read()
if "pass\n # ### end Alembic commands ###" in content:
os.remove(head_rev.path)
command.stamp(alembic_cfg, "head")
logging.info("No changes DB detected")
else:
command.upgrade(alembic_cfg, "head")
logging.info("New DB changes, upgrade table")
auto_lookup()
+84
View File
@@ -0,0 +1,84 @@
from logging.config import fileConfig
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from alembic import context
from models import Base
metadata = Base.metadata
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Interpret the config file for Python logging.
# This line sets up loggers basically.
if config.config_file_name is not None:
fileConfig(config.config_file_name)
# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
target_metadata = metadata
# 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 run_migrations_offline() -> None:
"""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=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online() -> None:
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
connectable = engine_from_config(
config.get_section(config.config_ini_section, {}),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
with connectable.connect() as connection:
context.configure(
connection=connection, target_metadata=target_metadata
)
with context.begin_transaction():
context.run_migrations()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
if config.config_file_name is not None:
fileConfig(config.config_file_name)
+28
View File
@@ -0,0 +1,28 @@
"""${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}
# revision identifiers, used by Alembic.
revision: str = ${repr(up_revision)}
down_revision: Union[str, Sequence[str], None] = ${repr(down_revision)}
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
def upgrade() -> None:
"""Upgrade schema."""
${upgrades if upgrades else "pass"}
def downgrade() -> None:
"""Downgrade schema."""
${downgrades if downgrades else "pass"}