Skip to content

env

Alembic Migration Environment Configuration.

This module configures Alembic's migration environment for the Tux Discord bot. It provides both offline (SQL generation) and online (database execution) migration modes with production-ready features including:

  • Automatic retry logic with exponential backoff for Docker/CI environments
  • Connection pre-testing before running migrations
  • Async-to-sync URL conversion for Alembic compatibility
  • Empty migration prevention for cleaner revision history
  • Object filtering for views and external tables
  • Comprehensive safety features and timeout configuration
Key Features
  • Database URL conversion: postgresql+psycopg_async:// → postgresql+psycopg://
  • Retry logic: 5 attempts with 2-second backoff for database startup delays
  • Connection testing: Validates connectivity with SELECT 1 before migrations
  • Smart filtering: Prevents empty migrations and handles views correctly
  • Type safety: Properly typed hooks for include_object and process_revision_directives
  • Production config: Pool management, timeouts, and transaction safety
Configuration Options

All options are set for maximum safety and compatibility: - compare_type: Detect column type changes - compare_server_default: Detect server default changes - render_as_batch: Better ALTER TABLE support - transaction_per_migration: Individual transaction rollback safety - include_schemas: Disabled to prevent schema confusion

Functions:

Classes

Functions

include_object

Python
include_object(
    obj: SchemaItem,
    name: str | None,
    type_: Literal[
        "schema",
        "table",
        "column",
        "index",
        "unique_constraint",
        "foreign_key_constraint",
    ],
    reflected: bool,
    compare_to: SchemaItem | None,
) -> bool

Filter schema objects for autogenerate operations.

This hook allows fine-grained control over which database objects are included in migration detection and generation.

Parameters:

  • obj (SchemaItem) –

    The SQLAlchemy schema object being considered.

  • name (str | None) –

    The name of the object.

  • type_ (str) –

    The type of object (table, index, column, etc.).

  • reflected (bool) –

    Whether the object was reflected from the database.

  • compare_to (SchemaItem | None) –

    The corresponding object in the metadata (None if not present).

Returns:

  • bool

    True to include the object, False to exclude it.

Examples:

  • Exclude views marked with info={'is_view': True}
  • Could exclude alembic_version table if needed
  • Could exclude temporary or external tables

process_revision_directives

Python
process_revision_directives(
    ctx: MigrationContext,
    revision: str | Iterable[str | None] | Iterable[str],
    directives: list[MigrationScript],
) -> None

Process and potentially modify migration directives before generation.

This hook prevents generation of empty migration files when using autogenerate, keeping the revision history clean and meaningful.

Parameters:

  • ctx (MigrationContext) –

    The current migration context.

  • revision (str | Iterable) –

    The revision identifier(s).

  • directives (list[MigrationScript]) –

    The migration directives to process.

Notes

When autogenerate detects no schema changes, this hook empties the directives list, preventing creation of an empty migration file.

run_migrations_offline

Python
run_migrations_offline() -> None

Run migrations in offline (SQL script generation) mode.

In this mode, Alembic generates SQL scripts without connecting to a database. Useful for generating migration SQL to review or execute manually.

The context is configured with just a database URL, and all operations are rendered as SQL statements that are emitted to the script output.

Notes
  • Converts async database URLs to sync format for compatibility
  • Generates literal SQL with bound parameters
  • No actual database connection is made

run_migrations_online

Python
run_migrations_online() -> None

Run migrations in online (database connection) mode.

This is the standard mode for executing migrations against a live database. It connects to the database, runs migrations within transactions, and includes production-ready features like retry logic and connection testing.

Features
  • URL Conversion: Automatically converts async URLs to sync for Alembic
  • Retry Logic: 5 attempts with 2-second delays for Docker/CI startup
  • Connection Testing: Validates database connectivity before migrations
  • Pool Management: Configured for production with pre-ping and recycling
  • Timeout Protection: 5-minute statement timeout prevents hung migrations
  • Transaction Safety: Each migration runs in its own transaction
Configuration Details
  • pool_pre_ping: Tests connections before use (handles stale connections)
  • pool_recycle: Recycles connections after 1 hour (prevents timeout issues)
  • connect_timeout: 10-second connection timeout
  • statement_timeout: 5-minute query timeout (300,000ms)
  • transaction_per_migration: Individual rollback capability per migration

Raises:

  • OperationalError

    If database connection fails after all retry attempts.

  • RuntimeError

    If engine creation succeeds but connection is None (should never happen).

Notes

The retry logic is critical for Docker and CI environments where the database container may still be starting up when migrations are attempted.