Skip to content

fix(oracle): coerce LIMIT before ROWNUM interpolation - #2634

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

fix(oracle): coerce LIMIT before ROWNUM interpolation#2634
Bartok9 wants to merge 2 commits into
Canner:mainfrom
Bartok9:fix/oracle-coerce-limit

Conversation

@Bartok9

@Bartok9 Bartok9 commented Jul 31, 2026

Copy link
Copy Markdown
Contributor

Summary

Oracle embeds limit into ROWNUM <= {limit} without validation. Coerce via int() and reject negatives (same contract as MySQL).

Test plan

  • cd core/wren && .venv/bin/python -m pytest tests/unit/test_oracle_coerce_limit.py -q (4 passed)

Summary by CodeRabbit

  • Bug Fixes

    • Improved Oracle query limit handling by validating and normalizing supplied limits.
    • Rejected negative or unsafe limit values to prevent malformed query execution.
    • Preserved unlimited queries when no limit is specified.
  • Tests

    • Added coverage for valid, missing, negative, and injection-like limit values.

Reject negative / non-numeric limit values before they are embedded in
``WHERE ROWNUM <= {limit}``.
@github-actions github-actions Bot added python Pull requests that update Python code core labels Jul 31, 2026
@coderabbitai

coderabbitai Bot commented Jul 31, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: d5f6ee09-5f3e-4484-98c6-747b47f075ea

📥 Commits

Reviewing files that changed from the base of the PR and between 6b15d02 and 60b2ff3.

📒 Files selected for processing (1)
  • core/wren/src/wren/connector/oracle.py
💤 Files with no reviewable changes (1)
  • core/wren/src/wren/connector/oracle.py

Walkthrough

The Oracle connector now coerces and validates query limits before SQL interpolation. Tests cover unlimited queries, invalid limits, injected values, and generated ROWNUM SQL.

Changes

Oracle limit coercion

Layer / File(s) Summary
Limit validation
core/wren/src/wren/connector/oracle.py, core/wren/tests/unit/test_oracle_coerce_limit.py
_coerce_limit preserves None, converts limits to integers, and raises ValueError for negative or injection-like values.
Query integration
core/wren/src/wren/connector/oracle.py, core/wren/tests/unit/test_oracle_coerce_limit.py
OracleConnector.query interpolates the coerced integer into the ROWNUM predicate. Test doubles capture execution and verify that the original semicolon-terminated SQL is not retained.

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

Suggested reviewers: goldmedal

Poem

A rabbit checks the limit line,
Coerces values neat and fine.
Bad inputs hop away,
Safe ROWNUM rules now stay.
SQL runs clean beneath the moon.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description includes a summary and test command but omits the required failure reproduction, actual error output, and duplicate check. Add the required failure reproduction with actual error output and document which open pull requests were checked for duplicates.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the Oracle LIMIT coercion change before ROWNUM interpolation.
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.
✨ 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

🧹 Nitpick comments (2)
core/wren/tests/unit/test_oracle_coerce_limit.py (1)

13-14: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Test the unlimited branch through OracleConnector.query.

This test verifies only _coerce_limit(None). It does not prove that OracleConnector.query(..., None) skips the ROWNUM wrapper and strips a trailing semicolon. Add a query-level assertion for the unlimited path.

