Skip to content

fix(duckdb): case-insensitive .duckdb discovery, deterministic attach aliases, and single-statement SQL hardening - #2411

Merged
goldmedal merged 10 commits into
Canner:mainfrom
Bartok9:fix/duckdb-ext-case
Jul 1, 2026
Merged

goldmedal merged 10 commits into
Canner:mainfrom
Bartok9:fix/duckdb-ext-case

Conversation

@Bartok9

@Bartok9 Bartok9 commented Jun 29, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Harden the DuckDB connector around database-file discovery and single-statement SQL handling:

  1. Case-insensitive .duckdb discovery (the original fix) — _list_duckdb_files matches the extension case-insensitively, so valid databases with upper/mixed-case extensions (e.g. WAREHOUSE.DUCKDB) are no longer silently skipped and no longer surface a spurious DUCKDB_FILE_NOT_FOUND.
  2. Deterministic alias de-duplication — case-insensitive discovery can now surface warehouse.duckdb and warehouse.DUCKDB, which previously derived the same attach alias. _attach_database sorts the file list and derives unique aliases deterministically (warehouse, warehouse_1, …), tracked case-insensitively.
  3. query() / dry_run() semicolon handling — both now use the shared _strip_trailing_semicolon regex helper (matching canner/clickhouse/trino) so a trailing ; doesn't produce invalid wrapped SQL, while semicolons inside string literals are preserved. dry_run() neutralizes multi-statement input by wrapping in a LIMIT 0 subquery (same as the other connectors) rather than pre-rejecting it — no side effects, no false positives.

Motivation

str.endswith(".duckdb") is case-sensitive, dropping mixed-case database files on case-preserving filesystems/object stores and raising DUCKDB_FILE_NOT_FOUND even when a valid database is present. The follow-on changes address edge cases that fix newly exposes (alias collisions) and align the LIMIT-wrap / dry-run semicolon handling with the rest of the codebase.

Fix

  • _list_duckdb_files: file.path.lower().endswith(".duckdb").
  • _attach_database: sorted() + deterministic, case-insensitively tracked unique aliases.
  • query()/dry_run(): reuse _strip_trailing_semicolon; dry_run wraps in LIMIT 0 subquery.

Verification

uv run --no-sync pytest tests/unit/test_duckdb_file_listing.py tests/unit/test_engine.py -q — 15 passed. ruff check clean.

Regression tests cover: mixed-case discovery, case-colliding alias uniquification, query() trailing-semicolon strip, dry_run() LIMIT-0 wrap, and dry_run() preserving a semicolon inside a string literal.

Scope / risk

Changes confined to core/wren/src/wren/connector/duckdb.py (Apache-2.0 path) plus its unit tests.

…bases

_list_duckdb_files filtered candidate files with
file.path.endswith('.duckdb'), a case-sensitive check. A DuckDB database
file with an upper- or mixed-case extension (e.g. WAREHOUSE.DUCKDB, a
common shape for exported files) was silently skipped, leaving the
connector to raise DUCKDB_FILE_NOT_FOUND even though a valid database was
present in the directory.

Lower-case the path before the suffix comparison so extension matching is
case-insensitive, mirroring how filesystems treat these files.
@github-actions github-actions Bot added python Pull requests that update Python code core labels Jun 29, 2026
@coderabbitai

coderabbitai Bot commented Jun 29, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

DuckDBConnector now filters .duckdb files case-insensitively and assigns unique attach aliases when discovered filenames collide by case. New unit tests cover mixed-case file discovery and alias suffixing.

Changes

DuckDB connector discovery and attachment

Layer / File(s) Summary
Connector docstrings and attachment logic
core/wren/src/wren/connector/duckdb.py
query, _attach_database, _list_duckdb_files, and close gain docstrings, _list_duckdb_files matches .duckdb case-insensitively, and _attach_database de-duplicates aliases with deterministic numeric suffixes.
DuckDB discovery and alias regression tests
core/wren/tests/unit/test_duckdb_file_listing.py
Helpers and tests mock directory listings and connection calls to verify mixed-case .duckdb discovery and unique aliases for case-colliding filenames.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~15 minutes

Poem

🐇 I hopped where ducky files may hide,
With caps and cases side by side.
One alias, two, then three in line,
And all the right paths now neatly shine.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 70.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
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.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly captures the DuckDB discovery and aliasing fixes, with only a minor extra clause.
✨ 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: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
core/wren/src/wren/connector/duckdb.py (1)

