{"record":{"id":"69a3e3a8ed74187a","repo":"pola-rs/polars","slug":"query-type-statements-are-not-valid-read-queri","errorCode":null,"errorMessage":"{query_type} statements are not valid 'read' queries","messagePattern":"(.+?) statements are not valid 'read' queries","errorType":"exception","errorClass":"UnsuitableSQLError","httpStatus":null,"severity":"error","filePath":"py-polars/src/polars/io/database/_executor.py","lineNumber":559,"sourceCode":"        if cursor_execute is None:\n            cursor_execute = (\n                self._sqlalchemy_async_execute if is_async else self.cursor.execute\n            )\n        return cursor_execute, options, query\n\n    def execute(\n        self,\n        query: str | TextClause | Selectable,\n        *,\n        options: dict[str, Any] | None = None,\n        select_queries_only: bool = True,\n    ) -> Self:\n        \"\"\"Execute a query and reference the result set.\"\"\"\n        if select_queries_only and isinstance(query, str):\n            q = re.search(r\"\\w{3,}\", re.sub(r\"/\\*(.|[\\r\\n])*?\\*/\", \"\", query))\n            if (query_type := \"\" if not q else q.group(0)) in _INVALID_QUERY_TYPES:\n                msg = f\"{query_type} statements are not valid 'read' queries\"\n                raise UnsuitableSQLError(msg)\n\n        options = options or {}\n\n        if self._is_alchemy_object(self.cursor):\n            # note: the Arrow \"fetch_df_*\" methods take raw SQL, so the Oracle fast-path\n            # is only available for string queries; anything else must be compiled first\n            if (\n                isinstance(query, str)\n                and (oracle_proxy := self._oracle_arrow_proxy()) is not None\n            ):\n                # note: `self.cursor` is deliberately left as the SQLAlchemy connection,\n                # so that it remains open (and closeable) for the proxy's lifetime\n                self.driver_name = \"oracledb_proxy\"\n                self.result = oracle_proxy.execute(query, **options)\n                return self\n\n            cursor_execute, options, query = self._sqlalchemy_setup(query, options)\n        else:","sourceCodeStart":541,"sourceCodeEnd":577,"githubUrl":"https://github.com/pola-rs/polars/blob/fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e/py-polars/src/polars/io/database/_executor.py#L541-L577","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","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()"],"exampleFix":"// before\npl.read_database(\"INSERT INTO t VALUES (1) RETURNING *\", conn)\n// after\nwith conn.cursor() as cur:\n    cur.execute(\"INSERT INTO t VALUES (1)\")\nconn.commit()\ndf = pl.read_database(\"SELECT * FROM t\", conn)","handlingStrategy":"validation","validationCode":"import re\nfirst = re.search(r\"\\w{3,}\", re.sub(r\"/\\*(.|[\\r\\n])*?\\*/\", \"\", query))\nif first and first.group(0).upper() in {\"INSERT\",\"UPDATE\",\"DELETE\",\"CREATE\",\"DROP\",\"ALTER\",\"TRUNCATE\",\"MERGE\",\"GRANT\",\"REVOKE\"}:\n    raise ValueError(f\"{first.group(0)} is not a read query\")","typeGuard":null,"tryCatchPattern":"from polars.exceptions import UnsuitableSQLError\ntry:\n    df = pl.read_database(query, conn)\nexcept UnsuitableSQLError:\n    with conn.cursor() as cur:\n        cur.execute(query)\n    conn.commit()\n    df = pl.read_database(\"SELECT * FROM t\", conn)","preventionTips":["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"],"tags":["database","sql","read-only","polars"],"backgroundTag":"sql-query-failed","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"}