Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Acquire exclusive lock during db migration #50

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 13 additions & 9 deletions alembic/env.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from logging.config import fileConfig

import alembic_postgresql_enum # noqa: F401
from sqlalchemy import pool
from sqlalchemy import pool, text
from sqlalchemy.engine import Connection
from sqlalchemy.ext.asyncio import async_engine_from_config

Expand All @@ -16,6 +16,15 @@

L = logging.getLogger("alembic.env")

# server settings to reduce possible service disruptions while running the migration
SERVER_SETTINGS = {
# Abort any statement that takes more than the specified amount of time
"statement_timeout": "6000",
# Abort any statement that waits longer than the specified amount of time while
# attempting to acquire a lock on a table, index, row, or other database object
"lock_timeout": "4000",
}

# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
Expand Down Expand Up @@ -87,25 +96,20 @@ def do_run_migrations(connection: Connection) -> None:
)

with context.begin_transaction():
# obtain an exclusive transaction-level advisory lock, waiting if necessary
connection.execute(text("SELECT pg_advisory_xact_lock(12345)"))
context.run_migrations()


async def run_async_migrations() -> None:
"""In this scenario we need to create an Engine
and associate a connection with the context.
"""
server_settings = {
# Abort any statement that takes more than the specified amount of time
"statement_timeout": "6000",
# Abort any statement that waits longer than the specified amount of time while
# attempting to acquire a lock on a table, index, row, or other database object
"lock_timeout": "4000",
}
connectable = async_engine_from_config(
config.get_section(config.config_ini_section, {}),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
connect_args={"server_settings": server_settings},
connect_args={"server_settings": SERVER_SETTINGS},
)

async with connectable.connect() as connection:
Expand Down