{"id":"105989ba4713c07e","repo":"sqlalchemy/alembic","slug":"can-t-return-inspector-as-this-autogencontext-has","errorCode":null,"errorMessage":"can't return inspector as this AutogenContext has no database connection","messagePattern":"can't return inspector as this AutogenContext has no database connection","errorType":"validation","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"alembic/autogenerate/api.py","lineNumber":406,"sourceCode":"            object_filters.append(include_object)\n        if include_name:\n            name_filters.append(include_name)\n\n        self._object_filters = object_filters\n        self._name_filters = name_filters\n\n        self.migration_context = migration_context\n        self.connection = self.migration_context.bind\n        self.dialect = self.migration_context.dialect\n\n        self.imports = set()\n        self.opts: dict[str, Any] = opts\n        self._has_batch: bool = False\n\n    @util.memoized_property\n    def inspector(self) -> Inspector:\n        if self.connection is None:\n            raise TypeError(\n                \"can't return inspector as this \"\n                \"AutogenContext has no database connection\"\n            )\n        return inspect(self.connection)\n\n    @contextlib.contextmanager\n    def _within_batch(self) -> Iterator[None]:\n        self._has_batch = True\n        yield\n        self._has_batch = False\n\n    def run_name_filters(\n        self,\n        name: str | None,\n        type_: NameFilterType,\n        parent_names: NameFilterParentNames,\n    ) -> bool:\n        \"\"\"Run the context's name filters and return True if the targets","sourceCodeStart":388,"sourceCodeEnd":424,"githubUrl":"https://github.com/sqlalchemy/alembic/blob/44fb3450330204b222ff05135e1fbbbdb28c44db/alembic/autogenerate/api.py#L388-L424","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","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."],"exampleFix":"// before\ncontext.configure(url=DATABASE_URL)  # offline, no connection\n# autogenerate invoked -> TypeError\n// after\nwith engine.connect() as conn:\n    context.configure(connection=conn, target_metadata=target_metadata)\n    with context.begin_transaction():\n        context.run_migrations()","handlingStrategy":"validation","validationCode":"from alembic.runtime.migration import MigrationContext\nmc = MigrationContext.get()\nif mc is None or getattr(mc, \"bind\", None) is None:\n    raise RuntimeError(\"Cannot autogenerate without a DB connection; configure env.py in online mode.\")","typeGuard":"def has_connection(ctx) -> bool:\n    return getattr(getattr(ctx, \"migration_context\", ctx), \"bind\", None) is not None","tryCatchPattern":null,"preventionTips":["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."],"tags":["autogenerate","connection","offline-mode","reflection"],"analyzedSha":"44fb3450330204b222ff05135e1fbbbdb28c44db","analyzedAt":"2026-08-04T19:57:10.248Z","schemaVersion":2}