Tx

Struct Tx 

Source
pub struct Tx<DB: Marker, E = Error> { /* private fields */ }
Expand description

An axum extractor for a database transaction.

&mut Tx implements sqlx::Executor so it can be used directly with sqlx::query() (and sqlx::query_as(), the corresponding macros, etc.):

use axum_sqlx_tx::Tx;
use sqlx::Sqlite;

async fn handler(mut tx: Tx<Sqlite>) -> Result<(), sqlx::Error> {
    sqlx::query("...").execute(&mut tx).await?;
    /* ... */
}

It also implements Deref<Target = sqlx::Transaction> and DerefMut, so you can call methods from Transaction and its traits:

use axum_sqlx_tx::Tx;
use sqlx::{Acquire as _, Sqlite};

async fn handler(mut tx: Tx<Sqlite>) -> Result<(), sqlx::Error> {
    let inner = tx.begin().await?;
    /* ... */
}

The E generic parameter controls the error type returned when the extractor fails. This can be used to configure the error response returned when the extractor fails:

use axum::response::IntoResponse;
use axum_sqlx_tx::Tx;
use sqlx::Sqlite;

struct MyError(axum_sqlx_tx::Error);

// The error type must implement From<axum_sqlx_tx::Error>
impl From<axum_sqlx_tx::Error> for MyError {
    fn from(error: axum_sqlx_tx::Error) -> Self {
        Self(error)
    }
}

// The error type must implement IntoResponse
impl IntoResponse for MyError {
    fn into_response(self) -> axum::response::Response {
        (http::StatusCode::INTERNAL_SERVER_ERROR, "internal server error").into_response()
    }
}

async fn handler(tx: Tx<Sqlite, MyError>) {
    /* ... */
}

Implementations§

Source§

impl<DB: Marker, E> Tx<DB, E>

Source

pub fn setup(pool: Pool<DB::Driver>) -> (State<DB>, Layer<DB, Error>)

Crate a State and Layer to enable the extractor.

This is convenient to use from a type alias, e.g.

type Tx = axum_sqlx_tx::Tx<sqlx::Sqlite>;

let pool: sqlx::SqlitePool = todo!();
let (state, layer) = Tx::setup(pool);
Source

pub fn config(pool: Pool<DB::Driver>) -> Config<DB, Error>

Configure extractor behaviour.

See the Config API for available options.

This is convenient to use from a type alias, e.g.

type Tx = axum_sqlx_tx::Tx<sqlx::Sqlite>;

let config = Tx::config(pool);
Source

pub async fn commit(self) -> Result<(), Error>

Explicitly commit the transaction.

By default, the transaction will be committed when a successful response is returned (specifically, when the Service middleware intercepts an HTTP 2XX or 3XX response). This method allows the transaction to be committed explicitly.

Note: trying to use the Tx extractor again after calling commit will currently generate Error::OverlappingExtractors errors. This may change in future.

Trait Implementations§

Source§

impl<DB: Marker, E> AsMut<Transaction<'static, <DB as Marker>::Driver>> for Tx<DB, E>

Source§

fn as_mut(&mut self) -> &mut Transaction<'static, DB::Driver>

Converts this type into a mutable reference of the (usually inferred) input type.
Source§

impl<DB: Marker, E> AsRef<Transaction<'static, <DB as Marker>::Driver>> for Tx<DB, E>

Source§

fn as_ref(&self) -> &Transaction<'static, DB::Driver>

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl<DB: Marker, E> Debug for Tx<DB, E>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<DB: Marker, E> Deref for Tx<DB, E>

Source§

type Target = Transaction<'static, <DB as Marker>::Driver>

The resulting type after dereferencing.
Source§

fn deref(&self) -> &Self::Target

Dereferences the value.
Source§

impl<DB: Marker, E> DerefMut for Tx<DB, E>

Source§

fn deref_mut(&mut self) -> &mut Self::Target

Mutably dereferences the value.
Source§

impl<'c, DB, E> Executor<'c> for &'c mut Tx<DB, E>
where DB: Marker, for<'t> &'t mut <DB::Driver as Database>::Connection: Executor<'t, Database = DB::Driver>, E: Debug + Send,

Source§

type Database = <DB as Marker>::Driver

Source§

fn fetch_many<'e, 'q: 'e, Q>( self, query: Q, ) -> BoxStream<'e, Result<Either<<Self::Database as Database>::QueryResult, <Self::Database as Database>::Row>, Error>>
where Q: Execute<'q, Self::Database> + 'q, 'c: 'e,

