Jump to content

Connect Leeroopedia MCP: Equip your AI agents to search best practices, build plans, verify code, diagnose failures, and look up hyperparameter defaults.

Heuristic:Langgenius Dify SQL Escape Backslash First

From Leeroopedia
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):

  1. Escape `\` → `\\` : No backslashes, no change → `He said "hello"`
  2. Escape `"` → `\"` : → `He said \"hello\"`

Incorrect order (quotes first):

  1. Escape `"` → `\"` : → `He said \"hello\"`
  2. 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.

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment