Skip to main content

oxtel_sql/
rusqlite.rs

1//! [rusqlite](https://docs.rs/rusqlite): a span and
2//! `db.client.operation.duration` for every statement a connection runs.
3//!
4//! It uses SQLite's own trace hooks, so nothing about how the program calls
5//! rusqlite changes. SQLite reports when a statement starts running and when
6//! it finishes, with its duration; the span runs between the two, and the
7//! metric records SQLite's duration.
8//!
9//! SQLite's hooks don't say whether a statement failed, so these spans and
10//! measurements carry no `error.type`. The program's own error handling sees
11//! failures as before.
12
13use std::cell::RefCell;
14use std::sync::Arc;
15
16use ::rusqlite::Connection;
17use ::rusqlite::trace::{TraceEvent, TraceEventCodes};
18
19use crate::record::{Analysis, Call, analyze, describe_metrics};
20
21/// Statements open at once on one thread past which the oldest is dropped,
22/// in case SQLite never reports one finishing.
23const MAX_OPEN: usize = 32;
24
25struct Open {
26    sql: String,
27    analysis: Arc<Analysis>,
28    /// Held until the statement finishes: dropping it ends the span.
29    _span: tracing::Span,
30}
31
32thread_local! {
33    static OPEN: RefCell<Vec<Open>> = const { RefCell::new(Vec::new()) };
34}
35
36/// Record a client span and `db.client.operation.duration` for every
37/// statement `connection` runs, named by its query summary (`SELECT
38/// users`), with `db.system.name` `sqlite` and, unless turned off with
39/// [`record_query_text`](crate::record_query_text), its text with literals
40/// replaced.
41///
42/// This replaces any trace callback already set on the connection with
43/// `trace_v2`. Call it once per connection, after `oxtel::init()` so the
44/// metric's unit reaches the recorder.
45///
46/// ```no_run
47/// let conn = rusqlite::Connection::open("app.db")?;
48/// oxtel_sql::rusqlite::instrument(&conn);
49/// conn.execute("INSERT INTO kv (k, v) VALUES (?1, ?2)", ("a", 1))?;
50/// # Ok::<(), rusqlite::Error>(())
51/// ```
52pub fn instrument(connection: &Connection) {
53    describe_metrics();
54    connection.trace_v2(
55        TraceEventCodes::SQLITE_TRACE_STMT | TraceEventCodes::SQLITE_TRACE_PROFILE,
56        Some(on_event),
57    );
58}
59
60const SQLITE: &str = "sqlite";
61
62fn on_event(event: TraceEvent<'_>) {
63    match event {
64        TraceEvent::Stmt(statement, text) => {
65            // A trigger's subprogram starting, inside a statement already open.
66            if text.starts_with("--") {
67                return;
68            }
69            let sql = statement.sql();
70            let analysis = analyze(&sql);
71            let call = Call {
72                system: SQLITE,
73                namespace: None,
74                server: None,
75                analysis: &analysis,
76            };
77            let span = call.span();
78            OPEN.with(|open| {
79                let mut open = open.borrow_mut();
80                if open.len() >= MAX_OPEN {
81                    open.remove(0);
82                }
83                open.push(Open {
84                    sql: sql.into_owned(),
85                    analysis,
86                    _span: span,
87                });
88            });
89        }
90        TraceEvent::Profile(statement, duration) => {
91            let sql = statement.sql();
92            let finished = OPEN.with(|open| {
93                let mut open = open.borrow_mut();
94                let i = open.iter().rposition(|o| o.sql == sql)?;
95                Some(open.remove(i))
96            });
97            let analysis = match &finished {
98                Some(open) => Arc::clone(&open.analysis),
99                None => analyze(&sql),
100            };
101            let call = Call {
102                system: SQLITE,
103                namespace: None,
104                server: None,
105                analysis: &analysis,
106            };
107            call.record_duration(duration.as_secs_f64(), None);
108            // Dropping the span ends it.
109            drop(finished);
110        }
111        _ => {}
112    }
113}