diff --git a/src/lib.rs b/src/lib.rs index fbf89ee..2c52100 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -98,7 +98,7 @@ #[cfg(test)] mod tests; -use crossbeam_channel::Sender; +use crossbeam_channel::{Receiver, Sender}; use std::{ fmt::{self, Debug, Display}, path::Path, @@ -361,6 +361,15 @@ impl Debug for Connection { } } +impl From for Connection { + fn from(conn: rusqlite::Connection) -> Self { + let (sender, receiver) = crossbeam_channel::unbounded::(); + thread::spawn(move || event_loop(conn, receiver)); + + Self { sender } + } +} + async fn start(open: F) -> rusqlite::Result where F: FnOnce() -> rusqlite::Result + Send + 'static, @@ -369,7 +378,7 @@ where let (result_sender, result_receiver) = oneshot::channel(); thread::spawn(move || { - let mut conn = match open() { + let conn = match open() { Ok(c) => c, Err(e) => { let _ = result_sender.send(Err(e)); @@ -381,25 +390,7 @@ where return; } - while let Ok(message) = receiver.recv() { - match message { - Message::Execute(f) => f(&mut conn), - Message::Close(s) => { - let result = conn.close(); - - match result { - Ok(v) => { - s.send(Ok(v)).expect(BUG_TEXT); - break; - } - Err((c, e)) => { - conn = c; - s.send(Err(e)).expect(BUG_TEXT); - } - } - } - } - } + event_loop(conn, receiver); }); result_receiver @@ -407,3 +398,25 @@ where .expect(BUG_TEXT) .map(|_| Connection { sender }) } + +fn event_loop(mut conn: rusqlite::Connection, receiver: Receiver) { + while let Ok(message) = receiver.recv() { + match message { + Message::Execute(f) => f(&mut conn), + Message::Close(s) => { + let result = conn.close(); + + match result { + Ok(v) => { + s.send(Ok(v)).expect(BUG_TEXT); + break; + } + Err((c, e)) => { + conn = c; + s.send(Err(e)).expect(BUG_TEXT); + } + } + } + } + } +}