pola-rs/polars · error · ValueError

Cannot set `iter_batches` without also setting a non-zero…

Error message

Cannot set `iter_batches` without also setting a non-zero `batch_size`

What it means

Raised by `_from_rows` (the non-Arrow fetch path of the database executor) when `iter_batches=True` is requested but `batch_size` is None or zero. Unlike the Arrow path, no driver name is cited — this is a plain precondition check: batched iteration is impossible without a batch size to chunk rows into.

Solutions

  1. Provide a non-zero `batch_size`, e.g. `pl.read_database(query, conn, iter_batches=True, batch_size=50_000)`.
  2. Remove `iter_batches=True` if a single DataFrame is acceptable.
  3. If memory limits motivated batching, size `batch_size` from estimated row width × available memory.

Example fix

// before
for df in pl.read_database(query, conn, iter_batches=True):
    process(df)
// after
for df in pl.read_database(query, conn, iter_batches=True, batch_size=50_000):
    process(df)
Defensive patterns

Strategy: validation

Validate before calling

def require_batch_size(iter_batches: bool, batch_size: int | None) -> None:
    if iter_batches and not batch_size:
        raise ValueError("iter_batches requires a non-zero batch_size")

require_batch_size(iter_batches=True, batch_size=50_000)

Type guard

def has_valid_batch_size(batch_size: int | None) -> bool:
    return isinstance(batch_size, int) and batch_size > 0

Try / catch

try:
    frames = pl.read_database(query, conn, iter_batches=True, batch_size=n)
except ValueError as e:
    if "batch_size" in str(e):
        frames = [pl.read_database(query, conn)]
    else:
        raise

Prevention

When it happens

Trigger: Calling `pl.read_database(query, connection, iter_batches=True)` (or the executor's `_from_rows` directly) on a driver that goes through the row-based fetch path (e.g. plain DB-API cursors, sqlalchemy without Arrow support) while omitting `batch_size` or passing `batch_size=0`.

Common situations: Chunked reading of large MySQL/Postgres/SQLite results with a DB-API cursor, forgetting the `batch_size` kwarg; copy-pasting `iter_batches=True` from an Arrow example; passing 0 as 'unlimited' by mistake.

Understand the failure class

Background: Conflicting config options: "cannot be used together" — configuration validation errors across open-source libraries — this error's family across 162 libraries.

Related errors


AI-assisted analysis of pola-rs/polars@fe841f959e (2026-09-18). Data as JSON: /api/errors/93979b60326f7721. Report an issue: GitHub.

Appendix: source

Thrown at py-polars/src/polars/io/database/_executor.py:293

        return None

    def _from_rows(
        self,
        *,
        batch_size: int | None,
        iter_batches: bool,
        schema_overrides: SchemaDict | None,
        infer_schema_length: int | None,
    ) -> DataFrame | Iterator[DataFrame] | None:
        """Return resultset data row-wise for frame init."""
        from polars import DataFrame

        if iter_batches and not batch_size:
            msg = (
                "Cannot set `iter_batches` without also setting a non-zero `batch_size`"
            )
            raise ValueError(msg)

        if is_async := isinstance(original_result := self.result, Coroutine):
            self.result = _run_async(self.result)
        try:
            if hasattr(self.result, "fetchall"):
                if is_alchemy := (self.driver_name == "sqlalchemy"):
                    if hasattr(self.result, "cursor"):
                        cursor_desc = [
                            (d[0], d[1:]) for d in self.result.cursor.description
                        ]
                    elif hasattr(self.result, "_metadata"):
                        cursor_desc = [(k, None) for k in self.result._metadata.keys]
                    else:
                        msg = f"Unable to determine metadata from query result; {self.result!r}"
                        raise ValueError(msg)

                elif hasattr(self.result, "description"):
                    cursor_desc = [(d[0], d[1:]) for d in self.result.description]

View on GitHub (pinned to fe841f959e)