🤖 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_oracle_coerce_limit.py` around lines 13 - 14, Add a
query-level test covering OracleConnector.query with a None limit, asserting the
generated SQL skips the ROWNUM wrapper and removes any trailing semicolon; keep
the existing _coerce_limit(None) unit assertion unchanged.
core/wren/src/wren/connector/oracle.py (1)

21-21: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Align the limit type hints with the accepted values.

_coerce_limit and the ConnectorABC.query contract are typed as int | None, but both MySQL and Oracle callers coerce int() inputs such as "5", and the MySQL tests keep that behavior. If numeric strings are supported, update the helper and shared interface contract to str | int | None. Otherwise, reject strings before coercion.

🤖 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/oracle.py` at line 21, Align the limit type
annotations with the behavior supported by MySQL and Oracle: update
_coerce_limit and the shared ConnectorABC.query contract to accept str | int |
None, preserving existing coercion of numeric strings. Ensure the related
connector implementations and tests remain consistent with this expanded
contract.
🤖 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/oracle.py`:
- Line 25: Update the limit conversion around coerced in the relevant Oracle
connector logic to reject fractional values and normalize TypeError, ValueError,
and OverflowError from int(limit) into ValueError, preserving the original
exception as the cause.

---

Nitpick comments:
In `@core/wren/src/wren/connector/oracle.py`:
- Line 21: Align the limit type annotations with the behavior supported by MySQL
and Oracle: update _coerce_limit and the shared ConnectorABC.query contract to
accept str | int | None, preserving existing coercion of numeric strings. Ensure
the related connector implementations and tests remain consistent with this
expanded contract.

In `@core/wren/tests/unit/test_oracle_coerce_limit.py`:
- Around line 13-14: Add a query-level test covering OracleConnector.query with
a None limit, asserting the generated SQL skips the ROWNUM wrapper and removes
any trailing semicolon; keep the existing _coerce_limit(None) unit assertion
unchanged.
🪄 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: 31a0ef11-ba90-42dc-88fe-7f0a3c210638

📥 Commits

Reviewing files that changed from the base of the PR and between 74bf59e and 6b15d02.

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

"""Validate limit before interpolating into ROWNUM SQL."""
if limit is None:
return None
coerced = int(limit)

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
python - <<'PY'
for value in (float("inf"), object()):
    try:
        int(value)
    except Exception as exc:
        print(type(exc).__name__)
PY

Repository: Canner/WrenAI

Length of output: 175


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Locate and inspect the relevant file and surrounding code without executing repository code.
fd -a 'oracle.py$' . || true
if [ -f core/wren/src/wren/connector/oracle.py ]; then
  wc -l core/wren/src/wren/connector/oracle.py
  sed -n '1,80p' core/wren/src/wren/connector/oracle.py | cat -n
fi

# Search for related query method definition/exception handling if the file path differs.
rg -n "def query|OverflowError|oracledb\.DatabaseError|int\(limit\)|raise ValueError" core/wren/src/wren/connector/oracle.py core -g '*.py' | head -200 || true

# Deterministic Python behavior probe for int() invalid inputs and whether catch-all DatabaseError matches them.
python3 - <<'PY'
values = (float('inf'), 'abc', object(), 1.9)
for value in values:
    try:
        result = int(value)
        print(f"{type(value).__name__}({value!r}) -> {result!r}")
    except Exception as exc:
        print(f"{type(value).__name__}({value!r}) -> {type(exc).__name__}: {exc!r}")

class FakeDatabaseError(Exception):
    pass

print("DatabaseError catches OverflowError?", isinstance(OverflowError(), FakeDatabaseError))
print("DatabaseError catches TypeError?", isinstance(TypeError(), FakeDatabaseError))
PY

Repository: Canner/WrenAI

Length of output: 11132


Normalize invalid limit conversion failures to ValueError.

int(limit) can raise OverflowError for nonfinite numbers and TypeError for unsupported objects, and it truncates fractional floats. Callers catch oracledb.DatabaseError, so these failures can escape with inconsistent exception types. Catch (TypeError, ValueError, OverflowError) and raise ValueError from the original exception.

Proposed fix
-    coerced = int(limit)
+    try:
+        coerced = int(limit)
+    except (TypeError, ValueError, OverflowError) as exc:
+        raise ValueError("limit must be an integer") from exc
📝 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
coerced = int(limit)
try:
coerced = int(limit)
except (TypeError, ValueError, OverflowError) as exc:
raise ValueError("limit must be an integer") from exc
🤖 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/oracle.py` at line 25, Update the limit
conversion around coerced in the relevant Oracle connector logic to reject
fractional values and normalize TypeError, ValueError, and OverflowError from
int(limit) into ValueError, preserving the original exception as the cause.

@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 specificallyoracle.py:186 interpolates into WHERE ROWNUM <= {limit}, so it belongs in the consolidated change too.

@Bartok9

Bartok9 commented Aug 3, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @goldmedal — understood. Closing rationale makes sense; consolidating into #2624 with the shared helper and strictest semantics.

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