I am migrating from rusqlite
where I was using get_interrupt_handle
to abort a query immediately from another thread (when the user changed the filter parameters).
Here's an example of my current code. The best I can do is add an interrupt check before every await
but that doesn't help if the initial query is taking ages to return the first result.
struct Query {
title: String,
}
fn start_async(requests: crossbeam::channel::Receiver<Query>) {
thread::spawn(move || {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
runtime.block_on(run_db_thread(requests));
});
}
async fn run_db_thread(requests: crossbeam::channel::Sender<Query>) {
let connection = SqliteConnection::connect("test.sqlite").await?;
loop {
if let Ok(query) = requests.recv() {
do_query(&connection, &query).await?;
}
}
}
async fn do_query(connection: &SqliteConnection, query: &Query) -> Result<(), Box<dyn Error>> {
let mut stream = sqlx::query("SELECT title, authors, series FROM Books where title like ?")
.bind(&format!("%{}%", query.title))
.fetch(&connection);
while let Some(row) = stream.next().await {
let (title, authors, series) = row?;
println!("{} {} {}", title, authors, series);
}
}
Is there a way to interrupt a running sqlx execution when a new Query
arrives in the channel? I'd be happy to send a signal separately if necessary.