Skip to main content

axum_session/databases/
any_db.rs

1use crate::{DatabaseError, DatabasePool, Session, SessionStore};
2use async_trait::async_trait;
3use std::fmt::Debug;
4use std::sync::Arc;
5///Any Session Helper type for the DatabasePool.
6pub type SessionAnySession = Session<SessionAnyPool>;
7///Any Session Store Helper type for the DatabasePool.
8pub type SessionAnySessionStore = SessionStore<SessionAnyPool>;
9
10/// [SessionAnyPool] is effectively a `dyn DatabasePool`. It can be useful if your application
11///
12/// requires a runtime decision between multiple database backends. For example using `sqlite`
13/// in development builds but `postgres` in production builds.
14#[derive(Clone)]
15pub struct SessionAnyPool {
16    pool: Arc<dyn DatabasePool + Send + Sync>,
17}
18
19impl SessionAnyPool {
20    pub fn new<Pool>(pool: Pool) -> Self
21    where
22        Pool: 'static + DatabasePool + Send + Sync,
23    {
24        Self {
25            pool: Arc::new(pool),
26        }
27    }
28}
29
30impl Debug for SessionAnyPool {
31    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
32        f.debug_struct("SessionAnyPool").finish()
33    }
34}
35
36#[async_trait]
37impl DatabasePool for SessionAnyPool {
38    async fn initiate(&self, table_name: &str) -> Result<(), DatabaseError> {
39        self.pool.initiate(table_name).await
40    }
41
42    async fn count(&self, table_name: &str) -> Result<i64, DatabaseError> {
43        self.pool.count(table_name).await
44    }
45
46    async fn store(
47        &self,
48        id: &str,
49        session: &str,
50        expires: i64,
51        table_name: &str,
52    ) -> Result<(), DatabaseError> {
53        self.pool.store(id, session, expires, table_name).await
54    }
55
56    async fn load(&self, id: &str, table_name: &str) -> Result<Option<String>, DatabaseError> {
57        self.pool.load(id, table_name).await
58    }
59
60    async fn delete_one_by_id(&self, id: &str, table_name: &str) -> Result<(), DatabaseError> {
61        self.pool.delete_one_by_id(id, table_name).await
62    }
63
64    async fn exists(&self, id: &str, table_name: &str) -> Result<bool, DatabaseError> {
65        self.pool.exists(id, table_name).await
66    }
67
68    async fn delete_by_expiry(&self, table_name: &str) -> Result<Vec<String>, DatabaseError> {
69        self.pool.delete_by_expiry(table_name).await
70    }
71
72    async fn delete_all(&self, table_name: &str) -> Result<(), DatabaseError> {
73        self.pool.delete_all(table_name).await
74    }
75
76    async fn get_ids(&self, table_name: &str) -> Result<Vec<String>, DatabaseError> {
77        self.pool.get_ids(table_name).await
78    }
79
80    fn auto_handles_expiry(&self) -> bool {
81        self.pool.auto_handles_expiry()
82    }
83}