pola-rs/polars · error · RuntimeError
cannot return a frame before executing a query
Error message
cannot return a frame before executing a query
What it means
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.
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
Example fix
// before cur = DatabaseExecutor(conn).cursor cur.to_polars() // after cur = DatabaseExecutor(conn).cursor cur.execute(query) df = cur.to_polars()
Defensive patterns
Strategy: try-catch
Validate before calling
if getattr(cursor, "result", None) is None:
cursor.execute(query) Type guard
def has_result(cursor) -> bool:
return getattr(cursor, "result", None) is not None Try / catch
try:
df = cur.to_polars()
except RuntimeError as e:
if "cannot return a frame before executing" in str(e):
cur.execute(query)
df = cur.to_polars() Prevention
- 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
When it happens
Trigger: 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.
Common situations: 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.
Understand the failure class
Background: "Invalid state transition" errors: "status must be X, actually Y", "already rejected/charging/uninstalled", "cannot ... while running" — what they mean when a library rejects your call — this error's family across 31 libraries.
Related errors
- cannot infer dtype from
- Cannot set `iter_batches` for
- Cannot set `iter_batches` without also setting a non-zero…
- column appears more than once in the query/result cursor
- Currently no support for
AI-assisted analysis of pola-rs/polars@fe841f959e (2026-09-18).
Data as JSON: /api/errors/3c5a9bde6bd2ed46.
Report an issue: GitHub.
Appendix: source
Thrown at py-polars/src/polars/io/database/_executor.py:622
return self
def to_polars(
self,
*,
iter_batches: bool = False,
batch_size: int | None = None,
schema_overrides: SchemaDict | None = None,
infer_schema_length: int | None = N_INFER_DEFAULT,
) -> DataFrame | Iterator[DataFrame]:
"""
Convert the result set to a DataFrame.
Wherever possible we try to return arrow-native data directly; only
fall back to initialising with row-level data if no other option.
"""
if self.result is None:
msg = "cannot return a frame before executing a query"
raise RuntimeError(msg)
can_close = self.can_close_cursor
if defer_cursor_close := (iter_batches and can_close):
self.can_close_cursor = False
for frame_init in (
self._from_arrow, # init from arrow-native data (where support exists)
self._from_rows, # row-wise fallback (sqlalchemy, dbapi2, pyodbc, etc)
):
frame = frame_init(
batch_size=batch_size,
iter_batches=iter_batches,
schema_overrides=schema_overrides,
infer_schema_length=infer_schema_length,
)
if frame is not None:
if defer_cursor_close:View on GitHub (pinned to fe841f959e)