Execute multiple queries and return the generated results as a stream from each query, in a stream.
Source§

fn fetch_optional<'e, 'q: 'e, Q>( self, query: Q, ) -> BoxFuture<'e, Result<Option<<Self::Database as Database>::Row>, Error>>
where Q: Execute<'q, Self::Database> + 'q, 'c: 'e,

Execute the query and returns at most one row.
Source§

fn prepare_with<'e, 'q: 'e>( self, sql: &'q str, parameters: &'e [<Self::Database as Database>::TypeInfo], ) -> BoxFuture<'e, Result<<Self::Database as Database>::Statement<'q>, Error>>
where 'c: 'e,

Prepare the SQL query, with parameter type information, to inspect the type information about its parameters and results. Read more
Source§

fn execute<'e, 'q, E>( self, query: E, ) -> Pin<Box<dyn Future<Output = Result<<Self::Database as Database>::QueryResult, Error>> + Send + 'e>>
where 'q: 'e, 'c: 'e, E: 'q + Execute<'q, Self::Database>,

Execute the query and return the total number of rows affected.
Source§

fn execute_many<'e, 'q, E>( self, query: E, ) -> Pin<Box<dyn Stream<Item = Result<<Self::Database as Database>::QueryResult, Error>> + Send + 'e>>
where 'q: 'e, 'c: 'e, E: 'q + Execute<'q, Self::Database>,

Execute multiple queries and return the rows affected from each query, in a stream.
Source§

fn fetch<'e, 'q, E>( self, query: E, ) -> Pin<Box<dyn Stream<Item = Result<<Self::Database as Database>::Row, Error>> + Send + 'e>>
where 'q: 'e, 'c: 'e, E: 'q + Execute<'q, Self::Database>,

Execute the query and return the generated results as a stream.
Source§

fn fetch_all<'e, 'q, E>( self, query: E, ) -> Pin<Box<dyn Future<Output = Result<Vec<<Self::Database as Database>::Row>, Error>> + Send + 'e>>
where 'q: 'e, 'c: 'e, E: 'q + Execute<'q, Self::Database>,

Execute the query and return all the generated results, collected into a Vec.
Source§

fn fetch_one<'e, 'q, E>( self, query: E, ) -> Pin<Box<dyn Future<Output = Result<<Self::Database as Database>::Row, Error>> + Send + 'e>>
where 'q: 'e, 'c: 'e, E: 'q + Execute<'q, Self::Database>,

Execute the query and returns exactly one row.
Source§

fn prepare<'e, 'q>( self, query: &'q str, ) -> Pin<Box<dyn Future<Output = Result<<Self::Database as Database>::Statement<'q>, Error>> + Send + 'e>>
where 'q: 'e, 'c: 'e,

Prepare the SQL query to inspect the type information of its parameters and results. Read more
Source§

impl<DB: Marker, S, E> FromRequestParts<S> for Tx<DB, E>
where S: Sync, E: From<Error> + IntoResponse + Send, State<DB>: FromRef<S>,

Source§

type Rejection = E

If the extractor fails it’ll use this “rejection” type. A rejection is a kind of error that can be converted into a response.
Source§

async fn from_request_parts( parts: &mut Parts, _state: &S, ) -> Result<Self, Self::Rejection>

Perform the extraction.

Auto Trait Implementations§

§

impl<DB, E> Freeze for Tx<DB, E>

§

impl<DB, E = Error> !RefUnwindSafe for Tx<DB, E>

§

impl<DB, E> Send for Tx<DB, E>
where E: Send,

§

impl<DB, E> Sync for Tx<DB, E>
where E: Sync, <<DB as Marker>::Driver as Database>::Connection: Sync,

§

impl<DB, E> Unpin for Tx<DB, E>
where E: Unpin,

§

impl<DB, E = Error> !UnwindSafe for Tx<DB, E>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<S, T> FromRequest<S, ViaParts> for T
where S: Send + Sync, T: FromRequestParts<S>,

Source§

type Rejection = <T as FromRequestParts<S>>::Rejection

If the extractor fails it’ll use this “rejection” type. A rejection is a kind of error that can be converted into a response.
Source§

fn from_request( req: Request<Body>, state: &S, ) -> impl Future<Output = Result<T, <T as FromRequest<S, ViaParts>>::Rejection>>

Perform the extraction.
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,