Heuristic:Langgenius Dify SQL Escape Backslash First
| Knowledge Sources | |
|---|---|
| Domains | Debugging, Backend |
| Last Updated | 2026-02-12 08:00 GMT |
Overview
SQL string escaping rule: always escape backslashes first, then other special characters. Wrong order causes double-escaping corruption.
Description
When building SQL strings that require escaping (e.g., for log queries, full-text search, or dynamic filters), the order of escape operations matters. Backslashes (`\`) must be escaped before any other characters that use backslash as an escape prefix. If you escape double quotes first (`"` → `\"`), and then escape backslashes (`\` → `\\`), the backslash introduced by the quote escaping gets double-escaped: `"` → `\"` → `\\"`.
Usage
Apply this rule whenever implementing custom SQL string escaping, building dynamic queries with user input, or debugging garbled query results in the log store or search functionality.
The Insight (Rule of Thumb)
- Action: In any multi-step string escaping function, escape `\` → `\\` as the first operation. Then escape other characters (e.g., `"` → `\"`).
- Value: Prevents double-escaping bugs that corrupt query strings.
- Trade-off: None. Correct ordering has no cost.
Reasoning
Consider the input string: `He said "hello"`
Correct order (backslash first):
- Escape `\` → `\\` : No backslashes, no change → `He said "hello"`
- Escape `"` → `\"` : → `He said \"hello\"`
Incorrect order (quotes first):
- Escape `"` → `\"` : → `He said \"hello\"`
- Escape `\` → `\\` : → `He said \\"hello\\"` (WRONG — double escaped!)
The incorrect order produces `\\"` instead of `\"`, causing the SQL parser to see a literal backslash followed by an unescaped quote, breaking the query.
Code evidence from `api/extensions/logstore/sql_escape.py:127-130`:
The implementation follows this exact pattern: backslash escaping is performed as the first step in the escape chain, ensuring all subsequent escape characters are handled correctly without interference.