Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement tokio_rusqlite::Connection: From<rusqlite::Connection> #33

Merged
merged 3 commits into from
Aug 20, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 34 additions & 21 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -361,6 +361,15 @@ impl Debug for Connection {
}
}

impl From<rusqlite::Connection> for Connection {
fn from(conn: rusqlite::Connection) -> Self {
let (sender, receiver) = crossbeam_channel::unbounded::<Message>();
thread::spawn(move || event_loop(conn, receiver));

Self { sender }
}
}

async fn start<F>(open: F) -> rusqlite::Result<Connection>
where
F: FnOnce() -> rusqlite::Result<rusqlite::Connection> + Send + 'static,
Expand All @@ -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));
Expand All @@ -381,29 +390,33 @@ 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
.await
.expect(BUG_TEXT)
.map(|_| Connection { sender })
}

fn event_loop(mut conn: rusqlite::Connection, receiver: Receiver<Message>) {
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);
}
}
}
}
}
}
Loading