Skip to main content

diesel/sqlite/connection/
trace.rs

1//! Types for the SQLite trace callback.
2//!
3//! See [`sqlite3_trace_v2`](https://sqlite.org/c3ref/trace_v2.html)
4//! and the [trace event codes](https://sqlite.org/c3ref/c_trace.html).
5
6#[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
7extern crate libsqlite3_sys as ffi;
8
9#[cfg(all(target_family = "wasm", target_os = "unknown"))]
10use sqlite_wasm_rs as ffi;
11
12use super::SqliteConnection;
13
14// The `SQLITE_TRACE_*` constants are typed `i32` in old `libsqlite3-sys` and
15// `c_uint` in new ones. Normalize them to `u32` here, the single place these
16// constants are read. The casts are required for the old versions.
17#[allow(clippy::unnecessary_cast)]
18pub(crate) const TRACE_STMT: u32 = ffi::SQLITE_TRACE_STMT as u32;
19#[allow(clippy::unnecessary_cast)]
20pub(crate) const TRACE_PROFILE: u32 = ffi::SQLITE_TRACE_PROFILE as u32;
21#[allow(clippy::unnecessary_cast)]
22pub(crate) const TRACE_ROW: u32 = ffi::SQLITE_TRACE_ROW as u32;
23
24bitflags::bitflags! {
25    /// Trace event mask selecting which events the callback receives.
26    ///
27    /// Added in SQLite 3.14.0 (2016-08-08). Combine flags with `|`, and
28    /// `SqliteTraceFlags::all()` selects every event.
29    ///
30    /// Bits that are not one of the declared flags, for example set through
31    /// `from_bits_retain`, are discarded before the callback is registered.
32    ///
33    /// SQLite's `SQLITE_TRACE_CLOSE` event is intentionally not exposed. Diesel
34    /// removes the trace callback before closing the connection, so a close
35    /// event can never reach the callback.
36    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
37    pub struct SqliteTraceFlags: u32 {
38        /// Statement start: fires when a prepared statement begins executing,
39        /// delivering the SQL text.
40        const STMT = TRACE_STMT;
41        /// Statement profile: fires when a statement finishes, delivering the
42        /// SQL text and the elapsed time in nanoseconds.
43        const PROFILE = TRACE_PROFILE;
44        /// Row: fires for every row a query returns. Very frequent and carries
45        /// no data, so prefer `STMT` and `PROFILE` for most logging.
46        const ROW = TRACE_ROW;
47    }
48}
49
50/// Trace events delivered to the trace callback.
51///
52/// The callback receives one of these events based on the mask
53/// registered with [`on_trace`](crate::sqlite::SqliteConnection::on_trace).
54#[derive(Debug, Clone, Copy)]
55#[non_exhaustive]
56pub enum SqliteTraceEvent<'a> {
57    /// A prepared statement is beginning to execute.
58    #[non_exhaustive]
59    Statement {
60        /// The unexpanded SQL text, with parameter placeholders. For triggers
61        /// and nested statements SQLite may report this as a `-- comment`
62        /// rather than the SQL itself.
63        sql: &'a str,
64        /// Whether the statement is read-only, via
65        /// [`sqlite3_stmt_readonly`](https://sqlite.org/c3ref/stmt_readonly.html)
66        /// (`true` for `SELECT` and read-only `PRAGMA`). Indirect writes, such
67        /// as a user-defined function on another connection or a virtual table
68        /// with side effects, are not detected.
69        readonly: bool,
70    },
71
72    /// A prepared statement has finished executing.
73    #[non_exhaustive]
74    Profile {
75        /// The SQL text of the statement (from `sqlite3_sql`).
76        sql: &'a str,
77        /// Time taken in nanoseconds.
78        duration_ns: u64,
79        /// Whether the statement is read-only. See
80        /// [`SqliteTraceEvent::Statement::readonly`] for details.
81        readonly: bool,
82    },
83
84    /// A row has been returned from a query.
85    ///
86    /// Fires for every returned row and carries no data.
87    #[non_exhaustive]
88    Row,
89}
90
91impl SqliteConnection {
92    /// Registers a trace callback for SQL execution monitoring.
93    ///
94    /// The callback receives the [`SqliteTraceEvent`]s selected by the
95    /// [`SqliteTraceFlags`] mask. `ROW` fires once per returned row, so prefer
96    /// `STMT`/`PROFILE` for most logging.
97    ///
98    /// Only one trace callback can be active at a time per connection.
99    /// Registering a new one replaces the previous.
100    ///
101    /// The callback must not use the database connection. It is invoked
102    /// synchronously on the thread driving the connection, so it is never
103    /// called concurrently. Panics in the callback abort the process.
104    ///
105    /// See: [`sqlite3_trace_v2`](https://sqlite.org/c3ref/trace_v2.html)
106    ///
107    /// # Example
108    ///
109    /// ```rust
110    /// # use diesel::prelude::*;
111    /// use diesel::sqlite::{SqliteConnection, SqliteTraceFlags, SqliteTraceEvent};
112    ///
113    /// # let conn = &mut SqliteConnection::establish(":memory:").unwrap();
114    /// conn.on_trace(SqliteTraceFlags::STMT | SqliteTraceFlags::PROFILE, |event| {
115    ///     match event {
116    ///         SqliteTraceEvent::Statement { sql, readonly, .. } => {
117    ///             println!("Executing ({}): {}", if readonly { "read" } else { "write" }, sql);
118    ///         }
119    ///         SqliteTraceEvent::Profile { sql, duration_ns, .. } => {
120    ///             println!("{} took {} ns", sql, duration_ns);
121    ///         }
122    ///         _ => {}
123    ///     }
124    /// });
125    ///
126    /// // Later: remove the trace callback
127    /// conn.remove_trace();
128    /// ```
129    pub fn on_trace<F>(&mut self, mask: SqliteTraceFlags, hook: F)
130    where
131        F: FnMut(SqliteTraceEvent<'_>) + Send + 'static,
132    {
133        self.raw_connection.set_trace(mask, hook);
134    }
135
136    /// Removes the trace callback.
137    ///
138    /// See [`on_trace`](Self::on_trace) for usage example.
139    pub fn remove_trace(&mut self) {
140        self.raw_connection.remove_trace();
141    }
142}
143
144// miri doesn't support ffi callbacks
145#[cfg(all(test, not(miri)))]
146mod tests {
147    use super::*;
148    use crate::connection::Connection;
149    use crate::query_dsl::RunQueryDsl;
150    use std::sync::Arc;
151    use std::sync::atomic::Ordering;
152
153    fn connection() -> SqliteConnection {
154        SqliteConnection::establish(":memory:").unwrap()
155    }
156
157    #[diesel_test_helper::test]
158    fn on_trace_reports_statement_and_profile() {
159        use std::sync::Mutex;
160
161        let conn = &mut connection();
162        crate::sql_query("CREATE TABLE t_trace (id INTEGER PRIMARY KEY)")
163            .execute(conn)
164            .unwrap();
165
166        // (sql, readonly) for Statement events, and the SQL of Profile events.
167        let stmts: Arc<Mutex<Vec<(String, bool)>>> = Arc::new(Mutex::new(Vec::new()));
168        let profiled: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));
169        let stmts2 = stmts.clone();
170        let profiled2 = profiled.clone();
171
172        conn.on_trace(
173            SqliteTraceFlags::STMT | SqliteTraceFlags::PROFILE,
174            move |event| match event {
175                SqliteTraceEvent::Statement { sql, readonly } => {
176                    stmts2.lock().unwrap().push((sql.to_owned(), readonly));
177                }
178                SqliteTraceEvent::Profile { sql, .. } => {
179                    profiled2.lock().unwrap().push(sql.to_owned());
180                }
181                _ => {}
182            },
183        );
184
185        crate::sql_query("SELECT id FROM t_trace")
186            .execute(conn)
187            .unwrap();
188        crate::sql_query("INSERT INTO t_trace (id) VALUES (1)")
189            .execute(conn)
190            .unwrap();
191
192        let stmts = stmts.lock().unwrap();
193        assert!(
194            stmts
195                .iter()
196                .any(|(sql, ro)| sql.contains("SELECT id FROM t_trace") && *ro),
197            "the SELECT should be traced and reported read-only"
198        );
199        assert!(
200            stmts
201                .iter()
202                .any(|(sql, ro)| sql.contains("INSERT INTO t_trace") && !*ro),
203            "the INSERT should be traced and reported not read-only"
204        );
205        assert!(
206            !profiled.lock().unwrap().is_empty(),
207            "at least one Profile event should have fired"
208        );
209    }
210
211    #[diesel_test_helper::test]
212    fn remove_trace_stops_events() {
213        use std::sync::atomic::AtomicUsize;
214
215        let conn = &mut connection();
216        let count: Arc<AtomicUsize> = Arc::new(AtomicUsize::new(0));
217        let count2 = count.clone();
218
219        conn.on_trace(SqliteTraceFlags::STMT, move |_event| {
220            count2.fetch_add(1, Ordering::Relaxed);
221        });
222        crate::sql_query("SELECT 1").execute(conn).unwrap();
223        let after_first = count.load(Ordering::Relaxed);
224        assert!(after_first > 0, "trace should fire while registered");
225
226        conn.remove_trace();
227        crate::sql_query("SELECT 1").execute(conn).unwrap();
228        assert_eq!(
229            count.load(Ordering::Relaxed),
230            after_first,
231            "no trace events should fire after remove_trace"
232        );
233    }
234
235    #[diesel_test_helper::test]
236    fn on_trace_ignores_unknown_mask_bits() {
237        use std::sync::Mutex;
238
239        let conn = &mut connection();
240        let seen: Arc<Mutex<Vec<String>>> = Default::default();
241        let seen2 = seen.clone();
242
243        // 0x41 keeps the STMT bit plus a bit that is not a declared event code.
244        conn.on_trace(SqliteTraceFlags::from_bits_retain(0x41), move |event| {
245            if let SqliteTraceEvent::Statement { sql, .. } = event {
246                seen2.lock().unwrap().push(sql.to_string());
247            }
248        });
249        crate::sql_query("SELECT 1").execute(conn).unwrap();
250
251        assert!(
252            seen.lock().unwrap().iter().any(|sql| sql == "SELECT 1"),
253            "the SELECT should be traced despite the unknown mask bit"
254        );
255    }
256
257    #[diesel_test_helper::test]
258    fn on_trace_with_unknown_mask_bits_keeps_v2_callback() {
259        let conn = &mut connection();
260
261        // A non-capturing closure, like the one in the `on_trace` documentation.
262        conn.on_trace(SqliteTraceFlags::from_bits_retain(0x41), |_event| {});
263        crate::sql_query("SELECT 1").execute(conn).unwrap();
264    }
265}