langchain4j/experimental/langchain4j-experimental-sql/src
Benamira05 cfd90e52f3
fix: Avoid StringIndexOutOfBoundsException when cleaning unclosed code fence in SqlDatabaseContentRetriever (#5737)
## Issue
Closes #5736

## Change

`SqlDatabaseContentRetriever.clean()` strips a markdown code fence from
the generated SQL before executing it. When the response has an opening
fence (```sql```/``````) but no closing fence, `substring(start,
lastIndexOf("```"))` gets `end < start` (`lastIndexOf` matches the
opening fence's own backticks) and throws
`StringIndexOutOfBoundsException`. `clean()` runs outside `retrieve()`'s
`try/catch`, so the exception escapes the retry / `emptyList()` fallback
the method is designed around.

This extracts the shared boundary logic into a `stripCodeFence` helper:
it slices to the closing fence only when one follows the opening tag,
otherwise returns the text after the opening tag. Behaviour for
correctly closed fences is unchanged.

Same underlying bug as #5731, fixed for `HibernateContentRetriever` in
#5732 (both classes independently implement the same fence-stripping
logic; `SqlDatabaseContentRetriever` was missed in that fix).

Added `SqlDatabaseContentRetrieverTest` (the module's first unit test —
`clean()` is `protected` and pure, so no live database is needed)
covering closed fences (regression), unclosed fences for both fence
types, and plain text.

## General checklist
- [X] There are no breaking changes (API, behaviour)
- [X] I have added unit and/or integration tests for my change
- [X] The tests cover both positive and negative cases
- [X] I have manually run all the unit and integration tests in the
module I have added/changed, and they are all green

---------

Co-authored-by: Benamira05 <145583236+Benamira05@users.noreply.github.com>
2026-07-09 09:42:59 +02:00
..
main/java/dev/langchain4j/experimental/rag/content/retriever/sql fix: Avoid StringIndexOutOfBoundsException when cleaning unclosed code fence in SqlDatabaseContentRetriever (#5737) 2026-07-09 09:42:59 +02:00
test fix: Avoid StringIndexOutOfBoundsException when cleaning unclosed code fence in SqlDatabaseContentRetriever (#5737) 2026-07-09 09:42:59 +02:00