mirror of
https://github.com/TheFunny/TelegramTwitterMediaBot.git
synced 2026-09-28 00:02:12 +00:00
refactor: share sqlite open/with_conn helpers in db.rs
Converge the duplicated open_db (open + busy_timeout) and the spawn_blocking + expect ceremony that every table access repeated into one db.rs module. ChatStore no longer creates the tasks table (schema ownership: queue.rs owns tasks, state.rs chat_state, link_cache.rs link_cache). No schema or behavior change - all CREATE TABLE statements are byte-identical, IF NOT EXISTS stays idempotent, so existing data/task_queue.db files need no migration.
This commit is contained in:
@@ -0,0 +1,37 @@
|
||||
//! Shared SQLite plumbing for the three tables in `data/task_queue.db`
|
||||
//! (`tasks` in queue.rs, `chat_state` in state.rs, `link_cache` in
|
||||
//! link_cache.rs).
|
||||
//!
|
||||
//! Every operation opens its own short-lived connection with a busy timeout:
|
||||
//! handler tasks enqueue while workers lease/update rows concurrently, and
|
||||
//! without the timeout a concurrent write fails immediately with SQLITE_BUSY
|
||||
//! and the operation is lost. All I/O runs inside `spawn_blocking` via
|
||||
//! [`with_conn`] — rusqlite connections are not Send-friendly to hold across
|
||||
//! an await point, and blocking the async executor stalls every handler.
|
||||
|
||||
use rusqlite::Connection;
|
||||
use std::time::Duration;
|
||||
|
||||
/// Opens the shared DB with a busy timeout.
|
||||
pub fn open_db(path: &str) -> rusqlite::Result<Connection> {
|
||||
let conn = Connection::open(path)?;
|
||||
conn.busy_timeout(Duration::from_secs(5))?;
|
||||
Ok(conn)
|
||||
}
|
||||
|
||||
/// Runs `f` against a fresh connection on a blocking thread, returning the
|
||||
/// closure's result. Owns the `spawn_blocking` + `expect` ceremony shared by
|
||||
/// every table access; the caller maps errors to its own log line.
|
||||
pub async fn with_conn<T, F>(path: &str, f: F) -> rusqlite::Result<T>
|
||||
where
|
||||
T: Send + 'static,
|
||||
F: FnOnce(&mut Connection) -> rusqlite::Result<T> + Send + 'static,
|
||||
{
|
||||
let path = path.to_string();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let mut conn = open_db(&path)?;
|
||||
f(&mut conn)
|
||||
})
|
||||
.await
|
||||
.expect("db worker panicked")
|
||||
}
|
||||
Reference in New Issue
Block a user