Fix SQL span summaries for multi-line queries and CTEs
Closed
AL
3d ago+84+84+01234567890123456789-15-15-01234567890123456789
Summary
Fixes two issues in logfire-sdk/logfire/_internal/db_statement_summary.py:
- Multi-line or space-padded CTE queries matched the inner
SELECTinstead of the outerSELECT:
After collapsing whitespace,WITH active_users AS (\n SELECT ...becameWITH active_users AS ( SELECT ....SELECT_CTE_RE = re.compile(rf'WITH (.+?) SELECT (.+?) FROM ({TABLE_RE})')then matched theSELECT ... FROM ...inside the first CTE body instead of the mainSELECTafter the CTE definitions — producing the wrong table name, wrong columns, wrong CTE count, and wrongWHERE …indicator. - Single newlines were not collapsed:
re.sub(r'\s{2,}', ' ', db_statement)left single\n/\tcharacters intact, so queries formatted with a single newline between clauses (e.g.SELECT ...\nFROM table) failedSELECT_REand fell back tofallback().
Replaced re.sub(r'\s{2,}', ' ', ...) with re.sub(r'\s+', ' ', ...) and replaced SELECT_CTE_RE with a linear-time match_cte_select() helper using the same quote/parenthesis depth tracking as outside_parentheses() (which also avoids quadratic regex backtracking in SELECT_CTE_RE).
Minimal runnable reproducer
from logfire._internal.db_statement_summary import message_from_db_statement
q = """
WITH active_users AS (
SELECT id, email FROM users WHERE active = true
),
recent_orders AS (
SELECT user_id, total FROM orders WHERE total > 100
)
SELECT * FROM recent_orders
"""
print(message_from_db_statement({'db.statement': q, 'db.system': 'postgresql'}, None, 'SELECT'))
# Before: 'WITH activ…users AS (…) SELECT id, email FROM users WHERE …'
# After: 'WITH …[2 CTEs] SELECT * FROM recent_orders'
Checklist context (CONTRIBUTING.md)
- Encountered in practice or analytical find: Observed by inspecting and testing standard formatted SQL queries against
db_statement_summary.py; affects any multi-line CTE or unindented multi-line query over 80 chars. - Impact on behavior: SQL span messages in the Logfire Live View showed misleading table names, columns, and CTE counts (or truncated fallback text with newlines).
- Security problem: No.
- Reviewability / confidence: Small (~30 lines), self-contained in
db_statement_summary.py, easy to verify and merge as-is. - Performance: Linear single pass over
db_statement(and removesSELECT_CTE_RE's two-lazy-group backtracking).
Verification
ruff checkandruff format --checkpassed on both touched files.pytest tests/test_db_statement_summary.py -vpassed (33 passed, including 3 new tests covering multi-line CTEs, spaces inside CTE parentheses, and unindented multi-lineSELECT).