Module db

Source
Expand description

Database module

§Axum

If you wan’t to use axum the best way is to make a small wrapper around ConnOwned.

use chuchi_postgres as pg;
use pg::db::{Conn, Trans, Db};
use axum::extract::{FromRequestParts, FromRef};
use axum::http::request::Parts;

pub struct ConnOwned(pub pg::db::ConnOwned);

impl ConnOwned {
	pub fn conn(&self) -> Conn {
		self.0.conn()
	}

	pub async fn trans(&mut self) -> Result<Trans, pg::Error> {
		self.0.trans().await
	}
}

impl<S> FromRequestParts<S> for ConnOwned
where
	S: Send + Sync,
	Db: FromRef<S>,
{
	type Rejection = MyError;

	async fn from_request_parts(
		_parts: &mut Parts,
		state: &S,
	) -> Result<Self, Self::Rejection> {
		let db = Db::from_ref(state);
		db.get()
			.await
			.map(Self)
			.map_err(|e| MyError::Internal(e.to_string()))
	}
}

Structs§

Conn
This might contain a connection or none.
ConnOwned
Db
This might contain a database or none.
Trans
This might contain a transaction or none.