Skip to main content

hwhkit_observability/
sqlx_instrument.rs

1//! Lightweight OpenTelemetry instrumentation helpers for `sqlx`.
2//!
3//! Rather than wrap [`sqlx::Executor`] (which is impractical because the
4//! trait is not dyn-compatible and bounds vary across query types), this
5//! module exposes:
6//!
7//! - [`SqlxSpan::query`]: a constructor that opens a `tracing` span with
8//!   the canonical OpenTelemetry semantic-conventions database attributes
9//!   (`db.system`, `db.statement`, …) and lets the caller `.instrument()`
10//!   the underlying sqlx future.
11//!
12//! Usage:
13//!
14//! ```ignore
15//! use hwhkit_observability::sqlx_instrument::SqlxSpan;
16//! use tracing::Instrument;
17//!
18//! let stmt = "SELECT name FROM users WHERE id = $1";
19//! let span = SqlxSpan::query(DbSystem::Postgres, stmt);
20//! let row = sqlx::query(stmt).bind(1).fetch_one(&pool).instrument(span).await?;
21//! ```
22//!
23//! When the `otel` feature is also enabled the spans are picked up by the
24//! tracing-opentelemetry layer installed by [`crate::otel_layer::init_with_otel`].
25
26use tracing::{field::Empty, Span};
27
28/// SQL dialect tag used as the `db.system` attribute on instrumented
29/// query spans (matching the OpenTelemetry semantic conventions).
30///
31/// Marked `#[non_exhaustive]` so adding new dialects in a minor release
32/// (e.g. `Mssql`) is non-breaking.
33#[derive(Debug, Clone, Copy)]
34#[non_exhaustive]
35pub enum DbSystem {
36    /// PostgreSQL — emitted as `db.system = "postgresql"`.
37    Postgres,
38    /// MySQL / MariaDB — emitted as `db.system = "mysql"`.
39    Mysql,
40    /// SQLite — emitted as `db.system = "sqlite"`.
41    Sqlite,
42    /// Catch-all for any other SQL dialect — emitted as
43    /// `db.system = "other_sql"`.
44    Other,
45}
46
47impl DbSystem {
48    /// Stable string representation used for the `db.system` span field.
49    pub fn as_str(&self) -> &'static str {
50        match self {
51            DbSystem::Postgres => "postgresql",
52            DbSystem::Mysql => "mysql",
53            DbSystem::Sqlite => "sqlite",
54            DbSystem::Other => "other_sql",
55        }
56    }
57}
58
59/// Span constructor for sqlx queries — see [`SqlxSpan::query`].
60pub struct SqlxSpan;
61
62impl SqlxSpan {
63    /// Open a `tracing::Span` describing a sqlx query. Set
64    /// `db.rows_affected` after execution via `Span::current().record(...)`.
65    pub fn query(system: DbSystem, statement: &str) -> Span {
66        let span = tracing::info_span!(
67            "sqlx.query",
68            otel.kind = "client",
69            db.system = system.as_str(),
70            db.statement = statement,
71            db.rows_affected = Empty,
72        );
73        span
74    }
75}
76
77/// Helper to record the `db.rows_affected` attribute on the current span
78/// after a sqlx execute completes.
79pub fn record_rows_affected(span: &Span, n: u64) {
80    span.record("db.rows_affected", n);
81}