rusqlite/src/trace.rs

185 lines
6.2 KiB
Rust
Raw Normal View History

2021-06-13 15:17:35 +08:00
//! Tracing and profiling functions. Error and warning log.
use std::ffi::{CStr, CString};
use std::mem;
2018-08-11 18:48:21 +08:00
use std::os::raw::{c_char, c_int, c_void};
use std::panic::catch_unwind;
2015-08-01 23:21:41 +08:00
use std::ptr;
use std::time::Duration;
2015-08-01 23:21:41 +08:00
use super::ffi;
2023-07-09 16:39:21 +08:00
use crate::Connection;
2015-08-01 23:21:41 +08:00
2021-06-13 15:17:35 +08:00
/// Set up the process-wide SQLite error logging callback.
2019-11-03 18:19:07 +08:00
///
/// # Safety
///
/// This function is marked unsafe for two reasons:
///
/// * The function is not threadsafe. No other SQLite calls may be made while
/// `config_log` is running, and multiple threads may not call `config_log`
/// simultaneously.
/// * The provided `callback` itself function has two requirements:
/// * It must not invoke any SQLite calls.
/// * It must be threadsafe if SQLite is used in a multithreaded way.
2015-08-01 23:21:41 +08:00
///
/// cf [The Error And Warning Log](http://sqlite.org/errlog.html).
2023-07-09 16:39:21 +08:00
#[cfg(not(feature = "loadable_extension"))]
pub unsafe fn config_log(callback: Option<fn(c_int, &str)>) -> crate::Result<()> {
extern "C" fn log_callback(p_arg: *mut c_void, err: c_int, msg: *const c_char) {
let c_slice = unsafe { CStr::from_ptr(msg).to_bytes() };
let callback: fn(c_int, &str) = unsafe { mem::transmute(p_arg) };
let s = String::from_utf8_lossy(c_slice);
2022-01-06 02:26:06 +08:00
drop(catch_unwind(|| callback(err, &s)));
}
2022-01-06 02:59:54 +08:00
let rc = if let Some(f) = callback {
ffi::sqlite3_config(
2020-08-18 02:07:56 +08:00
ffi::SQLITE_CONFIG_LOG,
log_callback as extern "C" fn(_, _, _),
f as *mut c_void,
2022-01-06 02:59:54 +08:00
)
} else {
let nullptr: *mut c_void = ptr::null_mut();
ffi::sqlite3_config(ffi::SQLITE_CONFIG_LOG, nullptr, nullptr)
2015-08-01 23:21:41 +08:00
};
if rc == ffi::SQLITE_OK {
Ok(())
} else {
2023-07-09 16:39:21 +08:00
Err(crate::error::error_from_sqlite_code(rc, None))
2015-08-01 23:21:41 +08:00
}
}
2021-06-13 15:17:35 +08:00
/// Write a message into the error log established by
/// `config_log`.
#[inline]
2015-08-01 23:21:41 +08:00
pub fn log(err_code: c_int, msg: &str) {
let msg = CString::new(msg).expect("SQLite log messages cannot contain embedded zeroes");
2015-08-01 23:21:41 +08:00
unsafe {
ffi::sqlite3_log(err_code, b"%s\0" as *const _ as *const c_char, msg.as_ptr());
2015-08-01 23:21:41 +08:00
}
}
impl Connection {
2021-06-13 15:17:35 +08:00
/// Register or clear a callback function that can be
/// used for tracing the execution of SQL statements.
2015-08-08 15:57:07 +08:00
///
2018-08-17 00:29:46 +08:00
/// Prepared statement placeholders are replaced/logged with their assigned
/// values. There can only be a single tracer defined for each database
/// connection. Setting a new tracer clears the old one.
pub fn trace(&mut self, trace_fn: Option<fn(&str)>) {
unsafe extern "C" fn trace_callback(p_arg: *mut c_void, z_sql: *const c_char) {
let trace_fn: fn(&str) = mem::transmute(p_arg);
let c_slice = CStr::from_ptr(z_sql).to_bytes();
let s = String::from_utf8_lossy(c_slice);
2022-01-06 02:26:06 +08:00
drop(catch_unwind(|| trace_fn(&s)));
}
2015-08-01 23:21:41 +08:00
let c = self.db.borrow_mut();
match trace_fn {
2015-12-11 05:48:09 +08:00
Some(f) => unsafe {
2020-08-18 02:07:56 +08:00
ffi::sqlite3_trace(c.db(), Some(trace_callback), f as *mut c_void);
2015-12-11 05:48:09 +08:00
},
None => unsafe {
ffi::sqlite3_trace(c.db(), None, ptr::null_mut());
},
}
2015-08-01 23:21:41 +08:00
}
2021-06-13 15:17:35 +08:00
/// Register or clear a callback function that can be
/// used for profiling the execution of SQL statements.
2015-08-08 15:57:07 +08:00
///
2018-08-17 00:29:46 +08:00
/// There can only be a single profiler defined for each database
/// connection. Setting a new profiler clears the old one.
pub fn profile(&mut self, profile_fn: Option<fn(&str, Duration)>) {
2018-08-11 18:48:21 +08:00
unsafe extern "C" fn profile_callback(
p_arg: *mut c_void,
z_sql: *const c_char,
nanoseconds: u64,
) {
let profile_fn: fn(&str, Duration) = mem::transmute(p_arg);
let c_slice = CStr::from_ptr(z_sql).to_bytes();
let s = String::from_utf8_lossy(c_slice);
const NANOS_PER_SEC: u64 = 1_000_000_000;
2018-08-11 18:48:21 +08:00
let duration = Duration::new(
nanoseconds / NANOS_PER_SEC,
(nanoseconds % NANOS_PER_SEC) as u32,
);
2022-01-06 02:26:06 +08:00
drop(catch_unwind(|| profile_fn(&s, duration)));
}
2015-08-01 23:21:41 +08:00
let c = self.db.borrow_mut();
match profile_fn {
2015-12-11 05:48:09 +08:00
Some(f) => unsafe {
2020-08-18 02:07:56 +08:00
ffi::sqlite3_profile(c.db(), Some(profile_callback), f as *mut c_void)
2015-12-11 05:48:09 +08:00
},
None => unsafe { ffi::sqlite3_profile(c.db(), None, ptr::null_mut()) },
};
2015-08-01 23:21:41 +08:00
}
// TODO sqlite3_trace_v2 (https://sqlite.org/c3ref/trace_v2.html) // 3.14.0, #977
2015-08-01 23:21:41 +08:00
}
#[cfg(test)]
mod test {
2019-08-10 02:03:46 +08:00
use lazy_static::lazy_static;
use std::sync::Mutex;
use std::time::Duration;
2015-08-01 23:21:41 +08:00
2020-11-06 05:14:00 +08:00
use crate::{Connection, Result};
2015-08-01 23:21:41 +08:00
#[test]
2020-11-06 05:14:00 +08:00
fn test_trace() -> Result<()> {
lazy_static! {
static ref TRACED_STMTS: Mutex<Vec<String>> = Mutex::new(Vec::new());
}
fn tracer(s: &str) {
let mut traced_stmts = TRACED_STMTS.lock().unwrap();
traced_stmts.push(s.to_owned());
}
2020-11-06 05:14:00 +08:00
let mut db = Connection::open_in_memory()?;
db.trace(Some(tracer));
{
let _ = db.query_row("SELECT ?1", [1i32], |_| Ok(()));
let _ = db.query_row("SELECT ?1", ["hello"], |_| Ok(()));
}
db.trace(None);
{
let _ = db.query_row("SELECT ?1", [2i32], |_| Ok(()));
let _ = db.query_row("SELECT ?1", ["goodbye"], |_| Ok(()));
}
let traced_stmts = TRACED_STMTS.lock().unwrap();
assert_eq!(traced_stmts.len(), 2);
assert_eq!(traced_stmts[0], "SELECT 1");
assert_eq!(traced_stmts[1], "SELECT 'hello'");
2020-11-06 05:14:00 +08:00
Ok(())
}
2015-08-01 23:21:41 +08:00
#[test]
2020-11-06 05:14:00 +08:00
fn test_profile() -> Result<()> {
lazy_static! {
static ref PROFILED: Mutex<Vec<(String, Duration)>> = Mutex::new(Vec::new());
}
fn profiler(s: &str, d: Duration) {
let mut profiled = PROFILED.lock().unwrap();
profiled.push((s.to_owned(), d));
}
2020-11-06 05:14:00 +08:00
let mut db = Connection::open_in_memory()?;
db.profile(Some(profiler));
2020-11-06 05:14:00 +08:00
db.execute_batch("PRAGMA application_id = 1")?;
db.profile(None);
2020-11-06 05:14:00 +08:00
db.execute_batch("PRAGMA application_id = 2")?;
let profiled = PROFILED.lock().unwrap();
assert_eq!(profiled.len(), 1);
assert_eq!(profiled[0].0, "PRAGMA application_id = 1");
2020-11-06 05:14:00 +08:00
Ok(())
2015-08-01 23:21:41 +08:00
}
2015-11-11 21:29:40 +08:00
}