{"record":{"id":"3c5a9bde6bd2ed46","repo":"pola-rs/polars","slug":"cannot-return-a-frame-before-executing-a-query","errorCode":null,"errorMessage":"cannot return a frame before executing a query","messagePattern":"cannot return a frame before executing a query","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"error","filePath":"py-polars/src/polars/io/database/_executor.py","lineNumber":622,"sourceCode":"        return self\n\n    def to_polars(\n        self,\n        *,\n        iter_batches: bool = False,\n        batch_size: int | None = None,\n        schema_overrides: SchemaDict | None = None,\n        infer_schema_length: int | None = N_INFER_DEFAULT,\n    ) -> DataFrame | Iterator[DataFrame]:\n        \"\"\"\n        Convert the result set to a DataFrame.\n\n        Wherever possible we try to return arrow-native data directly; only\n        fall back to initialising with row-level data if no other option.\n        \"\"\"\n        if self.result is None:\n            msg = \"cannot return a frame before executing a query\"\n            raise RuntimeError(msg)\n\n        can_close = self.can_close_cursor\n\n        if defer_cursor_close := (iter_batches and can_close):\n            self.can_close_cursor = False\n\n        for frame_init in (\n            self._from_arrow,  # init from arrow-native data (where support exists)\n            self._from_rows,  # row-wise fallback (sqlalchemy, dbapi2, pyodbc, etc)\n        ):\n            frame = frame_init(\n                batch_size=batch_size,\n                iter_batches=iter_batches,\n                schema_overrides=schema_overrides,\n                infer_schema_length=infer_schema_length,\n            )\n            if frame is not None:\n                if defer_cursor_close:","sourceCodeStart":604,"sourceCodeEnd":640,"githubUrl":"https://github.com/pola-rs/polars/blob/fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e/py-polars/src/polars/io/database/_executor.py#L604-L640","documentation":"Cursor.to_polars() can only materialize a frame from results of an already-executed query. If self.result is None — i.e. execute() was never called (or the cursor was reinitialised) — it raises RuntimeError telling you to execute the query first.","triggerScenarios":"Calling to_polars() (or iter_batches) directly on the internal Cursor/DatabaseExecutor without first calling execute(query); constructing a cursor manually and forgetting the execute step; calling to_polars twice after the result was consumed/reset.","commonSituations":"Using polars' internal database Cursor API directly in custom ingestion code; reordering a refactor so the execute call was dropped; conditionally skipping execute when a cached query 'should' have run.","solutions":["Call executor/cursor.execute(query) before to_polars()","Prefer the high-level pl.read_database / pl.read_database_uri API, which manages execute internally","Check that your code path always executes (guard against early returns before execute)","If reusing a cursor, re-execute the query rather than relying on a previous result"],"exampleFix":"// before\ncur = DatabaseExecutor(conn).cursor\ncur.to_polars()\n// after\ncur = DatabaseExecutor(conn).cursor\ncur.execute(query)\ndf = cur.to_polars()","handlingStrategy":"try-catch","validationCode":"if getattr(cursor, \"result\", None) is None:\n    cursor.execute(query)","typeGuard":"def has_result(cursor) -> bool:\n    return getattr(cursor, \"result\", None) is not None","tryCatchPattern":"try:\n    df = cur.to_polars()\nexcept RuntimeError as e:\n    if \"cannot return a frame before executing\" in str(e):\n        cur.execute(query)\n        df = cur.to_polars()","preventionTips":["Always pair execute() with to_polars()/iter_batches on the same cursor object","Prefer pl.read_database which manages execution order for you","Avoid reusing cursors across request boundaries"],"tags":["database","lifecycle","runtime-error","polars"],"backgroundTag":"invalid-state-transition","analyzedSha":"fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e","analyzedAt":"2026-09-18T22:14:11.667Z","contentChangedAt":"2026-09-18T22:14:11.667Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}