Skip to main content

boson_backend_sqlite/
lib.rs

1//! `SQLite` [`QueueBackend`](boson_core::QueueBackend) for Boson.
2//!
3//! Choose at worker boot (**Integrating the server**). Enable via the `boson` crate `sqlite` feature.
4//!
5//! ## Entry points
6//!
7//! - [`SqliteQueueBackend::new`] / [`SqliteQueueBackend::connect`] — open a database
8//! - [`install_default_sqlite_backend`] — register on the global [`QueueRouter`](boson_core::QueueRouter)
9
10mod bootstrap;
11
12use std::path::Path;
13
14use boson_backend_sql_common::SqlQueueBackend;
15use boson_core::Result;
16use sqlx::SqlitePool;
17
18pub use bootstrap::install_default_sqlite_backend;
19
20/// SQLite-backed queue backend.
21pub struct SqliteQueueBackend {
22    inner: SqlQueueBackend,
23}
24
25impl SqliteQueueBackend {
26    /// Open a `SQLite` database at `path` (creates the file if missing).
27    ///
28    /// # Errors
29    ///
30    /// Returns an error when the database cannot be opened or schema bootstrap fails.
31    pub async fn new(path: impl AsRef<Path>) -> Result<Self> {
32        let url = format!("sqlite://{}?mode=rwc", path.as_ref().display());
33        Self::connect(&url).await
34    }
35
36    /// Connect using a `SQLite` connection URL.
37    ///
38    /// # Errors
39    ///
40    /// Returns an error when the pool cannot connect or schema bootstrap fails.
41    pub async fn connect(url: &str) -> Result<Self> {
42        let inner = SqlQueueBackend::connect_sqlite(url).await?;
43        Ok(Self { inner })
44    }
45
46    /// Wrap an existing pool (schema bootstrap runs).
47    ///
48    /// # Errors
49    ///
50    /// Returns an error when schema bootstrap fails.
51    pub async fn from_pool(pool: SqlitePool) -> Result<Self> {
52        let inner = SqlQueueBackend::from_sqlite_pool(pool).await?;
53        Ok(Self { inner })
54    }
55
56    /// Underlying connection pool.
57    ///
58    /// # Panics
59    ///
60    /// Panics if the inner pool is not `SQLite` (internal invariant violation).
61    #[must_use]
62    pub fn pool(&self) -> &SqlitePool {
63        match self.inner.pool() {
64            boson_backend_sql_common::SqlPool::Sqlite(pool) => pool,
65            boson_backend_sql_common::SqlPool::Postgres(_) => {
66                panic!("sqlite backend has non-sqlite pool")
67            }
68        }
69    }
70}
71
72impl std::fmt::Debug for SqliteQueueBackend {
73    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
74        f.debug_struct("SqliteQueueBackend").finish_non_exhaustive()
75    }
76}
77
78boson_backend_sql_common::delegate_queue_backend!(SqliteQueueBackend, inner);