sqlalchemy/alembic · error · TypeError
can't return inspector as this AutogenContext has no databas
Error message
can't return inspector as this AutogenContext has no database connection
What it means
The AutogenContext.inspector property raises this when the migration context has no live database connection. Autogenerate needs to reflect the database schema, which requires an open Connection; in offline ('sql') mode, or when configure() was called against a MigrationContext with no bind, reflection is impossible and the property refuses to return a bogus inspector.
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 targetsView on GitHub (pinned to 44fb345033)
Solutions
- Switch env.py to online mode: use engine.connect() (or run_migrations_async with an async engine) and pass the connection to context.configure(connection=conn).
- If offline SQL generation is genuinely intended, do not invoke autogenerate (which needs reflection); generate an empty revision and hand-write the SQL.
- Ensure context.configure() receives a non-None connection before any call that reads autogen_context.inspector.
Example fix
// before
context.configure(url=DATABASE_URL) # offline, no connection
# autogenerate invoked -> TypeError
// after
with engine.connect() as conn:
context.configure(connection=conn, target_metadata=target_metadata)
with context.begin_transaction():
context.run_migrations() Defensive patterns
Strategy: validation
Validate before calling
from alembic.runtime.migration import MigrationContext
mc = MigrationContext.get()
if mc is None or getattr(mc, "bind", None) is None:
raise RuntimeError("Cannot autogenerate without a DB connection; configure env.py in online mode.") Type guard
def has_connection(ctx) -> bool:
return getattr(getattr(ctx, "migration_context", ctx), "bind", None) is not None Prevention
- In env.py, branch on context.is_offline_mode() and skip autogenerate in offline mode.
- Always call context.configure(connection=conn) with a live connection before run_migrations in online mode.
- Add an integration test that runs 'alembic revision --autogenerate' against a throwaway DB.
When it happens
Trigger: Calling command.autogenerate (alembic revision --autogenerate), or any code path that touches autogen_context.inspector, while the MigrationContext.bind is None. This occurs when env.py is configured for offline (as_sql=True) generation but an autogenerate comparison is still attempted, or when run_migrations is invoked without setting up a connection via online mode.
Common situations: A partially-written env.py that mixes offline and online configuration; running 'alembic revision --autogenerate' against an env.py that was set up for 'alembic upgrade sql' generation; a custom command that constructs MigrationContext.configure() without passing a connection.
Related errors
- Cannot call run_async in SQL mode
- Duplicate table keys across multiple MetaData objects: %s
- Autogenerate rendering of SQL Expression language constructs
- Can only return single object for UpgradeOps traverse
- Can only return single object for DowngradeOps traverse
AI-assisted analysis of sqlalchemy/alembic@44fb345033 (2026-08-04).
Data as JSON: /data/errors/105989ba4713c07e.json.
Report an issue: GitHub.