1use std::ffi::{c_int, c_void};
3use std::mem;
4use std::panic::catch_unwind;
5use std::ptr;
6use std::time::Duration;
7
8use crate::ffi;
9use crate::{Connection, InnerConnection, Result};
10
11impl Connection {
12 pub fn busy_timeout(&self, timeout: Duration) -> Result<()> {
27 let ms: i32 = timeout
28 .as_secs()
29 .checked_mul(1000)
30 .and_then(|t| t.checked_add(timeout.subsec_millis().into()))
31 .and_then(|t| t.try_into().ok())
32 .expect("too big");
33 self.db.borrow_mut().busy_timeout(ms)
34 }
35
36 pub fn busy_handler(&self, callback: Option<fn(i32) -> bool>) -> Result<()> {
58 unsafe extern "C" fn busy_handler_callback(p_arg: *mut c_void, count: c_int) -> c_int {
59 let handler_fn: fn(i32) -> bool = mem::transmute(p_arg);
60 c_int::from(catch_unwind(|| handler_fn(count)).unwrap_or_default())
61 }
62 let c = self.db.borrow_mut();
63 let r = match callback {
64 Some(f) => unsafe {
65 ffi::sqlite3_busy_handler(c.db(), Some(busy_handler_callback), f as *mut c_void)
66 },
67 None => unsafe { ffi::sqlite3_busy_handler(c.db(), None, ptr::null_mut()) },
68 };
69 c.decode_result(r)
70 }
71}
72
73impl InnerConnection {
74 #[inline]
75 fn busy_timeout(&mut self, timeout: c_int) -> Result<()> {
76 let r = unsafe { ffi::sqlite3_busy_timeout(self.db, timeout) };
77 self.decode_result(r)
78 }
79}
80
81#[cfg(test)]
82mod test {
83 use crate::{Connection, ErrorCode, Result, TransactionBehavior};
84 use std::sync::atomic::{AtomicBool, Ordering};
85
86 #[test]
87 fn test_default_busy() -> Result<()> {
88 let temp_dir = tempfile::tempdir().unwrap();
89 let path = temp_dir.path().join("test.db3");
90
91 let mut db1 = Connection::open(&path)?;
92 let tx1 = db1.transaction_with_behavior(TransactionBehavior::Exclusive)?;
93 let db2 = Connection::open(&path)?;
94 let r: Result<()> = db2.query_row("PRAGMA schema_version", [], |_| unreachable!());
95 assert_eq!(
96 r.unwrap_err().sqlite_error_code(),
97 Some(ErrorCode::DatabaseBusy)
98 );
99 tx1.rollback()
100 }
101
102 #[test]
103 fn test_busy_handler() -> Result<()> {
104 static CALLED: AtomicBool = AtomicBool::new(false);
105 fn busy_handler(n: i32) -> bool {
106 if n > 2 {
107 false
108 } else {
109 CALLED.swap(true, Ordering::Relaxed)
110 }
111 }
112
113 let temp_dir = tempfile::tempdir().unwrap();
114 let path = temp_dir.path().join("busy-handler.db3");
115
116 let db1 = Connection::open(&path)?;
117 db1.execute_batch("CREATE TABLE IF NOT EXISTS t(a)")?;
118 let db2 = Connection::open(&path)?;
119 db2.busy_handler(Some(busy_handler))?;
120 db1.execute_batch("BEGIN EXCLUSIVE")?;
121 let err = db2.prepare("SELECT * FROM t").unwrap_err();
122 assert_eq!(err.sqlite_error_code(), Some(ErrorCode::DatabaseBusy));
123 assert!(CALLED.load(Ordering::Relaxed));
124 db1.busy_handler(None)?;
125 Ok(())
126 }
127}