From 819252ffe64289b4d67a32d3fd414bae52072e7e Mon Sep 17 00:00:00 2001 From: Quentin Gliech Date: Thu, 23 Sep 2021 17:40:50 +0200 Subject: [PATCH] Make database-related warp filters generic over the DB type --- crates/core/src/filters/database.rs | 37 ++++++++++++++++------------- 1 file changed, 21 insertions(+), 16 deletions(-) diff --git a/crates/core/src/filters/database.rs b/crates/core/src/filters/database.rs index 4bc18ff3a..fc8b941f3 100644 --- a/crates/core/src/filters/database.rs +++ b/crates/core/src/filters/database.rs @@ -12,45 +12,50 @@ // See the License for the specific language governing permissions and // limitations under the License. +//! Database-related filters to grab connections and start transactions from the +//! connection pool + use std::convert::Infallible; -use sqlx::{pool::PoolConnection, PgPool, Postgres, Transaction}; +use sqlx::{ + pool::{Pool, PoolConnection}, + Database, Transaction, +}; use warp::{Filter, Rejection}; use crate::errors::WrapError; -fn with_pool( - pool: &PgPool, -) -> impl Filter + Clone + Send + Sync + 'static { +fn with_pool( + pool: &Pool, +) -> impl Filter,), Error = Infallible> + Clone + Send + Sync + 'static { let pool = pool.clone(); warp::any().map(move || pool.clone()) } /// Acquire a connection to the database -pub fn connection( - pool: &PgPool, -) -> impl Filter,), Error = Rejection> + Clone + Send + Sync + 'static +pub fn connection( + pool: &Pool, +) -> impl Filter,), Error = Rejection> + Clone + Send + Sync + 'static { with_pool(pool).and_then(acquire_connection) } -async fn acquire_connection(pool: PgPool) -> Result, Rejection> { +async fn acquire_connection(pool: Pool) -> Result, Rejection> { let conn = pool.acquire().await.wrap_error()?; Ok(conn) } /// Start a database transaction -pub fn transaction( - pool: &PgPool, -) -> impl Filter,), Error = Rejection> - + Clone - + Send - + Sync - + 'static { +pub fn transaction( + pool: &Pool, +) -> impl Filter,), Error = Rejection> + Clone + Send + Sync + 'static +{ with_pool(pool).and_then(acquire_transaction) } -async fn acquire_transaction(pool: PgPool) -> Result, Rejection> { +async fn acquire_transaction( + pool: Pool, +) -> Result, Rejection> { let txn = pool.begin().await.wrap_error()?; Ok(txn) }