Debian Codegraph @

third_party/rust/rusqlite/src/trace.rs

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