axum_sqlite/
lib.rs

1//! Provides Sqlite database for `axum`.
2//!
3//! ```rust
4//! use axum::{Extension, response::Html, routing::get, Router};
5//! use std::net::SocketAddr;
6//! use axum_sqlite::*;
7//! 
8//! #[tokio::main]
9//! async fn main() {
10//!     let app = Router::new()
11//!         .route("/", get(index))
12//!         .layer(Database::new(":memory:").unwrap());
13//!     axum::Server::bind(&SocketAddr::from(([127, 0, 0, 1], 3000)))
14//!         .serve(app.into_make_service())
15//!         .await
16//!         .unwrap();
17//! }
18//! 
19//! async fn index(Extension(database): Extension<Database>) -> Html<&'static str> {
20//!     let connection = database.connection().unwrap(); // Do stuff with connection
21//!     Html("Hello, sqlite!")
22//! }
23//! ```
24
25use axum::Extension;
26use r2d2::{Pool, Error, PooledConnection};
27use r2d2_sqlite::SqliteConnectionManager;
28
29#[derive(Clone)]
30pub struct Database {
31    pool: Pool<SqliteConnectionManager>,
32}
33
34impl Database {
35    pub fn new(path: &str) -> Result<Extension<Self>, Error> {
36        let manager = SqliteConnectionManager::file(path);
37        let pool = Pool::new(manager)?;
38        Ok(Extension(Self { pool }))
39    }
40
41    pub fn connection(
42        &self,
43    ) -> Result<PooledConnection<SqliteConnectionManager>, Error> {
44        Ok(self.pool.get()?)
45    }
46}