Skip to main content

Module sql_commenter

Module sql_commenter 

Source
Expand description

Correlate SQL statements with OpenTelemetry traces.

annotate_sql appends a sqlcommenter-style traceparent comment carrying the currently active span’s trace context to a SQL statement, e.g.

SELECT * FROM users WHERE id = $1 /*traceparent='00-<32-hex>-<16-hex>-01'*/

The comment survives Postgres query normalization and appears in pg_stat_activity and in Postgres logs (slow query log, auto_explain, lock waits), so a statement observed server-side can be matched back to a distributed trace. pg_stat_statements retains the comment of the first execution seen per query id (comments are excluded from the query id jumble), which yields an exemplar trace per statement shape.

§Sampling and the prepared statement cache

Annotation only happens when the active span is sampled: an un-sampled span is never exported, so its trace id cannot be looked up in the tracing backend and annotating would be pure cost. The cost matters because an annotated statement’s text is unique per span — it can never be served from sqlx’s per-connection prepared statement cache and is executed non-persistently (a server-side parse + plan per execution). Gating on the sampled flag keeps full prepared-statement reuse for all un-sampled traffic.

Annotation requires the tracing-context feature and an initialized OpenTelemetry tracing layer. Otherwise annotate_sql is a zero-cost pass-through.

Functions§

annotate_sql
Appends the current sampled span’s traceparent as a SQL comment to sql.
current_traceparent
W3C traceparent of the currently active span. Always None without the tracing-context feature.