Skip to content

feat: Add Google SQLCommenter support for automatic query attribution #407

@cofin

Description

@cofin

Summary

Add built-in support for Google SQLCommenter — a spec for appending structured /* key='value' */ comments to SQL statements that correlate queries with application context (framework, route, trace IDs).

This enables observability tools like Cloud SQL Insights, PgHero, and OpenTelemetry-aware query analyzers to automatically map slow queries back to the application code that generated them.

Example

-- Before
SELECT * FROM users WHERE active = $1

-- After (with sqlcommenter enabled)
SELECT * FROM users WHERE active = $1
/*db_driver='asyncpg',framework='litestar%3A2.15.0',route='%2Fapi%2Fusers',
traceparent='00-5bd66ef5095369c7b0d1f8f4bd33716a-c532cb4098ac3dd2-01'*/

Proposed Design

1. Core Module (sqlspec/sqlcommenter.py)

Standalone serialization/parsing per the sqlcommenter spec:

  • generate_comment(attributes) — URL-encode keys/values, escape meta-chars, sort lexicographically, wrap in /* */
  • append_comment(sql, attributes) — append to SQL; skip if comment already present
  • parse_comment(sql) — extract and decode comment back to dict (round-trip)
  • Stdlib only (urllib.parse.quote), mypyc-compatible

2. Pipeline Integration (via output_transformer)

sqlspec already has an output_transformer hook on StatementConfig that transforms (sql, params) -> (sql, params) post-compilation. sqlcommenter plugs in cleanly:

from sqlspec.sqlcommenter import create_sqlcommenter_transformer

config = StatementConfig(
    # ... existing config ...
    output_transformer=create_sqlcommenter_transformer(
        db_driver="asyncpg",
        framework="litestar:2.15.0",
    ),
)

Or via a convenience flag:

config = StatementConfig(
    enable_sqlcommenter=True,  # auto-populates db_driver, traceparent from context
)

3. Framework Enrichment

  • Litestar: SQLSpecPlugin auto-injects route, controller, action from request scope
  • FastAPI/Starlette: Middleware sets request-scoped attributes via contextvars
  • Custom labels: SQLCommenterContext.set("tenant_id", tenant) for user-defined attributes

Why sqlspec?

sqlspec already has the infrastructure for this:

  • StatementEvent carries trace_id, span_id, db_system, driver — the exact attributes sqlcommenter needs
  • output_transformer provides a clean, zero-overhead hook point (no driver changes needed)
  • ObservabilityRuntime and SpanManager already manage OpenTelemetry context

Standard Attributes

Per the sqlcommenter spec:

Key Source Description
db_driver Adapter metadata e.g., asyncpg, psycopg
framework Framework integration e.g., litestar:2.15.0
route Request context e.g., /api/users
controller Request context e.g., UserController
action Request context e.g., list_users
traceparent OpenTelemetry span W3C Trace Context
tracestate OpenTelemetry span W3C Trace State

Implementation Plan

Chapter Scope Depends On
1. sqlcommenter-core Serialization, parsing, escaping, unit tests
2. pipeline-integration output_transformer factory, enable_sqlcommenter flag, OTel auto-population Ch. 1
3. framework-enrichment Litestar/FastAPI/Starlette request context injection, custom attribute API Ch. 2

Detailed PRD: .agents/specs/sqlcommenter-support/prd.md

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions