Skip to main content

rusqlite/
trace.rs

1//! Tracing and profiling functions. Error and warning log.
2
3use std::borrow::Cow;
4use std::ffi::{CStr, CString, c_char, c_int, c_uint, c_void};
5use std::marker::PhantomData;
6#[cfg(not(feature = "loadable_extension"))]
7use std::mem;
8use std::panic::catch_unwind;
9#[cfg(not(feature = "loadable_extension"))]
10use std::ptr;
11use std::time::Duration;
12
13use super::ffi;
14use crate::{Connection, MAIN_DB, Result, StatementStatus};
15
16/// Set up the process-wide SQLite error logging callback.
17///
18/// # Safety
19///
20/// This function is marked unsafe for two reasons:
21///
22/// * The function is not threadsafe. No other SQLite calls may be made while
23///   `config_log` is running, and multiple threads may not call `config_log`
24///   simultaneously.
25/// * The provided `callback` itself function has two requirements:
26///     * It must not invoke any SQLite calls.
27///     * It must be threadsafe if SQLite is used in a multithreaded way.
28///
29/// cf [The Error And Warning Log](http://sqlite.org/errlog.html).
30#[cfg(not(feature = "loadable_extension"))]
31pub unsafe fn config_log(callback: Option<fn(c_int, &str)>) -> Result<()> {
32    extern "C" fn log_callback(p_arg: *mut c_void, err: c_int, msg: *const c_char) {
33        let s = unsafe { CStr::from_ptr(msg).to_string_lossy() };
34        let callback: fn(c_int, &str) = unsafe { mem::transmute(p_arg) };
35
36        drop(catch_unwind(|| callback(err, &s)));
37    }
38    let rc = unsafe {
39        if let Some(f) = callback {
40            ffi::sqlite3_config(
41                ffi::SQLITE_CONFIG_LOG,
42                log_callback as extern "C" fn(_, _, _),
43                f as *mut c_void,
44            )
45        } else {
46            let nullptr: *mut c_void = ptr::null_mut();
47            ffi::sqlite3_config(ffi::SQLITE_CONFIG_LOG, nullptr, nullptr)
48        }
49    };
50    if rc == ffi::SQLITE_OK {
51        Ok(())
52    } else {
53        Err(crate::error::error_from_sqlite_code(rc, None))
54    }
55}
56
57/// Write a message into the error log established by
58/// `config_log`.
59#[inline]
60pub fn log(err_code: c_int, msg: &str) {
61    let msg = CString::new(msg).expect("SQLite log messages cannot contain embedded zeroes");
62    unsafe {
63        ffi::sqlite3_log(err_code, c"%s".as_ptr(), msg.as_ptr());
64    }
65}
66
67bitflags::bitflags! {
68    /// Trace event codes
69    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
70    #[non_exhaustive]
71    #[repr(C)]
72    pub struct TraceEventCodes: c_uint {
73        /// when a prepared statement first begins running and possibly at other times during the execution
74        /// of the prepared statement, such as at the start of each trigger subprogram
75        const SQLITE_TRACE_STMT = ffi::SQLITE_TRACE_STMT;
76        /// when the statement finishes
77        const SQLITE_TRACE_PROFILE = ffi::SQLITE_TRACE_PROFILE;
78        /// whenever a prepared statement generates a single row of result
79        const SQLITE_TRACE_ROW = ffi::SQLITE_TRACE_ROW;
80        /// when a database connection closes
81        const SQLITE_TRACE_CLOSE = ffi::SQLITE_TRACE_CLOSE;
82    }
83}
84
85/// Trace event
86#[non_exhaustive]
87pub enum TraceEvent<'s> {
88    /// when a prepared statement first begins running and possibly at other times during the execution
89    /// of the prepared statement, such as at the start of each trigger subprogram
90    Stmt(StmtRef<'s>, &'s str),
91    /// when the statement finishes
92    Profile(StmtRef<'s>, Duration),
93    /// whenever a prepared statement generates a single row of result
94    Row(StmtRef<'s>),
95    /// when a database connection closes
96    Close(ConnRef<'s>),
97}
98
99/// Statement reference
100pub struct StmtRef<'s> {
101    ptr: *mut ffi::sqlite3_stmt,
102    phantom: PhantomData<&'s ()>,
103}
104
105impl StmtRef<'_> {
106    fn new(ptr: *mut ffi::sqlite3_stmt) -> Self {
107        StmtRef {
108            ptr,
109            phantom: PhantomData,
110        }
111    }
112
113    /// SQL text
114    #[must_use]
115    pub fn sql(&self) -> Cow<'_, str> {
116        let sql = unsafe { ffi::sqlite3_sql(self.ptr) };
117
118        if sql.is_null() {
119            return Cow::default();
120        }
121
122        // Safety: sql is a valid pointer to a cstr returned by sqlite3
123        unsafe { CStr::from_ptr(sql).to_string_lossy() }
124    }
125
126    /// Expanded SQL text
127    #[must_use]
128    pub fn expanded_sql(&self) -> Option<String> {
129        unsafe {
130            crate::raw_statement::expanded_sql(self.ptr).map(|s| s.to_string_lossy().to_string())
131        }
132    }
133
134    /// Get the value for one of the status counters for this statement.
135    #[must_use]
136    pub fn get_status(&self, status: StatementStatus) -> i32 {
137        unsafe { crate::raw_statement::stmt_status(self.ptr, status, false) }
138    }
139}
140
141/// Connection reference
142pub struct ConnRef<'s> {
143    ptr: *mut ffi::sqlite3,
144    phantom: PhantomData<&'s ()>,
145}
146
147impl ConnRef<'_> {
148    /// Test for auto-commit mode.
149    #[must_use]
150    pub fn is_autocommit(&self) -> bool {
151        unsafe { crate::inner_connection::get_autocommit(self.ptr) }
152    }
153
154    /// the path to the database file, if one exists and is known.
155    #[must_use]
156    pub fn db_filename(&self) -> Option<&str> {
157        unsafe { crate::inner_connection::db_filename(self.phantom, self.ptr, MAIN_DB) }
158    }
159}
160
161impl Connection {
162    /// Register or clear a trace callback function
163    pub fn trace_v2<F>(&mut self, mask: TraceEventCodes, trace_fn: Option<F>) -> Result<()>
164    where
165        F: FnMut(TraceEvent<'_>) + Send + 'static,
166    {
167        unsafe extern "C" fn trace_callback<F>(
168            evt: c_uint,
169            ctx: *mut c_void,
170            p: *mut c_void,
171            x: *mut c_void,
172        ) -> c_int
173        where
174            F: FnMut(TraceEvent<'_>),
175        {
176            unsafe {
177                drop(catch_unwind(|| {
178                    let trace_fn: *mut F = ctx.cast::<F>();
179                    match evt {
180                        ffi::SQLITE_TRACE_STMT => {
181                            let str = CStr::from_ptr(x as *const c_char).to_string_lossy();
182                            (*trace_fn)(TraceEvent::Stmt(
183                                StmtRef::new(p.cast::<ffi::sqlite3_stmt>()),
184                                &str,
185                            ));
186                        }
187                        ffi::SQLITE_TRACE_PROFILE => {
188                            let ns = *(x as *const i64);
189                            (*trace_fn)(TraceEvent::Profile(
190                                StmtRef::new(p.cast::<ffi::sqlite3_stmt>()),
191                                Duration::from_nanos(u64::try_from(ns).unwrap_or_default()),
192                            ));
193                        }
194                        ffi::SQLITE_TRACE_ROW => {
195                            (*trace_fn)(TraceEvent::Row(StmtRef::new(
196                                p.cast::<ffi::sqlite3_stmt>(),
197                            )));
198                        }
199                        ffi::SQLITE_TRACE_CLOSE => (*trace_fn)(TraceEvent::Close(ConnRef {
200                            ptr: p.cast::<ffi::sqlite3>(),
201                            phantom: PhantomData,
202                        })),
203                        _ => {}
204                    }
205                }));
206                // The integer return value from the callback is currently ignored, though this may change in future releases.
207                // Callback implementations should return zero to ensure future compatibility.
208                ffi::SQLITE_OK
209            }
210        }
211        let mut c = self.db.borrow_mut();
212        let x = trace_fn.as_ref().map(|_| trace_callback::<F> as _);
213        c.set_clientdata(c"sqlite3_trace_v2", trace_fn, |db, bh| unsafe {
214            ffi::sqlite3_trace_v2(db, mask.bits(), x, bh);
215            ffi::SQLITE_OK
216        })?;
217        Ok(())
218    }
219}
220
221#[cfg(all(test, not(miri)))]
222mod test {
223    use std::cell::RefCell;
224    #[cfg(all(target_family = "wasm", target_os = "unknown"))]
225    use wasm_bindgen_test::wasm_bindgen_test as test;
226
227    use std::time::Duration;
228
229    use super::{TraceEvent, TraceEventCodes};
230    use crate::{Connection, Result};
231
232    #[test]
233    pub fn trace_v2() -> Result<()> {
234        use std::borrow::Borrow as _;
235        use std::cmp::Ordering;
236
237        let mut db = Connection::open_in_memory()?;
238        db.trace_v2(
239            TraceEventCodes::all(),
240            Some(|e: TraceEvent<'_>| match e {
241                TraceEvent::Stmt(s, sql) => {
242                    assert_eq!(s.sql(), sql);
243                }
244                TraceEvent::Profile(s, d) => {
245                    assert_eq!(s.get_status(crate::StatementStatus::Sort), 0);
246                    #[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
247                    assert_eq!(d.cmp(&Duration::ZERO), Ordering::Greater);
248                    // Timers on the web are not very accurate
249                    #[cfg(all(target_family = "wasm", target_os = "unknown"))]
250                    std::assert_matches!(
251                        d.cmp(&Duration::ZERO),
252                        Ordering::Equal | Ordering::Greater
253                    );
254                }
255                TraceEvent::Row(s) => {
256                    assert_eq!(s.expanded_sql().as_deref(), Some(s.sql().borrow()));
257                }
258                TraceEvent::Close(db) => {
259                    assert!(db.is_autocommit());
260                    // https://www.sqlite.org/c3ref/db_filename.html
261                    // if database N is a temporary or in-memory database,
262                    // then this function will return either a NULL pointer or an empty string.
263                    assert!(db.db_filename().is_none_or(|s| s.is_empty()));
264                }
265            }),
266        )?;
267
268        db.one_column::<u32, _>("PRAGMA user_version", [])?;
269        drop(db);
270
271        let mut db = Connection::open_in_memory()?;
272        db.trace_v2(TraceEventCodes::empty(), None::<fn(TraceEvent<'_>)>)
273    }
274
275    #[test]
276    #[cfg(feature = "blob")]
277    pub fn null_sql() -> Result<()> {
278        let mut db = Connection::open_in_memory()?;
279        let sql = "CREATE TABLE test (content BLOB);
280                   INSERT INTO test VALUES (ZEROBLOB(10));";
281        db.execute_batch(sql)?;
282        let rowid = db.last_insert_rowid();
283
284        db.trace_v2(
285            TraceEventCodes::SQLITE_TRACE_ROW,
286            Some(|e: TraceEvent<'_>| {
287                if let TraceEvent::Row(s) = e {
288                    assert_eq!(s.sql(), "");
289                }
290            }),
291        )?;
292        db.blob_open(crate::MAIN_DB, c"test", c"content", rowid, true)?;
293
294        Ok(())
295    }
296
297    #[test]
298    #[cfg_attr(all(target_family = "wasm", target_os = "unknown"), ignore)]
299    pub fn already_borrowed() {
300        thread_local! {
301            static CONN: RefCell<Option<Connection>> = const { RefCell::new(None) };
302        }
303        CONN.with_borrow_mut(|c| c.replace(Connection::open_in_memory().unwrap()));
304        let budget: Vec<u8> = vec![0];
305        CONN.with_borrow_mut(|c| {
306            c.as_mut()
307                .unwrap()
308                .trace_v2(
309                    TraceEventCodes::SQLITE_TRACE_STMT,
310                    Some(move |e: TraceEvent<'_>| {
311                        if let TraceEvent::Stmt(_, sql) = e {
312                            println!("{}", sql);
313                        }
314                        CONN.with_borrow_mut(|c| {
315                            c.as_mut()
316                                .unwrap()
317                                .trace_v2(
318                                    TraceEventCodes::SQLITE_TRACE_STMT,
319                                    None::<fn(TraceEvent)>,
320                                )
321                                .unwrap();
322                        });
323                        println!("{}", budget[0]);
324                    }),
325                )
326                .unwrap();
327            c.as_ref()
328                .unwrap()
329                .query_one("SELECT 1;", [], |r| r.get::<_, bool>(0))
330                .unwrap();
331        });
332    }
333}