123-129: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Handle alias collisions introduced by case-insensitive discovery.

With this change, warehouse.duckdb and warehouse.DUCKDB are both returned here, but Line 102 derives the same attach alias (warehouse) for both. On a case-sensitive filesystem or object store, the second attach will now fail even though both files are valid.

🤖 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/duckdb.py` around lines 123 - 129, The DuckDB
discovery logic in the file listing loop now returns case-insensitive duplicates
that can map to the same attach alias in the alias derivation path, so update
the attach flow in duckdb.py to detect and resolve collisions before attaching.
Use the existing discovery/attach code around the URL collection and the alias
creation logic to ensure each discovered .duckdb file gets a unique alias (or
skip duplicates deterministically) when files like warehouse.duckdb and
warehouse.DUCKDB both appear.
🤖 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/duckdb.py`:
- Around line 81-83: The LIMIT wrapping in DuckDB is currently applied directly
to the raw SQL string, so semicolon-terminated queries become invalid when
wrapped. Update the DuckDB connector logic in the execute/query path to strip
any trailing semicolons from the SQL before constructing the SELECT * FROM (...)
AS _q LIMIT wrapper, and keep the limit behavior unchanged for non-semicolon
inputs.
- Around line 85-87: The dry_run() method in DuckDBConnector currently passes
raw SQL into EXPLAIN, which still allows semicolon-separated batches to execute
beyond the first statement. Update dry_run() to detect and reject
multi-statement input before calling self.connection.execute(), keeping the
no-side-effects contract intact. Use the dry_run() method as the fix point and
ensure only a single statement is accepted before EXPLAIN is run.

---

Outside diff comments:
In `@core/wren/src/wren/connector/duckdb.py`:
- Around line 123-129: The DuckDB discovery logic in the file listing loop now
returns case-insensitive duplicates that can map to the same attach alias in the
alias derivation path, so update the attach flow in duckdb.py to detect and
resolve collisions before attaching. Use the existing discovery/attach code
around the URL collection and the alias creation logic to ensure each discovered
.duckdb file gets a unique alias (or skip duplicates deterministically) when
files like warehouse.duckdb and warehouse.DUCKDB both appear.
🪄 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

Run ID: 0dc86538-6433-4dbf-a374-0354f3310ad4

📥 Commits

Reviewing files that changed from the base of the PR and between 035e258 and 7fff629.

📒 Files selected for processing (1)
  • core/wren/src/wren/connector/duckdb.py

Comment thread core/wren/src/wren/connector/duckdb.py Resolved
Comment thread core/wren/src/wren/connector/duckdb.py Resolved
Bartok9 added 2 commits June 29, 2026 02:43
Case-insensitive discovery can surface files whose basenames differ only
by case (warehouse.duckdb / warehouse.DUCKDB). Both derived the same
attach alias, so the second ATTACH would fail on case-sensitive
filesystems/object stores. Derive a unique alias per file deterministically.

Adds a regression test asserting distinct aliases (warehouse, warehouse_1).
@Bartok9

Bartok9 commented Jun 29, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @coderabbitai — good catch on the alias collision. That edge case is real: case-insensitive discovery can now surface warehouse.duckdb and warehouse.DUCKDB, both of which previously derived the same attach alias (warehouse), so the second ATTACH would fail on a case-sensitive filesystem/object store.

Pushed a fix: _attach_database now derives a unique alias per file deterministically (warehouse, then warehouse_1, …), tracked case-insensitively to match the discovery semantics. Added a regression test (test_attach_database_uniquifies_case_colliding_aliases) asserting distinct aliases. Full suite green.

On the two inline LIMIT/dry_run semicolon comments: those touch pre-existing code paths unrelated to this one-line case-insensitivity change, so I'm leaving them out of scope for this PR to keep it focused.

@coderabbitai

coderabbitai Bot commented Jun 29, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

@Bartok9 Good fix — the deterministic alias uniquification in core/wren/src/wren/connector/duckdb.py addresses the collision cleanly, and the regression test coverage sounds spot on. Keeping the unrelated LIMIT/dry_run semicolon comments out of scope for this PR makes sense to me.

(•ᴗ•)🐇


✏️ Learnings added
Learnt from: Bartok9
URL: https://github.com/Canner/WrenAI/pull/2411

