//! Tracing and profiling functions. Error and warning log.
use std::borrow::Cow; use std::ffi::{c_char, c_int, c_uint, c_void, CStr, CString}; use std::marker::PhantomData; use std::mem; use std::panic::catch_unwind; use std::ptr; use std::time::Duration;
/// Set up the process-wide SQLite error logging callback. /// /// # 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. /// /// cf [The Error And Warning Log](http://sqlite.org/errlog.html). #[cfg(not(feature = "loadable_extension"))] pubunsafefn 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 s = unsafe { CStr::from_ptr(msg).to_string_lossy() }; let callback: fn(c_int, &str) = unsafe { mem::transmute(p_arg) };
drop(catch_unwind(|| callback(err, &s)));
}
let rc = iflet Some(f) = callback {
ffi::sqlite3_config(
ffi::SQLITE_CONFIG_LOG,
log_callback asextern"C"fn(_, _, _),
f as *mut c_void,
)
} else { let nullptr: *mut c_void = ptr::null_mut();
ffi::sqlite3_config(ffi::SQLITE_CONFIG_LOG, nullptr, nullptr)
};
/// Write a message into the error log established by /// `config_log`. #[inline] pubfn log(err_code: c_int, msg: &str) { let msg = CString::new(msg).expect("SQLite log messages cannot contain embedded zeroes"); unsafe {
ffi::sqlite3_log(err_code, b"%s\0"as *const _ as *const c_char, msg.as_ptr());
}
}
bitflags::bitflags! { /// Trace event codes #[derive(Clone, Copy, Debug, Eq, PartialEq)] #[non_exhaustive] #[repr(C)] pubstruct TraceEventCodes: c_uint { /// when a prepared statement first begins running and possibly at other times during the execution /// of the prepared statement, such as at the start of each trigger subprogram const SQLITE_TRACE_STMT = ffi::SQLITE_TRACE_STMT; /// when the statement finishes const SQLITE_TRACE_PROFILE = ffi::SQLITE_TRACE_PROFILE; /// whenever a prepared statement generates a single row of result const SQLITE_TRACE_ROW = ffi::SQLITE_TRACE_ROW; /// when a database connection closes const SQLITE_TRACE_CLOSE = ffi::SQLITE_TRACE_CLOSE;
}
}
/// Trace event #[non_exhaustive] pubenum TraceEvent<'s> { /// when a prepared statement first begins running and possibly at other times during the execution /// of the prepared statement, such as at the start of each trigger subprogram
Stmt(StmtRef<'s>, &'s str), /// when the statement finishes
Profile(StmtRef<'s>, Duration), /// whenever a prepared statement generates a single row of result
Row(StmtRef<'s>), /// when a database connection closes
Close(ConnRef<'s>),
}
impl ConnRef<'_> { /// Test for auto-commit mode. pubfn is_autocommit(&self) -> bool { unsafe { crate::inner_connection::get_autocommit(self.ptr) }
} /// the path to the database file, if one exists and is known. pubfn db_filename(&self) -> Option<&str> { unsafe { crate::inner_connection::db_filename(self.phantom, self.ptr, MAIN_DB) }
}
}
impl Connection { /// Register or clear a callback function that can be /// used for tracing the execution of SQL statements. /// /// 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. #[deprecated(since = "0.33.0", note = "use trace_v2 instead")] pubfn trace(&mutself, trace_fn: Option<fn(&str)>) { unsafeextern"C"fn trace_callback(p_arg: *mut c_void, z_sql: *const c_char) { let trace_fn: fn(&str) = mem::transmute(p_arg); let s = CStr::from_ptr(z_sql).to_string_lossy();
drop(catch_unwind(|| trace_fn(&s)));
}
let c = self.db.borrow_mut(); match trace_fn {
Some(f) => unsafe {
ffi::sqlite3_trace(c.db(), Some(trace_callback), f as *mut c_void);
},
None => unsafe {
ffi::sqlite3_trace(c.db(), None, ptr::null_mut());
},
}
}
/// Register or clear a callback function that can be /// used for profiling the execution of SQL statements. /// /// There can only be a single profiler defined for each database /// connection. Setting a new profiler clears the old one. #[deprecated(since = "0.33.0", note = "use trace_v2 instead")] pubfn profile(&mutself, profile_fn: Option<fn(&str, Duration)>) { unsafeextern"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 s = CStr::from_ptr(z_sql).to_string_lossy();
let duration = Duration::from_nanos(nanoseconds);
drop(catch_unwind(|| profile_fn(&s, duration)));
}
let c = self.db.borrow_mut(); match profile_fn {
Some(f) => unsafe {
ffi::sqlite3_profile(c.db(), Some(profile_callback), f as *mut c_void)
},
None => unsafe { ffi::sqlite3_profile(c.db(), None, ptr::null_mut()) },
};
}
/// Register or clear a trace callback function pubfn trace_v2(&self, mask: TraceEventCodes, trace_fn: Option<fn(TraceEvent<'_>)>) { unsafeextern"C"fn trace_callback(
evt: c_uint,
ctx: *mut c_void,
p: *mut c_void,
x: *mut c_void,
) -> c_int { let trace_fn: fn(TraceEvent<'_>) = mem::transmute(ctx);
drop(catch_unwind(|| match evt {
ffi::SQLITE_TRACE_STMT => { let str = CStr::from_ptr(x as *const c_char).to_string_lossy();
trace_fn(TraceEvent::Stmt(
StmtRef::new(p as *mut ffi::sqlite3_stmt),
&str,
))
}
ffi::SQLITE_TRACE_PROFILE => { let ns = *(x as *const i64);
trace_fn(TraceEvent::Profile(
StmtRef::new(p as *mut ffi::sqlite3_stmt),
Duration::from_nanos(u64::try_from(ns).unwrap_or_default()),
))
}
ffi::SQLITE_TRACE_ROW => {
trace_fn(TraceEvent::Row(StmtRef::new(p as *mut ffi::sqlite3_stmt)))
}
ffi::SQLITE_TRACE_CLOSE => trace_fn(TraceEvent::Close(ConnRef {
ptr: p as *mut ffi::sqlite3,
phantom: PhantomData,
})),
_ => {}
})); // The integer return value from the callback is currently ignored, though this may change in future releases. // Callback implementations should return zero to ensure future compatibility.
ffi::SQLITE_OK
} let c = self.db.borrow_mut(); iflet Some(f) = trace_fn { unsafe {
ffi::sqlite3_trace_v2(c.db(), mask.bits(), Some(trace_callback), f as *mut c_void);
}
} else { unsafe {
ffi::sqlite3_trace_v2(c.db(), 0, None, ptr::null_mut());
}
}
}
}
#[cfg(test)] mod test { use std::sync::{LazyLock, Mutex}; use std::time::Duration;
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.