pola-rs/polars · error · UnsuitableSQLError
statements are not valid 'read' queries
Error message
{query_type} statements are not valid 'read' queries What it means
read_database is for reading only. Before executing, it strips SQL comments and checks the first keyword of a string query; if the statement starts with a keyword in _INVALID_QUERY_TYPES (INSERT, UPDATE, DELETE, CREATE, DROP, etc.) it raises UnsuitableSQLError to prevent accidental writes during a read.
Solutions
- Use only SELECT statements (or a WITH ... SELECT CTE) with read_database
- Execute writes separately with the raw connection: conn.execute(...) / cursor.execute(...), then commit
- If you truly must run a non-SELECT that returns rows and you accept the risk, call the executor with select_queries_only=False
- For stored procedures returning results, select from a table function or wrap as SELECT * FROM func()
Example fix
// before
pl.read_database("INSERT INTO t VALUES (1) RETURNING *", conn)
// after
with conn.cursor() as cur:
cur.execute("INSERT INTO t VALUES (1)")
conn.commit()
df = pl.read_database("SELECT * FROM t", conn) Defensive patterns
Strategy: validation
Validate before calling
import re
first = re.search(r"\w{3,}", re.sub(r"/\*(.|[\r\n])*?\*/", "", query))
if first and first.group(0).upper() in {"INSERT","UPDATE","DELETE","CREATE","DROP","ALTER","TRUNCATE","MERGE","GRANT","REVOKE"}:
raise ValueError(f"{first.group(0)} is not a read query") Try / catch
from polars.exceptions import UnsuitableSQLError
try:
df = pl.read_database(query, conn)
except UnsuitableSQLError:
with conn.cursor() as cur:
cur.execute(query)
conn.commit()
df = pl.read_database("SELECT * FROM t", conn) Prevention
- Keep read and write paths on separate functions/APIs
- Never route DML through read_database, even with RETURNING
- Sanitize user-supplied SQL before passing to read paths
When it happens
Trigger: Calling pl.read_database with a string query beginning with INSERT/UPDATE/DELETE/CREATE/DROP/ALTER and the default select_queries_only=True; queries whose leading keyword is a DML/DDL verb even if wrapped in comments-stripped form.
Common situations: Trying to 'write via read' by passing INSERT ... RETURNING; reusing one query string for both write and read paths; calling with a stored-procedure call string (CALL/EXEC) that parses as invalid type.
Understand the failure class
Background: "query failed", "%w: SQL error" — wrapped database query errors in Go libraries explained — this error's family across 3 libraries.
Related errors
- cannot infer dtype from
- cannot return a frame before executing a query
- 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
AI-assisted analysis of pola-rs/polars@fe841f959e (2026-09-18).
Data as JSON: /api/errors/69a3e3a8ed74187a.
Report an issue: GitHub.
Appendix: source
Thrown at py-polars/src/polars/io/database/_executor.py:559
if cursor_execute is None:
cursor_execute = (
self._sqlalchemy_async_execute if is_async else self.cursor.execute
)
return cursor_execute, options, query
def execute(
self,
query: str | TextClause | Selectable,
*,
options: dict[str, Any] | None = None,
select_queries_only: bool = True,
) -> Self:
"""Execute a query and reference the result set."""
if select_queries_only and isinstance(query, str):
q = re.search(r"\w{3,}", re.sub(r"/\*(.|[\r\n])*?\*/", "", query))
if (query_type := "" if not q else q.group(0)) in _INVALID_QUERY_TYPES:
msg = f"{query_type} statements are not valid 'read' queries"
raise UnsuitableSQLError(msg)
options = options or {}
if self._is_alchemy_object(self.cursor):
# note: the Arrow "fetch_df_*" methods take raw SQL, so the Oracle fast-path
# is only available for string queries; anything else must be compiled first
if (
isinstance(query, str)
and (oracle_proxy := self._oracle_arrow_proxy()) is not None
):
# note: `self.cursor` is deliberately left as the SQLAlchemy connection,
# so that it remains open (and closeable) for the proxy's lifetime
self.driver_name = "oracledb_proxy"
self.result = oracle_proxy.execute(query, **options)
return self
cursor_execute, options, query = self._sqlalchemy_setup(query, options)
else:View on GitHub (pinned to fe841f959e)