Timestamp: 2026-06-29T06:46:30.478Z
Learning: In `core/wren/src/wren/connector/duckdb.py`, case-insensitive DuckDB file discovery can surface files whose stems differ only by extension casing, such as `warehouse.duckdb` and `warehouse.DUCKDB`. To avoid `ATTACH` alias collisions, `DuckDBConnector._attach_database` should derive deterministic unique aliases like `warehouse`, `warehouse_1`, ... and track them case-insensitively to match discovery semantics. A regression test exists for this behavior: `core/wren/tests/unit/test_duckdb_file_listing.py::test_attach_database_uniquifies_case_colliding_aliases`.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.


If you found this review helpful, would you consider giving us a shout-out on X?

Thank you for using CodeRabbit!

@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/duckdb.py`:
- Around line 99-114: Alias assignment in the DuckDB connector is still
nondeterministic because db_files is processed in whatever order OpenDAL
returns. Sort db_files before the loop in the alias-deriving logic inside the
DuckDB attach path so the same file consistently gets the bare alias across
runs, while preserving the existing unique_alias/used_aliases collision
handling.
🪄 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

Run ID: 94b10aae-f250-49e8-9843-7e2f2a430d69

📥 Commits

Reviewing files that changed from the base of the PR and between c32c043 and 84c966c.

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

Comment thread core/wren/src/wren/connector/duckdb.py Resolved
@Bartok9

Bartok9 commented Jun 29, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @coderabbitai — addressed the nondeterministic alias ordering. db_files is now sorted() before the attach loop, so the bare alias deterministically maps to the same file across runs regardless of OpenDAL listing order, while the existing used_aliases collision handling (warehouse, warehouse_1, …) is preserved. Pushed in 5cbbc49.

@coderabbitai

coderabbitai Bot commented Jun 29, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

@Bartok9 Good catch — sorting db_files before the attach loop is the missing piece here. That makes the unsuffixed alias assignment deterministic across OpenDAL listing order while keeping the existing case-insensitive collision handling intact. Thanks for tightening that up in 5cbbc49.

🐇✨


✏️ Learnings added
Learnt from: Bartok9
URL: https://github.com/Canner/WrenAI/pull/2411

Timestamp: 2026-06-29T06:51:13.284Z
Learning: In `core/wren/src/wren/connector/duckdb.py`, `DuckDBConnector._attach_database` should sort `db_files` before iterating so the bare attach alias deterministically maps to the same DuckDB file across runs regardless of OpenDAL listing order, while preserving the existing case-insensitive `used_aliases` collision handling such as `warehouse` and `warehouse_1`.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

Bartok9 and others added 2 commits June 29, 2026 04:18
…ed order

Files are sorted before alias assignment, so 'data' attaches first and the
two case-colliding 'warehouse' files get warehouse/warehouse_1.
…i-statement dry_run

Addresses CodeRabbit findings:
- query(): a semicolon-terminated SQL string produced invalid wrapped SQL
  (SELECT * FROM (SELECT 1;) AS _q LIMIT n). Strip trailing ; before wrapping.
- dry_run(): duckdb.execute runs semicolon-separated batches, so EXPLAIN could
  still execute trailing statements. Reject multi-statement input.
Adds regression tests for both.
@Bartok9

Bartok9 commented Jun 29, 2026

Copy link
Copy Markdown
Contributor Author

Addressed in cb3bcb9:

  • query() LIMIT-wrap with trailing semicolon (valid): now strips a trailing ; before wrapping, so SELECT 1; becomes SELECT * FROM (SELECT 1) AS _q LIMIT n.
  • dry_run() multi-statement guard (valid): rejects multi-statement input via WrenError before EXPLAIN, preserving the no-side-effects contract (single trailing ; still allowed).
  • Alias collision on case-insensitive discovery (already resolved): _attach_database deterministically uniquifies case-colliding aliases (warehouse / warehouse_1) over a sorted file list.

Added 3 regression tests; full test_duckdb_file_listing.py (5) and test_engine.py (9) pass, ruff clean.

@goldmedal

Copy link
Copy Markdown
Collaborator

Review

The core fix is correct and well-tested, but the PR bundles more than the title/description says, and the dry_run change has a correctness bug. Two items to address before merge (no need to split the PR — updating the title/description is fine).

🔴 1. Title & description don't match the diff

The body says:

One-line change (file.path -> file.path.lower()) in the suffix check only. Directory exclusion and path construction are untouched.

But the diff actually changes four things:

Change Disclosed?
_list_duckdb_files — .lower().endswith(".duckdb") ✅ the stated fix
_attach_database — sorted() + alias uniquification ⚠️ only in the CodeRabbit blurb (a valid follow-on: the case fix newly makes case-colliding aliases possible)
query() — strip trailing ; before the LIMIT wrap ❌ not mentioned
dry_run() — reject multi-statement SQL ❌ not mentioned

The query/dry_run changes are legitimate hardening, so keeping them here is fine — but please update the title and description so they reflect the real scope (case-insensitive discovery + alias dedup + query/dry_run semicolon/multi-statement handling). A reviewer reading "one-line change" would not expect dry_run semantics to change.

🔴 2. dry_run multi-statement check has false positives

stripped = sql.rstrip().rstrip(";")
if ";" in stripped:
    raise WrenError(ErrorCode.INVALID_SQL, "dry_run only accepts a single SQL statement.")

";" in stripped rejects valid single statements that contain a semicolon inside a string literal:

SELECT ';' AS x   →  rejected as "multi-statement"

This contradicts the codebase's own stance — the sibling _strip_trailing_semicolon helpers (clickhouse.py:315, trino.py:354, canner.py:124) deliberately preserve semicolons inside string literals. The new tests don't cover this case, so it stays green while the bug is live.

Suggested fix: the other connectors don't reject multi-statement at all — they neutralize it by wrapping in a subquery (SELECT * FROM ({stripped}) AS _q LIMIT 0), where any trailing statement becomes a natural syntax error. DuckDB's EXPLAIN {sql} is the odd one out because EXPLAIN doesn't wrap. Applying the same subquery-wrap to dry_run removes the side-effect risk without false positives and matches the rest of the codebase.

🟡 3. Reuse the shared _strip_trailing_semicolon helper

query() uses inline sql.rstrip().rstrip(";"), but three connectors already have a regex-based _strip_trailing_semicolon for exactly this LIMIT-wrap problem. The inline version is also weaker — it doesn't fully clean interleaved separators:

"SELECT 1 ; ; "  →  "SELECT 1 ; "   # stray ; survives → invalid wrapped subquery

Prefer promoting/reusing the existing helper over a fourth, less-robust inline variant.

🟢 What's good

  • The core .lower().endswith fix is correct and minimal.
  • Alias uniquification is sound: lowercased-alias tracking gives warehouse.duckdb / warehouse.DUCKDB → warehouse / warehouse_1, and it handles a real warehouse_1.duckdb colliding with the generated suffix. sorted() makes assignment deterministic — a genuine improvement.
  • Tests are clean (bypass the real connection via __new__) and cover the happy paths for all four changes.

…ejecting multi-statement

- query() and dry_run() now use a shared _strip_trailing_semicolon regex
  helper (matching canner/clickhouse/trino) instead of the weaker inline
  rstrip, which mishandled interleaved separators like 'SELECT 1 ; ; '.
- dry_run() no longer pre-rejects multi-statement input (false-positived on
  semicolons inside string literals, e.g. SELECT ';' AS x). It now wraps in a
  LIMIT 0 subquery like the other connectors, so trailing statements become a
  natural syntax error with no side effects.
- Updated/added regression tests: string-literal semicolon preserved, LIMIT 0
  wrap for dry_run.
@Bartok9 Bartok9 changed the title fix(duckdb): match .duckdb files case-insensitively when listing databases fix(duckdb): case-insensitive .duckdb discovery, deterministic attach aliases, and single-statement SQL hardening Jul 1, 2026
@Bartok9

Bartok9 commented Jul 1, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review @goldmedal — all three addressed in 89bb6cb.

1. Title & description scope — Updated both to reflect the real diff: case-insensitive discovery + deterministic alias dedup + query/dry_run semicolon/multi-statement handling. No more "one-line change" framing.

2. dry_run false positives (🔴) — Good catch, ";" in stripped did reject valid statements like SELECT ';' AS x. Dropped the multi-statement pre-check entirely and switched to the same neutralization the other connectors use: wrap in SELECT * FROM ({stripped}) AS _q LIMIT 0. Any trailing statement becomes a natural syntax error inside the subquery, no rows materialize, and semicolons inside string literals are preserved. Added a regression test for the string-literal case.

3. Shared helper (🟡) — query() and dry_run() now both call a _strip_trailing_semicolon helper using the same re.compile(r"[;\s]+\Z") pattern as canner/clickhouse, which also fixes the interleaved-separator weakness ("SELECT 1 ; ; " → "SELECT 1").

Full suite green: test_duckdb_file_listing.py + test_engine.py = 15 passed, ruff clean.

@goldmedal goldmedal left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

@Bartok9 LGTM

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