axum_sqlx_tx/
state.rs

1use axum_core::extract::FromRef;
2
3use crate::Marker;
4
5/// Application state that enables the [`Tx`] extractor.
6///
7/// `State` must be provided to `Router`s in order to use the [`Tx`] extractor, or else attempting
8/// to use the `Router` will not compile.
9///
10/// `State` is constructed via [`Tx::setup`](crate::Tx::setup) or
11/// [`Config::setup`](crate::Config::setup), which also return a middleware [`Layer`](crate::Layer).
12/// The state and the middleware together enable the [`Tx`] extractor to work.
13///
14/// [`Tx`]: crate::Tx
15#[derive(Debug)]
16pub struct State<DB: Marker> {
17    pool: sqlx::Pool<DB::Driver>,
18}
19
20impl<DB: Marker> State<DB> {
21    pub(crate) fn new(pool: sqlx::Pool<DB::Driver>) -> Self {
22        Self { pool }
23    }
24
25    pub(crate) async fn transaction(
26        &self,
27    ) -> Result<sqlx::Transaction<'static, DB::Driver>, sqlx::Error> {
28        self.pool.begin().await
29    }
30}
31
32impl<DB: Marker> Clone for State<DB> {
33    fn clone(&self) -> Self {
34        Self {
35            pool: self.pool.clone(),
36        }
37    }
38}
39
40impl<DB: Marker> FromRef<State<DB>> for sqlx::Pool<DB::Driver> {
41    fn from_ref(input: &State<DB>) -> Self {
42        input.pool.clone()
43    }
44}