Skip to content

fix(postgres): coerce LIMIT before SQL interpolation - #2625

Closed
Bartok9 wants to merge 2 commits into
Canner:mainfrom
Bartok9:fix/postgres-coerce-limit
Closed

fix(postgres): coerce LIMIT before SQL interpolation#2625
Bartok9 wants to merge 2 commits into
Canner:mainfrom
Bartok9:fix/postgres-coerce-limit

Conversation

@Bartok9

@Bartok9 Bartok9 commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

Summary

Coerce limit to a non-negative int before interpolating into Postgres SQL (same contract as MySQL).

What failure does this repair?

PostgresConnector.query built the clause as a raw f-string LIMIT {limit}, so a non-numeric or negative limit flowed straight into the SQL text. Example before this fix:

connector.query("SELECT * FROM t", limit="1; DROP TABLE users")
# -> ... LIMIT 1; DROP TABLE users   (injection / malformed SQL)
connector.query("SELECT * FROM t", limit=-5)
# -> ... LIMIT -5                    (invalid Postgres LIMIT -> ProgrammingError)

_coerce_limit now rejects negatives and non-numeric strings before interpolation, while still accepting numeric strings like "3".

Motivation

Raw LIMIT {limit} accepted injection-style strings and negatives.

Verification

cd core/wren && .venv/bin/python -m pytest tests/unit/test_postgres_coerce_limit.py -q
3 passed

Duplicate check

Related open connector-limit PRs (parallel work across connectors, no overlap):

Summary by CodeRabbit

  • Bug Fixes
    • Improved PostgreSQL query limit handling by validating and converting limit values before SQL generation.
    • Negative and injection-like (non-numeric) limit inputs are now rejected with an error.
    • Numeric limit values provided as strings continue to be supported.
  • Tests
    • Added unit test coverage for valid numeric limits, negative limits, and injection-like inputs.

Reject negative and non-numeric limits so client values cannot break QUERY composition.
@github-actions github-actions Bot added python Pull requests that update Python code core labels Jul 30, 2026
@coderabbitai

coderabbitai Bot commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

The Postgres connector now coerces and validates query limits before SQL interpolation. Unit tests cover negative values, injection-like strings, and numeric string limits.

Changes

Postgres limit validation

Layer / File(s) Summary
Limit coercion integration
core/wren/src/wren/connector/postgres.py
Adds _coerce_limit and applies it in PostgresConnector.query before constructing the LIMIT clause.
Limit validation tests
core/wren/tests/unit/test_postgres_coerce_limit.py
Stubs the optional psycopg import and tests invalid limits plus SQL generation for numeric string limits.

Estimated code review effort: 2 (Simple) | ~10 minutes

Possibly related PRs

  • Canner/WrenAI#2407: Modifies the same Postgres query wrapping and LIMIT flow.
  • Canner/WrenAI#2490: Updates PostgresConnector.query and related tests around SQL preprocessing.
  • Canner/WrenAI#2626: Implements the same limit coercion pattern with connector query updates and tests.

Suggested reviewers: goldmedal

Poem

I’m a rabbit guarding the query gate,
Turning stringy limits into numbers straight.
No negative hops, no SQL surprise,
Safe LIMIT 3 makes my ears rise.
Test paws confirm the path is bright!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly summarizes the main change: coercing PostgreSQL LIMIT before SQL interpolation.
Description check ✅ Passed The description covers the summary, failure mode, testing, and duplicate check, with only the test section using a different heading.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@core/wren/src/wren/connector/postgres.py`:
- Around line 223-234: Update _coerce_limit so negative numeric inputs are
rejected before int() truncates them; alternatively reject non-integral limits
explicitly while preserving safe coercion for valid values. Add a regression
test verifying limit=-0.5 raises ValueError rather than producing LIMIT 0.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 4584742b-8b84-4390-9068-756c84dfca65

📥 Commits

Reviewing files that changed from the base of the PR and between 32d76bf and bf2afaa.

📒 Files selected for processing (2)
  • core/wren/src/wren/connector/postgres.py
  • core/wren/tests/unit/test_postgres_coerce_limit.py

Comment on lines +223 to +234
def _coerce_limit(limit: int | None) -> int | None:
"""Validate and coerce a user-supplied ``limit`` to a non-negative ``int``.

``int(limit)`` rejects strings like ``"5 OR 1=1"`` so the value can be
safely interpolated into SQL. Negative limits are also rejected.
"""
if limit is None:
return None
coerced = int(limit)
if coerced < 0:
raise ValueError(f"limit must be non-negative, got {coerced}")
return coerced

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Validate negativity before integer truncation.

int(-0.5) produces 0, so the current check allows a negative runtime value and emits LIMIT 0. Check the original numeric value before coercion, or reject non-integral limits explicitly; add a regression test for limit=-0.5.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@core/wren/src/wren/connector/postgres.py` around lines 223 - 234, Update
_coerce_limit so negative numeric inputs are rejected before int() truncates
them; alternatively reject non-integral limits explicitly while preserving safe
coercion for valid values. Add a regression test verifying limit=-0.5 raises
ValueError rather than producing LIMIT 0.

