Skip to main content

oxtel_sql/
lib.rs

1//! Database client spans and metrics, following the OpenTelemetry semantic
2//! conventions for databases. Part of [oxtel](https://github.com/agentstatelabs/oxtel).
3//!
4//! With the `rusqlite` feature, one line instruments a SQLite connection:
5//!
6//! ```no_run
7//! # #[cfg(feature = "rusqlite")] {
8//! let conn = rusqlite::Connection::open("app.db").unwrap();
9//! oxtel_sql::rusqlite::instrument(&conn);
10//! # }
11//! ```
12//!
13//! With the `postgres` feature, one line wraps a tokio-postgres client where
14//! the connection is made, and with `deadpool-postgres`, a pool (see
15//! `oxtel_sql::postgres`):
16//!
17//! ```no_run
18//! # #[cfg(feature = "postgres")]
19//! # async fn run(client: tokio_postgres::Client, config: tokio_postgres::Config) {
20//! let client = oxtel_sql::postgres::Client::new(client, &config);
21//! # }
22//! ```
23//!
24//! Every statement they run then gets:
25//!
26//! - **a client span**, named by its query summary (`SELECT users`, `INSERT
27//!   orders SELECT carts`), with `db.system.name`, `db.query.summary` and
28//!   `db.query.text`, plus `db.namespace` and the server for PostgreSQL;
29//! - **`db.client.operation.duration`**, through the `metrics` facade, by
30//!   system and query summary;
31//! - for PostgreSQL, when it fails, the error's SQLSTATE as
32//!   `db.response.status_code` and `error.type`, on both.
33//!
34//! `db.query.text` is the statement with every literal replaced by `?` and
35//! comments removed, so values never reach telemetry; turn it off with
36//! [`record_query_text`]. As the conventions say for raw SQL, the operation
37//! and table names aren't taken from the text into `db.operation.name` and
38//! `db.collection.name`: the summary carries them.
39//!
40//! Spans are recorded with `tracing` and metrics with `metrics`, so they go
41//! wherever the program sends them: with `oxtel::init()`, to OTLP or
42//! Prometheus. The spans' target is `oxtel_sql`, so `RUST_LOG=…,oxtel_sql=off`
43//! turns them off.
44//!
45//! For sqlx, wrap the pool with the `sqlx-0.8` or `sqlx-0.9` feature:
46//! `oxtel_sql::sqlx::v0_9::Pool::new(pool)`. `oxtel::init()` also makes the
47//! same spans and metric from sqlx's own query events, with no code change,
48//! but without failures or which database a query went to; the
49//! `oxtel_sql::sqlx` module compares the two.
50//!
51//! [`summarize`] and [`sanitize`] are available on their own, for
52//! instrumenting a database client this crate doesn't cover.
53
54#[cfg(any(
55    feature = "deadpool-postgres",
56    feature = "sqlx-0.8",
57    feature = "sqlx-0.9"
58))]
59mod pool;
60#[cfg(feature = "postgres")]
61pub mod postgres;
62mod query;
63mod record;
64#[cfg(feature = "rusqlite")]
65pub mod rusqlite;
66#[cfg(any(feature = "sqlx-0.8", feature = "sqlx-0.9"))]
67pub mod sqlx;
68
69pub use query::{sanitize, summarize};
70pub use record::{describe_metrics, record_query_text, records_query_text};