sqlalchemy/alembic · error · TypeError

can't return inspector as this AutogenContext has no…

Error message

can't return inspector as this AutogenContext has no database connection

What it means

The AutogenContext.inspector property raises TypeError when the migration context has no live database connection (self.connection is None). Alembic needs an Inspector to reflect the live database schema during autogenerate comparison, which is impossible without a connection. This most commonly occurs when autogenerate is run in offline/SQL-generation mode (--sql) or when the URL/bind resolves to None.

Solutions

  1. Provide a real database connection: run autogenerate without the --sql flag against a reachable database.
  2. Verify sqlalchemy.url in alembic.ini (or the URL returned by env.py) is non-empty and connects successfully.
  3. Ensure env.py calls context.configure(connection=connection, ...) with a live connection obtained from engine.connect().
  4. If you intentionally need offline mode, do not access autogen_context.inspector; restructure custom hooks to avoid reflection.

Example fix

// before (env.py, offline)
context.configure(url=MY_URL, literal_binds=True)  # no connection

// after
connectable = engine_from_config(...)
with connectable.connect() as connection:
    context.configure(connection=connection, target_metadata=target_metadata)
Defensive patterns

Strategy: validation

Validate before calling

# Before calling autogenerate or accessing inspector
from alembic.runtime.migration import MigrationContext

def can_autogenerate(migration_context: MigrationContext) -> bool:
    return migration_context.bind is not None

if not can_autogenerate(context):
    raise RuntimeError('A live DB connection is required for autogenerate')

Type guard

def has_connection(ctx) -> bool:
    return getattr(ctx, 'connection', None) is not None

Try / catch

try:
    inspector = autogen_context.inspector
except TypeError:
    # no connection available; skip reflection or fail loudly
    raise

Prevention

When it happens

Trigger: Calling `alembic revision --autogenerate` while the environment is configured for offline SQL output, or invoking compare_metadata/AutogenContext against a MigrationContext whose bind is None. Also triggered by custom autogenerate code that accesses autogen_context.inspector after initializing MigrationContext with no engine.

Common situations: Running autogenerate with `--sql` flag set; misconfigured alembic.ini with an empty sqlalchemy.url; using a script that constructs MigrationContext.configure() without passing a connection; CI pipelines that run alembic offline.

Related errors


AI-assisted analysis of sqlalchemy/alembic@5551b5d35f (2026-08-11). Data as JSON: /api/errors/105989ba4713c07e. Report an issue: GitHub.

Appendix: source

Thrown at alembic/autogenerate/api.py:406

            object_filters.append(include_object)
        if include_name:
            name_filters.append(include_name)

        self._object_filters = object_filters
        self._name_filters = name_filters

        self.migration_context = migration_context
        self.connection = self.migration_context.bind
        self.dialect = self.migration_context.dialect

        self.imports = set()
        self.opts: dict[str, Any] = opts
        self._has_batch: bool = False

    @util.memoized_property
    def inspector(self) -> Inspector:
        if self.connection is None:
            raise TypeError(
                "can't return inspector as this "
                "AutogenContext has no database connection"
            )
        return inspect(self.connection)

    @contextlib.contextmanager
    def _within_batch(self) -> Iterator[None]:
        self._has_batch = True
        yield
        self._has_batch = False

    def run_name_filters(
        self,
        name: str | None,
        type_: NameFilterType,
        parent_names: NameFilterParentNames,
    ) -> bool:
        """Run the context's name filters and return True if the targets

View on GitHub (pinned to 5551b5d35f)