Unit CI lacks the postgres extra; match semicolon unlimited stub pattern.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@core/wren/tests/unit/test_postgres_coerce_limit.py`:
- Around line 17-24: Update _ensure_psycopg_stub() to expose the created errors
module as the psycopg module’s errors attribute and define a QueryCanceled
exception on it, matching the symbol caught by the PostgreSQL connector’s query
error handler.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 513c1419-04ce-4cf4-bc1e-8eca6d8c84e5

📥 Commits

Reviewing files that changed from the base of the PR and between bf2afaa and f0eb3c9.

📒 Files selected for processing (1)
  • core/wren/tests/unit/test_postgres_coerce_limit.py

Comment on lines +17 to +24
def _ensure_psycopg_stub() -> None:
if "psycopg" in sys.modules:
return
mod = types.ModuleType("psycopg")
errors = types.ModuleType("psycopg.errors")
sys.modules["psycopg"] = mod
sys.modules["psycopg.errors"] = errors

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== files =="
git ls-files | rg 'test_postgres_coerce_limit|postgres\.py$|settings|pytest|requirements|pyproject' || true

echo "== target test =="
if [ -f core/wren/tests/unit/test_postgres_coerce_limit.py ]; then
  wc -l core/wren/tests/unit/test_postgres_coerce_limit.py
  sed -n '1,90p' core/wren/tests/unit/test_postgres_coerce_limit.py | nl -ba
fi

echo "== postgres connector references =="
if [ -f core/wren/src/wren/connector/postgres.py ]; then
  wc -l core/wren/src/wren/connector/postgres.py
  rg -n "psycopg|QueryCanceled|coerce|limit" core/wren/src/wren/connector/postgres.py || true
  echo "--- relevant context ---"
  rg -n -C 4 "psycopg|QueryCanceled|execute|limit" core/wren/src/wren/connector/postgres.py || true
fi

echo "== imports/usages of coerce_limit tests or module =="
rg -n "test_postgres_coerce_limit|psycopg\.errors|QueryCanceled|_ensure_psycopg_stub|stub_psycopg" . || true

echo "== python semantic probe =="
python3 - <<'PY'
import types, sys

mod = types.ModuleType("psycopg")
errors = types.ModuleType("psycopg.errors")
sys.modules["psycopg"] = mod
sys.modules["psycopg.errors"] = errors

try:
    errors.QueryCanceled
except AttributeError as e:
    print("empty stub missing errors.QueryCanceled:", e)

try:
    mod.QueryCanceled
except AttributeError as e:
    pass

errors.QueryCanceled = Exception
mod.errors = errors

from psycopg.errors import QueryCanceled
print("fixed stub has errors.QueryCanceled:", QueryCanceled)
PY

Repository: Canner/WrenAI

Length of output: 602


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== target test =="
cat -n core/wren/tests/unit/test_postgres_coerce_limit.py

echo "== postgres connector relevant symbols/context =="
wc -l core/wren/src/wren/connector/postgres.py
rg -n -C 5 "psycopg|QueryCanceled|execute|limit|get_limit|coerce" core/wren/src/wren/connector/postgres.py || true

echo "== imports/usages =="
rg -n "test_postgres_coerce_limit|psycopg\.errors|QueryCanceled|_ensure_psycopg_stub|stub_psycopg" core/wren/tests/unit/test_postgres_coerce_limit.py core/wren/tests/connectors/test_postgres.py core/wren/src/wren/connector/postgres.py || true

echo "== python semantic probe =="
python3 - <<'PY'
import types, sys

mod = types.ModuleType("psycopg")
errors = types.ModuleType("psycopg.errors")
sys.modules["psycopg"] = mod
sys.modules["psycopg.errors"] = errors

try:
    errors.QueryCanceled
except AttributeError as e:
    print("current_stub_missing_errors_QueryCanceled")
    print(repr(e))

try:
    mod.errors
except AttributeError:
    print("current_stub_missing_mod_errors")

errors.QueryCanceled = Exception
mod.errors = errors

from psycopg.errors import QueryCanceled
print("fixed_import_has_errors_QueryCanceled")
print(QueryCanceled)
PY

Repository: Canner/WrenAI

Length of output: 9269


Complete the psycopg stub’s error surface.

core/wren/src/wren/connector/postgres.py catches psycopg.errors.QueryCanceled, but _ensure_psycopg_stub() only registers psycopg.errors without exposing it on psycopg or providing QueryCanceled. Connector errors raised during query() can trigger AttributeError while evaluating the handler.

Proposed fix
     mod = types.ModuleType("psycopg")
     errors = types.ModuleType("psycopg.errors")
+    errors.QueryCanceled = type("QueryCanceled", (Exception,), {})
+    mod.errors = errors
     sys.modules["psycopg"] = mod
     sys.modules["psycopg.errors"] = errors
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def _ensure_psycopg_stub() -> None:
if "psycopg" in sys.modules:
return
mod = types.ModuleType("psycopg")
errors = types.ModuleType("psycopg.errors")
sys.modules["psycopg"] = mod
sys.modules["psycopg.errors"] = errors
def _ensure_psycopg_stub() -> None:
if "psycopg" in sys.modules:
return
mod = types.ModuleType("psycopg")
errors = types.ModuleType("psycopg.errors")
errors.QueryCanceled = type("QueryCanceled", (Exception,), {})
mod.errors = errors
sys.modules["psycopg"] = mod
sys.modules["psycopg.errors"] = errors
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@core/wren/tests/unit/test_postgres_coerce_limit.py` around lines 17 - 24,
Update _ensure_psycopg_stub() to expose the created errors module as the psycopg
module’s errors attribute and define a QueryCanceled exception on it, matching
the symbol caught by the PostgreSQL connector’s query error handler.

