{"record":{"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":"exception","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/5551b5d35f985c99cb8f1af2b3c526b050e4c059/alembic/autogenerate/api.py#L388-L424","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Provide a real database connection: run autogenerate without the --sql flag against a reachable database.","Verify sqlalchemy.url in alembic.ini (or the URL returned by env.py) is non-empty and connects successfully.","Ensure env.py calls context.configure(connection=connection, ...) with a live connection obtained from engine.connect().","If you intentionally need offline mode, do not access autogen_context.inspector; restructure custom hooks to avoid reflection."],"exampleFix":"// before (env.py, offline)\ncontext.configure(url=MY_URL, literal_binds=True)  # no connection\n\n// after\nconnectable = engine_from_config(...)\nwith connectable.connect() as connection:\n    context.configure(connection=connection, target_metadata=target_metadata)","handlingStrategy":"validation","validationCode":"# Before calling autogenerate or accessing inspector\nfrom alembic.runtime.migration import MigrationContext\n\ndef can_autogenerate(migration_context: MigrationContext) -> bool:\n    return migration_context.bind is not None\n\nif not can_autogenerate(context):\n    raise RuntimeError('A live DB connection is required for autogenerate')","typeGuard":"def has_connection(ctx) -> bool:\n    return getattr(ctx, 'connection', None) is not None","tryCatchPattern":"try:\n    inspector = autogen_context.inspector\nexcept TypeError:\n    # no connection available; skip reflection or fail loudly\n    raise","preventionTips":["Always run autogenerate against a live database connection, never with --sql.","In env.py, obtain a real connection via engine.connect() before context.configure().","Assert the connection is not None before entering autogenerate in custom hooks."],"tags":["autogenerate","connection","offline-mode","configuration"],"backgroundTag":null,"analyzedSha":"5551b5d35f985c99cb8f1af2b3c526b050e4c059","analyzedAt":"2026-08-11T01:38:46.612Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}