Skip to content

HarnessRouter Community Edition: the self-hosted, Apache-2.0 edition of the unified interface for agent harnesses. Run Codex, Claude Code, Hermes, PI, DSH, and more through one API, with sessions, streaming, files, cancellation, and failure handling. Implements the Unified Harness Protocol (UHP), an open standard. Your keys, your infrastructure.

sql: a statement's own row limit is respected in every form Postgres takes: LIMIT ALL, FETCH FIRST and an OFFSET in ROWS (#542)

Rudy Mizrahi Celekli1afe97ffa482
diff --git a/gateway/sql_plane.py b/gateway/sql_plane.py
index a689167f..c7e8a4b2 100644
--- a/gateway/sql_plane.py
+++ b/gateway/sql_plane.py
@@ -102,8 +102,15 @@ def check_readonly(sql: str) -> str:
return raw
-# `LIMIT n`, `LIMIT n OFFSET m`, and MySQL's `LIMIT offset, count`.
-_LIMIT_TAIL = re.compile(r"\blimit\s+\d+\s*(?:(?:offset\s+\d+|,\s*\d+)\s*)?$", re.I)
+# The row-limit clauses a statement can end in: `LIMIT n`, MySQL's `LIMIT offset, count`, Postgres's
+# `LIMIT ALL` (`LIMIT { count | ALL }`), the SQL standard's `FETCH {FIRST|NEXT} [n] {ROW|ROWS} {ONLY|WITH
+# TIES}`, and an OFFSET (which may say ROWS), in any order Postgres takes them. A second LIMIT after any
+# of them is a syntax error there, so the query never ran. Read only at the very end of the statement,
+# so a subquery's own limit or a column called `all_rows` is not taken for the outer one.
+_ROW_CLAUSE = (r"(?:limit\s+(?:\d+(?:\s*,\s*\d+)?|all)|offset\s+\d+(?:\s+rows?)?"
+ r"|fetch\s+(?:first|next)\s+(?:\d+\s+)?rows?\s+(?:only|with\s+ties))")
+_LIMIT_TAIL = re.compile(rf"(?:\b{_ROW_CLAUSE}\s*)+$", re.I)
+_LIMITS = re.compile(r"\b(?:limit|fetch)\b", re.I) # an OFFSET alone limits nothing
def with_limit(sql: str, max_rows: int) -> tuple[str, bool]:
@@ -114,7 +121,8 @@ def with_limit(sql: str, max_rows: int) -> tuple[str, bool]:
in one; a query with its own smaller LIMIT keeps it.
"""
bare = _strip(sql).strip().rstrip(";").strip()
- if _LIMIT_TAIL.search(bare):
+ tail = _LIMIT_TAIL.search(bare)
+ if tail and _LIMITS.search(tail.group(0)):
return sql, False
return f"{sql}\nLIMIT {int(max_rows)}", True
diff --git a/gateway/tests/test_sql_plane.py b/gateway/tests/test_sql_plane.py
index 01625036..da5d95af 100644
--- a/gateway/tests/test_sql_plane.py
+++ b/gateway/tests/test_sql_plane.py
@@ -119,6 +119,51 @@ def test_mysqls_limit_offset_count_is_respected():
assert not added and out == sql
+def test_postgres_limit_all_is_respected():
+ """Postgres spells "no limit" `LIMIT ALL` (`LIMIT { count | ALL }`). The tail check read only a
+ digit, so it appended a second LIMIT after this one — `LIMIT ALL LIMIT 500`, two LIMIT clauses,
+ which Postgres refuses, so the query never ran. The fetch is bounded by the cursor either way
+ (_pg_query, _mysql_query), so leaving the statement alone still returns at most max_rows."""
+ for sql in ("SELECT * FROM t LIMIT ALL", "SELECT * FROM t ORDER BY x limit all",
+ "SELECT * FROM t LIMIT ALL OFFSET 20"):
+ out, added = with_limit(sql, 500)
+ assert not added and out == sql, sql
+
+
+def test_the_standards_fetch_and_an_offset_in_rows_are_the_statements_own_limit():
+ """Postgres takes the SQL standard's row limit too, `FETCH {FIRST|NEXT} [n] {ROW|ROWS} {ONLY|WITH
+ TIES}`, before or after an OFFSET, and an OFFSET may say ROWS. Each ended in a shape the tail
+ check did not read, so a second LIMIT went after it, and Postgres 16 refused every one of them
+ (`syntax error at or near "LIMIT"`, measured 2026-10-22): the query never ran."""
+ for sql in ("SELECT * FROM t ORDER BY x FETCH FIRST 4 ROWS ONLY",
+ "SELECT * FROM t ORDER BY x fetch first row only",
+ "SELECT * FROM t ORDER BY x FETCH NEXT 2 ROWS WITH TIES",
+ "SELECT * FROM t ORDER BY x OFFSET 2 ROWS FETCH FIRST 2 ROWS ONLY",
+ "SELECT * FROM t ORDER BY x FETCH FIRST 2 ROWS ONLY OFFSET 3",
+ "SELECT * FROM t ORDER BY x LIMIT 2 OFFSET 3 ROWS",
+ "SELECT * FROM t ORDER BY x OFFSET 3 LIMIT 2"):
+ out, added = with_limit(sql, 500)
+ assert not added and out == sql, sql
+
+
+def test_an_offset_alone_still_gets_the_cap():
+ """An OFFSET with no LIMIT or FETCH beside it limits nothing: the cap goes after it, which
+ Postgres takes (`OFFSET 5 ROWS LIMIT 501` answered, 2026-10-22)."""
+ for sql in ("SELECT * FROM t OFFSET 5", "SELECT * FROM t OFFSET 5 ROWS"):
+ out, added = with_limit(sql, 500)
+ assert added and out.rstrip().endswith("LIMIT 500"), sql
+ out, added = with_limit("SELECT fetch_count, rows FROM t", 500)
+ assert added and out.rstrip().endswith("LIMIT 500")
+
+
+def test_all_as_a_name_is_not_read_as_a_limit():
+ """`ALL` is only the statement's own limit directly after LIMIT at the end of it."""
+ out, added = with_limit("SELECT all_rows FROM t", 500)
+ assert added and out.rstrip().endswith("LIMIT 500")
+ out, added = with_limit("SELECT * FROM (SELECT * FROM t LIMIT ALL) s", 500)
+ assert added and out.rstrip().endswith("LIMIT 500")
+
+
def test_a_comma_inside_the_query_is_not_read_as_a_limit():
out, added = with_limit("SELECT a, b FROM (SELECT a, b FROM t LIMIT 5, 10) s", 500)
assert added and out.rstrip().endswith("LIMIT 500")