@goldmedal

Copy link
Copy Markdown
Collaborator

Closing in favour of a single consolidated change — thanks for the work, the underlying tidy-up is worth doing, just not as one PR per connector.

Why this is being closed rather than reviewed:

  1. This is one mechanical change spread across eight PRs. The contribution bar added in docs: set an explicit contribution bar for agent-authored PRs #2602 asks for exactly this to be a single diff: "A mechanical change repeated across several files or connectors belongs in one PR, not one PR per file. Reviewers need to see the resulting convention in a single diff."

  2. A shared helper already exists in this same batch, and none of these PRs use it. refactor(connector): centralize LIMIT coercion #2624 adds coerce_limit() to connector/base.py. Every other PR in the series re-declares a private _coerce_limit in its own module instead of importing it. Merged as-is the repo would carry nine copies of the same function (the eight here plus the existing one at connector/mysql.py:44).

  3. The copies have already diverged before merge. base.py (refactor(connector): centralize LIMIT coercion #2624), postgres, trino, oracle, redshift and bigquery use int(limit) then a negativity check; fix(clickhouse): coerce LIMIT before SQL interpolation #2627 (clickhouse) additionally rejects fractional negatives such as -0.5 via numbers.Number; fix(duckdb): coerce LIMIT before SQL interpolation #2637 (duckdb) additionally rejects bool and non-integral float. Three different semantics for one contract is the specific outcome a shared helper prevents.

  4. Coverage is inconsistent. connector/canner.py:255 interpolates a bare {limit} and is not covered by any PR in the series, while bigquery, duckdb and redshift already interpolate {int(limit)} today — for those three the only behavioural delta is the negativity check.

On the fix: label and the stated failure. The reproduction in the description calls connector.query(sql, limit="1; DROP TABLE users") directly. Tracing the call paths:

  • run_sql in mcp_server.py declares limit: int | None, so a non-numeric string is rejected by tool-argument validation, and mcp_server.py:84 already rejects negatives and clamps to MAX_ROW_LIMIT.
  • The CLI declares --limit/-l as Optional[int], so a non-integer is rejected at parse time.
  • That leaves Engine.query(sql, limit) as a Python API. At that boundary the caller already supplies sql verbatim — anyone able to pass limit="1; DROP TABLE t" can pass that as sql instead. limit is not a lower-trust channel than sql there, so this is not an injection path.

What remains is genuine but smaller: a negative limit currently surfaces as a driver-level error instead of a clear ValueError, and the coercion contract is inconsistent across connectors. That is refactor:, per "fix: requires a reproducible failure that the change repairs."

What we would take instead — a single PR, refactor(connector): centralize LIMIT coercion, that:

  • keeps one coerce_limit() in connector/base.py, with the strictest semantics of the three variants above (reject bool, non-integral values, and negatives);
  • routes every interpolating connector through it — including canner.py, and replacing the private copy in mysql.py;
  • leaves ConnectorABC.query's signature as int | None (see the per-PR note on fix(duckdb): coerce LIMIT before SQL interpolation #2637 below);
  • tests the helper once in tests/unit/test_coerce_limit.py, with at most a smoke test per connector proving it is wired in, rather than repeating the same six cases eight times.

#2624 is the natural home for that; it is being kept open with a note to that effect.


On this PR specificallypostgres.py:256 is one of the bare-{limit} sites, so it does belong in the consolidated change.

@goldmedal goldmedal closed this Aug 3, 2026
@Bartok9

Bartok9 commented Aug 3, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @goldmedal — completely fair, and appreciated the detailed write-up.

Agreed on consolidating into a single refactor(connector): centralize LIMIT coercion on #2624: one shared coerce_limit() in connector/base.py with the strictest semantics (reject bool, non-integral values, and negatives), wire every interpolating connector through it (including canner.py and replacing the private copy in mysql.py), leave ConnectorABC.query as int | None, and test the helper once with light per-connector smoke wiring.

I'll reshape #2624 along those lines and close out the per-connector duplicates. Thanks again for the clear bar and for keeping #2624 open as the home.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

core python Pull requests that update Python code

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants