Skip to content

Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation

feat(observability): add context aware database connections (#13472)

spritianeja03fe3d92cfc7ea
diff --git a/Cargo.lock b/Cargo.lock
index 9074364d41..f825157c6e 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3120,6 +3120,7 @@ version = "0.1.0"
dependencies = [
"async-bb8-diesel",
"base64 0.22.1",
+ "bb8",
"common_enums",
"common_types",
"common_utils",
@@ -3228,6 +3229,7 @@ dependencies = [
"serde",
"serde_json",
"serde_path_to_error",
+ "storage_impl",
"thiserror 1.0.69",
"tokio 1.48.0",
]
diff --git a/crates/diesel_models/Cargo.toml b/crates/diesel_models/Cargo.toml
index c06c01f533..e33285952a 100644
--- a/crates/diesel_models/Cargo.toml
+++ b/crates/diesel_models/Cargo.toml
@@ -18,6 +18,7 @@ deja = ["dep:deja", "deja/diesel-pg"]
[dependencies]
async-bb8-diesel = "0.2.1"
base64 = "0.22.1"
+bb8 = "0.8.6"
diesel = { version = "2.2.10", features = ["postgres", "serde_json", "time", "128-column-tables", "i-implement-a-third-party-backend-and-opt-into-breaking-changes"] }
error-stack = "0.4.1"
serde = { version = "1.0.219", features = ["derive"] }
diff --git a/crates/diesel_models/src/kv.rs b/crates/diesel_models/src/kv.rs
index 4e5a6dfa8f..090d2fb449 100644
--- a/crates/diesel_models/src/kv.rs
+++ b/crates/diesel_models/src/kv.rs
@@ -69,7 +69,7 @@ impl SerializableQuery {
}
async fn from_query<Q>(
- conn: &mut crate::PgPooledConn,
+ conn: &mut crate::DatabaseConnectionWithContext<'_>,
query: Q,
entity_type: String,
operation: DatabaseOperation,
@@ -94,6 +94,7 @@ impl SerializableQuery {
)?;
let bind_collector = conn
+ .raw_connection()
.run(move |c| {
let mut bc = RawBytesBindCollector::<Pg>::new();
query.collect_binds(&mut bc, c, &Pg)?;
@@ -138,14 +139,18 @@ impl SerializableQuery {
)
}
- pub async fn execute(self, conn: &mut crate::PgPooledConn) -> crate::StorageResult<usize> {
+ pub async fn execute(
+ self,
+ conn: &mut crate::DatabaseConnectionWithContext<'_>,
+ ) -> crate::StorageResult<usize> {
use common_utils::errors::ReportSwitchExt;
let query = self.to_collected_query();
logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());
- conn.run(move |c| ExecuteDsl::execute(query, c))
+ conn.raw_connection()
+ .run(move |c| ExecuteDsl::execute(query, c))
.await
.attach_printable("Failed to execute drainer query")
.switch()
@@ -172,7 +177,7 @@ impl SerializableQuery {
}
pub(crate) async fn generate_insert_query<T, N>(
- conn: &mut crate::PgPooledConn,
+ conn: &mut crate::DatabaseConnectionWithContext<'_>,
new: N,
) -> crate::StorageResult<SerializableQuery>
where
@@ -189,7 +194,7 @@ where
}
pub(crate) async fn generate_update_query_by_id<T, V, Pk>(
- conn: &mut crate::PgPooledConn,
+ conn: &mut crate::DatabaseConnectionWithContext<'_>,
id: Pk,
values: V,
) -> crate::StorageResult<SerializableQuery>
@@ -212,7 +217,7 @@ where
}
pub(crate) async fn generate_update_query_with_predicate<T, V, P>(
- conn: &mut crate::PgPooledConn,
+ conn: &mut crate::DatabaseConnectionWithContext<'_>,
predicate: P,
values: V,
) -> crate::StorageResult<SerializableQuery>
diff --git a/crates/diesel_models/src/lib.rs b/crates/diesel_models/src/lib.rs
index c93d1c113c..80494f08a3 100644
--- a/crates/diesel_models/src/lib.rs
+++ b/crates/diesel_models/src/lib.rs
@@ -66,6 +66,9 @@ pub mod user_authentication_method;
pub mod user_key_store;
pub mod user_role;
+use std::sync::Arc;
+
+use common_utils::external_service::ExternalServiceEventEmitter;
use diesel_impl::{DieselArray, OptionalDieselArray};
#[cfg(feature = "v2")]
use diesel_impl::{RequiredFromNullable, RequiredFromNullableWithDefault};
@@ -81,7 +84,52 @@ pub type DejaPgConnection = deja::DejaLoadConnection<diesel::PgConnection>;
#[cfg(not(feature = "deja"))]
pub type DejaPgConnection = diesel::PgConnection;
+pub type RawPgConnection = async_bb8_diesel::Connection<DejaPgConnection>;
pub type PgPooledConn = async_bb8_diesel::Connection<DejaPgConnection>;
+
+/// A connection leased from a database pool, along with the request context that queries run on
+/// it are attributed to. The connection is returned to the pool when this value is dropped.
+///
+/// Every query in this crate is issued through this type, so a query cannot be run without first
+/// stating whether a request context exists for it.
+///
+/// The lease borrows the pool it was acquired from through `bb8::Pool::get`, so this wrapper
+/// cannot outlive that pool. The pool lifetime is carried through query signatures in this crate.
+pub struct DatabaseConnectionWithContext<'pool> {
+ connection: bb8::PooledConnection<'pool, async_bb8_diesel::ConnectionManager<DejaPgConnection>>,
+ request_id: Option<String>,
+ event_emitter: Arc<dyn ExternalServiceEventEmitter>,
+}
+
+impl<'pool> DatabaseConnectionWithContext<'pool> {
+ pub fn new(
+ connection: bb8::PooledConnection<
+ 'pool,
+ async_bb8_diesel::ConnectionManager<DejaPgConnection>,
+ >,
+ request_id: Option<String>,
+ event_emitter: Arc<dyn ExternalServiceEventEmitter>,
+ ) -> Self {
+ Self {
+ connection,
+ request_id,
+ event_emitter,
+ }
+ }
+
+ pub fn raw_connection(&self) -> &RawPgConnection {
+ &self.connection
+ }
+
+ pub fn request_id(&self) -> Option<&str> {
+ self.request_id.as_deref()
+ }
+
+ pub fn event_emitter(&self) -> &dyn ExternalServiceEventEmitter {
+ self.event_emitter.as_ref()
+ }
+}
+
pub use self::{
address::*, api_keys::*, callback_mapper::*, capture::*, cards_info::*, configs::*,
customers::*, dispute::*, ephemeral_key::*, events::*, file::*, generic_link::*,
diff --git a/crates/diesel_models/src/query/address.rs b/crates/diesel_models/src/query/address.rs
index b7f057aa67..68838c9d9b 100644
--- a/crates/diesel_models/src/query/address.rs
+++ b/crates/diesel_models/src/query/address.rs
@@ -6,17 +6,17 @@ use crate::{
address::{Address, AddressNew, AddressUpdateInternal},
errors, kv,
schema::address::dsl,
- PgPooledConn, StorageResult,
+ DatabaseConnectionWithContext, StorageResult,
};
impl AddressNew {
- pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Address> {
+ pub async fn insert(self, conn: &DatabaseConnectionWithContext<'_>) -> StorageResult<Address> {
generics::generic_insert(conn, self).await
}
pub async fn generate_drainer_insert_query(
self,
- conn: &mut PgPooledConn,
+ conn: &mut DatabaseConnectionWithContext<'_>,
) -> StorageResult<kv::SerializableQuery> {
kv::generate_insert_query(conn, self)
.await
@@ -25,13 +25,16 @@ impl AddressNew {
}
impl Address {
- pub async fn find_by_address_id(conn: &PgPooledConn, address_id: &str) -> StorageResult<Self> {
+ pub async fn find_by_address_id(
+ conn: &DatabaseConnectionWithContext<'_>,
+ address_id: &str,
+ ) -> StorageResult<Self> {
generics::generic_find_by_id::<<Self as HasTable>::Table, _, _>(conn, address_id.to_owned())
.await
}
pub async fn update_by_address_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
address_id: String,
address: AddressUpdateInternal,
) -> StorageResult<Self> {
@@ -61,7 +64,7 @@ impl Address {
pub async fn update(
self,
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
address_update_internal: AddressUpdateInternal,
) -> StorageResult<Self> {
match generics::generic_update_with_unique_predicate_get_result::<
@@ -85,7 +88,7 @@ impl Address {
}
pub async fn delete_by_address_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
address_id: &str,
) -> StorageResult<bool> {
generics::generic_delete::<<Self as HasTable>::Table, _>(
@@ -96,7 +99,7 @@ impl Address {
}
pub async fn update_by_merchant_id_customer_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
customer_id: &common_utils::id_type::CustomerId,
merchant_id: &common_utils::id_type::MerchantId,
address: AddressUpdateInternal,
@@ -112,7 +115,7 @@ impl Address {
}
pub async fn find_by_merchant_id_payment_id_address_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
payment_id: &common_utils::id_type::PaymentId,
address_id: &str,
@@ -141,7 +144,7 @@ impl Address {
}
pub async fn find_optional_by_address_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
address_id: &str,
) -> StorageResult<Option<Self>> {
generics::generic_find_by_id_optional::<<Self as HasTable>::Table, _, _>(
@@ -155,7 +158,7 @@ impl Address {
impl AddressUpdateInternal {
pub async fn generate_drainer_update_query(
self,
- conn: &mut PgPooledConn,
+ conn: &mut DatabaseConnectionWithContext<'_>,
address_id: String,
) -> StorageResult<kv::SerializableQuery> {
kv::generate_update_query_with_predicate::<<Address as HasTable>::Table, _, _>(
diff --git a/crates/diesel_models/src/query/api_keys.rs b/crates/diesel_models/src/query/api_keys.rs
index 479e226c1d..73c747b2e4 100644
--- a/crates/diesel_models/src/query/api_keys.rs
+++ b/crates/diesel_models/src/query/api_keys.rs
@@ -5,18 +5,18 @@ use crate::{
api_keys::{ApiKey, ApiKeyNew, ApiKeyUpdate, ApiKeyUpdateInternal, HashedApiKey},
errors,
schema::api_keys::dsl,
- PgPooledConn, StorageResult,
+ DatabaseConnectionWithContext, StorageResult,
};
impl ApiKeyNew {
- pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<ApiKey> {
+ pub async fn insert(self, conn: &DatabaseConnectionWithContext<'_>) -> StorageResult<ApiKey> {
generics::generic_insert(conn, self).await
}
}
impl ApiKey {
pub async fn update_by_merchant_id_key_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: common_utils::id_type::MerchantId,
key_id: common_utils::id_type::ApiKeyId,
api_key_update: ApiKeyUpdate,
@@ -55,7 +55,7 @@ impl ApiKey {
}
pub async fn revoke_by_merchant_id_key_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
key_id: &common_utils::id_type::ApiKeyId,
) -> StorageResult<bool> {
@@ -69,7 +69,7 @@ impl ApiKey {
}
pub async fn find_optional_by_merchant_id_key_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
key_id: &common_utils::id_type::ApiKeyId,
) -> StorageResult<Option<Self>> {
@@ -83,7 +83,7 @@ impl ApiKey {
}
pub async fn find_optional_by_hashed_api_key(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
hashed_api_key: HashedApiKey,
) -> StorageResult<Option<Self>> {
generics::generic_find_one_optional::<<Self as HasTable>::Table, _, _>(
@@ -94,7 +94,7 @@ impl ApiKey {
}
pub async fn find_by_merchant_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
limit: Option<i64>,
offset: Option<i64>,
diff --git a/crates/diesel_models/src/query/authentication.rs b/crates/diesel_models/src/query/authentication.rs
index b030d549e1..6f04f8bd5b 100644
--- a/crates/diesel_models/src/query/authentication.rs
+++ b/crates/diesel_models/src/query/authentication.rs
@@ -6,17 +6,20 @@ use crate::{
authentication::{Authentication, AuthenticationNew, AuthenticationUpdateInternal},
errors, kv,
schema::authentication::dsl,
- PgPooledConn, StorageResult,
+ DatabaseConnectionWithContext, StorageResult,
};
impl AuthenticationNew {
- pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Authentication> {
+ pub async fn insert(
+ self,
+ conn: &DatabaseConnectionWithContext<'_>,
+ ) -> StorageResult<Authentication> {
Box::pin(generics::generic_insert(conn, self)).await
}
pub async fn generate_drainer_insert_query(
self,
- conn: &mut PgPooledConn,
+ conn: &mut DatabaseConnectionWithContext<'_>,
) -> StorageResult<kv::SerializableQuery> {
kv::generate_insert_query(conn, self)
.await
@@ -26,7 +29,7 @@ impl AuthenticationNew {
impl Authentication {
pub async fn update_by_processor_merchant_id_authentication_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
processor_merchant_id: &common_utils::id_type::MerchantId,
authentication_id: &common_utils::id_type::AuthenticationId,
authentication_update: AuthenticationUpdateInternal,
@@ -65,7 +68,7 @@ impl Authentication {
}
pub async fn update_by_merchant_id_authentication_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
authentication_id: &common_utils::id_type::AuthenticationId,
authentication_update: AuthenticationUpdateInternal,
@@ -104,7 +107,7 @@ impl Authentication {
}
pub async fn find_by_processor_merchant_id_authentication_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
processor_merchant_id: &common_utils::id_type::MerchantId,
authentication_id: &common_utils::id_type::AuthenticationId,
) -> StorageResult<Self> {
@@ -118,7 +121,7 @@ impl Authentication {
}
pub async fn find_by_merchant_id_authentication_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
authentication_id: &common_utils::id_type::AuthenticationId,
) -> StorageResult<Self> {
@@ -132,7 +135,7 @@ impl Authentication {
}
pub async fn find_authentication_by_processor_merchant_id_connector_authentication_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
processor_merchant_id: &common_utils::id_type::MerchantId,
connector_authentication_id: &str,
) -> StorageResult<Self> {
@@ -146,7 +149,7 @@ impl Authentication {
}
pub async fn find_authentication_by_merchant_id_connector_authentication_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
connector_authentication_id: &str,
) -> StorageResult<Self> {
@@ -163,7 +166,7 @@ impl Authentication {
impl AuthenticationUpdateInternal {
pub async fn generate_drainer_update_query(
self,
- conn: &mut PgPooledConn,
+ conn: &mut DatabaseConnectionWithContext<'_>,
processor_merchant_id: common_utils::id_type::MerchantId,
authentication_id: common_utils::id_type::AuthenticationId,
) -> StorageResult<kv::SerializableQuery> {
diff --git a/crates/diesel_models/src/query/authorization.rs b/crates/diesel_models/src/query/authorization.rs
index 86e2b10d37..2c774014b6 100644
--- a/crates/diesel_models/src/query/authorization.rs
+++ b/crates/diesel_models/src/query/authorization.rs
@@ -7,18 +7,21 @@ use crate::{
},
errors,
schema::incremental_authorization::dsl,
- PgPooledConn, StorageResult,
+ DatabaseConnectionWithContext, StorageResult,
};
impl AuthorizationNew {
- pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Authorization> {
+ pub async fn insert(
+ self,
+ conn: &DatabaseConnectionWithContext<'_>,
+ ) -> StorageResult<Authorization> {
generics::generic_insert(conn, self).await
}
}
impl Authorization {
pub async fn update_by_processor_merchant_id_authorization_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
processor_merchant_id: common_utils::id_type::MerchantId,
authorization_id: String,
authorization_update: AuthorizationUpdate,
@@ -58,7 +61,7 @@ impl Authorization {
// Fallback function for stagger release - updates by merchant_id when processor_merchant_id is NULL
pub async fn update_by_merchant_id_authorization_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: common_utils::id_type::MerchantId,
authorization_id: String,
authorization_update: AuthorizationUpdate,
@@ -97,7 +100,7 @@ impl Authorization {
}
pub async fn find_by_processor_merchant_id_payment_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
processor_merchant_id: &common_utils::id_type::MerchantId,
payment_id: &common_utils::id_type::PaymentId,
) -> StorageResult<Vec<Self>> {
@@ -115,7 +118,7 @@ impl Authorization {
// Fallback function for stagger release - queries by merchant_id when processor_merchant_id is NULL
pub async fn find_by_merchant_id_payment_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
payment_id: &common_utils::id_type::PaymentId,
) -> StorageResult<Vec<Self>> {
diff --git a/crates/diesel_models/src/query/batch_blocklist_job.rs b/crates/diesel_models/src/query/batch_blocklist_job.rs
index 2f4a398328..f8d420d082 100644
--- a/crates/diesel_models/src/query/batch_blocklist_job.rs
+++ b/crates/diesel_models/src/query/batch_blocklist_job.rs
@@ -4,18 +4,21 @@ use super::generics;
use crate::{
batch_blocklist_job::{BatchBlocklistJob, BatchBlocklistJobNew, BatchBlocklistJobUpdate},
schema::batch_blocklist_jobs::dsl,
- PgPooledConn, StorageResult,
+ DatabaseConnectionWithContext, StorageResult,
};
impl BatchBlocklistJobNew {
- pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<BatchBlocklistJob> {
+ pub async fn insert(
+ self,
+ conn: &DatabaseConnectionWithContext<'_>,
+ ) -> StorageResult<BatchBlocklistJob> {
generics::generic_insert(conn, self).await
}
}
impl BatchBlocklistJob {
pub async fn find_by_id_merchant_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
id: &str,
merchant_id: &str,
) -> StorageResult<Self> {
@@ -29,7 +32,7 @@ impl BatchBlocklistJob {
}
pub async fn list_by_merchant_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &str,
limit: i64,
offset: i64,
@@ -45,7 +48,7 @@ impl BatchBlocklistJob {
}
pub async fn count_by_merchant_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &str,
) -> StorageResult<usize> {
generics::generic_count::<<Self as HasTable>::Table, _>(
@@ -56,7 +59,7 @@ impl BatchBlocklistJob {
}
pub async fn update_by_id_merchant_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
id: &str,
merchant_id: &str,
update: BatchBlocklistJobUpdate,
diff --git a/crates/diesel_models/src/query/blocklist.rs b/crates/diesel_models/src/query/blocklist.rs
index 1bacb5a2c8..9e6b80ff93 100644
--- a/crates/diesel_models/src/query/blocklist.rs
+++ b/crates/diesel_models/src/query/blocklist.rs
@@ -7,16 +7,19 @@ use crate::{
blocklist::{Blocklist, BlocklistNew},
errors,
schema::blocklist::dsl,
- PgPooledConn, StorageResult,
+ DatabaseConnectionWithContext, StorageResult,
};
impl BlocklistNew {
- pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Blocklist> {
+ pub async fn insert(
+ self,
+ conn: &DatabaseConnectionWithContext<'_>,
+ ) -> StorageResult<Blocklist> {
generics::generic_insert(conn, self).await
}
pub async fn bulk_insert_on_conflict_do_nothing(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
entries: Vec<Self>,
) -> StorageResult<usize> {
let query = diesel::insert_into(<Blocklist as HasTable>::table())
@@ -29,8 +32,10 @@ impl BlocklistNew {
.do_nothing();
generics::db_metrics::track_database_call::<<Blocklist as HasTable>::Table, _, _>(
- query.execute_async(conn),
+ conn.request_id(),
+ conn.event_emitter(),
generics::db_metrics::DatabaseOperation::Insert,
+ query.execute_async(conn.raw_connection()),
)
.await
.map_err(|e| error_stack::report!(e))
@@ -41,7 +46,7 @@ impl BlocklistNew {
impl Blocklist {
pub async fn find_by_processor_merchant_id_fingerprint_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
processor_merchant_id: &common_utils::id_type::MerchantId,
fingerprint_id: &str,
) -> StorageResult<Self> {
@@ -57,7 +62,7 @@ impl Blocklist {
// Rows written before profile scoping have a NULL profile_id and block the whole merchant,
// so they must keep matching every profile.
pub async fn find_by_processor_merchant_id_profile_id_fingerprint_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
processor_merchant_id: &common_utils::id_type::MerchantId,
profile_id: &common_utils::id_type::ProfileId,
fingerprint_id: &str,
@@ -78,7 +83,7 @@ impl Blocklist {
// Fallback function for stagger release - finds by merchant_id when processor_merchant_id is NULL
pub async fn find_by_merchant_id_fingerprint_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
processor_merchant_id: &common_utils::id_type::MerchantId,
fingerprint_id: &str,
) -> StorageResult<Self> {
@@ -92,7 +97,7 @@ impl Blocklist {
}
pub async fn find_by_merchant_id_profile_id_fingerprint_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
processor_merchant_id: &common_utils::id_type::MerchantId,
profile_id: &common_utils::id_type::ProfileId,
fingerprint_id: &str,
@@ -112,7 +117,7 @@ impl Blocklist {
}
pub async fn list_by_processor_merchant_id_data_kind(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
processor_merchant_id: &common_utils::id_type::MerchantId,
data_kind: common_enums::BlocklistDataKind,
limit: i64,
@@ -134,7 +139,7 @@ impl Blocklist {
}
pub async fn list_by_processor_merchant_id_profile_id_data_kind(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
processor_merchant_id: &common_utils::id_type::MerchantId,
profile_id: &common_utils::id_type::ProfileId,
data_kind: common_enums::BlocklistDataKind,
@@ -162,7 +167,7 @@ impl Blocklist {
}
pub async fn get_count_by_processor_merchant_id_data_kind(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
processor_merchant_id: &common_utils::id_type::MerchantId,
data_kind: common_enums::BlocklistDataKind,
) -> StorageResult<usize> {
@@ -179,7 +184,7 @@ impl Blocklist {
}
pub async fn get_count_by_processor_merchant_id_profile_id_data_kind(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
processor_merchant_id: &common_utils::id_type::MerchantId,
profile_id: &common_utils::id_type::ProfileId,
data_kind: common_enums::BlocklistDataKind,
@@ -202,7 +207,7 @@ impl Blocklist {
}
pub async fn list_by_processor_merchant_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
processor_merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
@@ -220,7 +225,7 @@ impl Blocklist {
}
pub async fn delete_by_processor_merchant_id_fingerprint_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
processor_merchant_id: &common_utils::id_type::MerchantId,
fingerprint_id: &str,
) -> StorageResult<Self> {
@@ -234,7 +239,7 @@ impl Blocklist {
}
pub async fn delete_by_processor_merchant_id_profile_id_fingerprint_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
processor_merchant_id: &common_utils::id_type::MerchantId,
profile_id: &common_utils::id_type::ProfileId,
fingerprint_id: &str,
@@ -255,7 +260,7 @@ impl Blocklist {
// Fallback function for stagger release - deletes by merchant_id when processor_merchant_id is NULL
pub async fn delete_by_merchant_id_fingerprint_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
processor_merchant_id: &common_utils::id_type::MerchantId,
fingerprint_id: &str,
) -> StorageResult<Self> {
@@ -269,7 +274,7 @@ impl Blocklist {
}
pub async fn delete_by_merchant_id_profile_id_fingerprint_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
processor_merchant_id: &common_utils::id_type::MerchantId,
profile_id: &common_utils::id_type::ProfileId,
fingerprint_id: &str,
diff --git a/crates/diesel_models/src/query/blocklist_fingerprint.rs b/crates/diesel_models/src/query/blocklist_fingerprint.rs
index ce9bba3c60..9f83fa815c 100644
--- a/crates/diesel_models/src/query/blocklist_fingerprint.rs
+++ b/crates/diesel_models/src/query/blocklist_fingerprint.rs
@@ -4,18 +4,21 @@ use super::generics;
use crate::{
blocklist_fingerprint::{BlocklistFingerprint, BlocklistFingerprintNew},
schema::blocklist_fingerprint::dsl,
- PgPooledConn, StorageResult,
+ DatabaseConnectionWithContext, StorageResult,
};
impl BlocklistFingerprintNew {
- pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<BlocklistFingerprint> {
+ pub async fn insert(
+ self,
+ conn: &DatabaseConnectionWithContext<'_>,
+ ) -> StorageResult<BlocklistFingerprint> {
generics::generic_insert(conn, self).await
}
}
impl BlocklistFingerprint {
pub async fn find_by_merchant_id_fingerprint_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
fingerprint_id: &str,
) -> StorageResult<Self> {
diff --git a/crates/diesel_models/src/query/blocklist_lookup.rs b/crates/diesel_models/src/query/blocklist_lookup.rs
index 0cd2b5a2c4..0e94e0b1f4 100644
--- a/crates/diesel_models/src/query/blocklist_lookup.rs
+++ b/crates/diesel_models/src/query/blocklist_lookup.rs
@@ -4,18 +4,21 @@ use super::generics;
use crate::{
blocklist_lookup::{BlocklistLookup, BlocklistLookupNew},
schema::blocklist_lookup::dsl,
- PgPooledConn, StorageResult,
+ DatabaseConnectionWithContext, StorageResult,
};
impl BlocklistLookupNew {
- pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<BlocklistLookup> {
+ pub async fn insert(
+ self,
+ conn: &DatabaseConnectionWithContext<'_>,
+ ) -> StorageResult<BlocklistLookup> {
generics::generic_insert(conn, self).await
}
}
impl BlocklistLookup {
pub async fn find_by_merchant_id_fingerprint(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
fingerprint: &str,
) -> StorageResult<Self> {
@@ -29,7 +32,7 @@ impl BlocklistLookup {
}
pub async fn delete_by_merchant_id_fingerprint(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
fingerprint: &str,
) -> StorageResult<Self> {
diff --git a/crates/diesel_models/src/query/business_profile.rs b/crates/diesel_models/src/query/business_profile.rs
index 172590888c..9bc4f7968d 100644
--- a/crates/diesel_models/src/query/business_profile.rs
+++ b/crates/diesel_models/src/query/business_profile.rs
@@ -7,11 +7,11 @@ use crate::schema::business_profile::dsl::{self, profile_id as dsl_identifier};
use crate::schema_v2::business_profile::dsl::{self, id as dsl_identifier};
use crate::{
business_profile::{Profile, ProfileNew, ProfileUpdateInternal},
- errors, PgPooledConn, StorageResult,
+ errors, DatabaseConnectionWithContext, StorageResult,
};
impl ProfileNew {
- pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Profile> {
+ pub async fn insert(self, conn: &DatabaseConnectionWithContext<'_>) -> StorageResult<Profile> {
Box::pin(generics::generic_insert(conn, self)).await
}
}
@@ -19,7 +19,7 @@ impl ProfileNew {
impl Profile {
pub async fn update_by_profile_id(
self,
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
business_profile: ProfileUpdateInternal,
) -> StorageResult<Self> {
match Box::pin(generics::generic_update_by_id::<
@@ -39,7 +39,7 @@ impl Profile {
}
pub async fn find_by_profile_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
profile_id: &common_utils::id_type::ProfileId,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
@@ -50,7 +50,7 @@ impl Profile {
}
pub async fn find_by_merchant_id_profile_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
profile_id: &common_utils::id_type::ProfileId,
) -> StorageResult<Self> {
@@ -64,7 +64,7 @@ impl Profile {
}
pub async fn find_by_profile_name_merchant_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
profile_name: &str,
merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Self> {
@@ -78,7 +78,7 @@ impl Profile {
}
pub async fn list_profile_by_merchant_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<
@@ -97,7 +97,7 @@ impl Profile {
}
pub async fn delete_by_profile_id_merchant_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
profile_id: &common_utils::id_type::ProfileId,
merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<bool> {
diff --git a/crates/diesel_models/src/query/callback_mapper.rs b/crates/diesel_models/src/query/callback_mapper.rs
index 4210330e07..b8f5cf5f06 100644
--- a/crates/diesel_models/src/query/callback_mapper.rs
+++ b/crates/diesel_models/src/query/callback_mapper.rs
@@ -2,15 +2,19 @@ use diesel::{associations::HasTable, ExpressionMethods};
use super::generics;
use crate::{
- callback_mapper::CallbackMapper, schema::callback_mapper::dsl, PgPooledConn, StorageResult,
+ callback_mapper::CallbackMapper, schema::callback_mapper::dsl, DatabaseConnectionWithContext,
+ StorageResult,
};
impl CallbackMapper {
- pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Self> {
+ pub async fn insert(self, conn: &DatabaseConnectionWithContext<'_>) -> StorageResult<Self> {
generics::generic_insert(conn, self).await
}
- pub async fn find_by_id(conn: &PgPooledConn, id: &str) -> StorageResult<Self> {
+ pub async fn find_by_id(
+ conn: &DatabaseConnectionWithContext<'_>,
+ id: &str,
+ ) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::id.eq(id.to_owned()),
diff --git a/crates/diesel_models/src/query/capture.rs b/crates/diesel_models/src/query/capture.rs
index 552f096bc8..52a9800cb8 100644
--- a/crates/diesel_models/src/query/capture.rs
+++ b/crates/diesel_models/src/query/capture.rs
@@ -7,17 +7,17 @@ use crate::{
capture::{Capture, CaptureNew, CaptureUpdate, CaptureUpdateInternal},
errors, kv,
schema::captures::dsl,
- PgPooledConn, StorageResult,
+ DatabaseConnectionWithContext, StorageResult,
};
impl CaptureNew {
- pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Capture> {
+ pub async fn insert(self, conn: &DatabaseConnectionWithContext<'_>) -> StorageResult<Capture> {
generics::generic_insert(conn, self).await
}
pub async fn generate_drainer_insert_query(
self,
- conn: &mut PgPooledConn,
+ conn: &mut DatabaseConnectionWithContext<'_>,
) -> StorageResult<kv::SerializableQuery> {
kv::generate_insert_query(conn, self)
.await
@@ -26,7 +26,10 @@ impl CaptureNew {
}
impl Capture {
- pub async fn find_by_capture_id(conn: &PgPooledConn, capture_id: &str) -> StorageResult<Self> {
+ pub async fn find_by_capture_id(
+ conn: &DatabaseConnectionWithContext<'_>,
+ capture_id: &str,
+ ) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::capture_id.eq(capture_id.to_owned()),
@@ -36,7 +39,7 @@ impl Capture {
pub async fn update_with_capture_id(
self,
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
capture: CaptureUpdate,
) -> StorageResult<Self> {
match generics::generic_update_with_unique_predicate_get_result::<
@@ -63,7 +66,7 @@ impl Capture {
merchant_id: &common_utils::id_type::MerchantId,
payment_id: &common_utils::id_type::PaymentId,
authorized_attempt_id: &str,
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
conn,
@@ -101,7 +104,7 @@ impl ConnectorTransactionIdTrait for Capture {
impl CaptureUpdate {
pub async fn generate_drainer_update_query(
self,
- conn: &mut PgPooledConn,
+ conn: &mut DatabaseConnectionWithContext<'_>,
capture_id: String,
) -> StorageResult<kv::SerializableQuery> {
kv::generate_update_query_by_id::<<Capture as HasTable>::Table, _, _>(
diff --git a/crates/diesel_models/src/query/card_issuer.rs b/crates/diesel_models/src/query/card_issuer.rs
index 48cd5e8f03..e7c43b8c36 100644
--- a/crates/diesel_models/src/query/card_issuer.rs
+++ b/crates/diesel_models/src/query/card_issuer.rs
@@ -5,12 +5,12 @@ use super::generics;
use crate::{
card_issuer::{CardIssuer, NewCardIssuer, UpdateCardIssuer},
schema::card_issuers::dsl,
- PgPooledConn, StorageResult,
+ DatabaseConnectionWithContext, StorageResult,
};
impl CardIssuer {
pub async fn list_filtered(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
query: Option<String>,
limit: Option<i64>,
) -> StorageResult<Vec<Self>> {
@@ -26,7 +26,7 @@ impl CardIssuer {
}
pub async fn find_by_ids(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
ids: Vec<id_type::CardIssuerId>,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<
@@ -39,7 +39,7 @@ impl CardIssuer {
}
pub async fn update(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
id: id_type::CardIssuerId,
data: UpdateCardIssuer,
) -> StorageResult<Self> {
@@ -47,7 +47,7 @@ impl CardIssuer {
}
pub async fn delete_by_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
id: id_type::CardIssuerId,
) -> StorageResult<bool> {
generics::generic_delete::<<Self as HasTable>::Table, _>(conn, dsl::id.eq(id)).await
@@ -55,7 +55,10 @@ impl CardIssuer {
}
impl NewCardIssuer {
- pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<CardIssuer> {
+ pub async fn insert(
+ self,
+ conn: &DatabaseConnectionWithContext<'_>,
+ ) -> StorageResult<CardIssuer> {
generics::generic_insert(conn, self).await
}
}
diff --git a/crates/diesel_models/src/query/cards_info.rs b/crates/diesel_models/src/query/cards_info.rs
index 0699f318d9..d87b9f3bff 100644
--- a/crates/diesel_models/src/query/cards_info.rs
+++ b/crates/diesel_models/src/query/cards_info.rs
@@ -6,22 +6,25 @@ use crate::{
errors,
query::generics,
schema::cards_info::dsl,
- PgPooledConn, StorageResult,
+ DatabaseConnectionWithContext, StorageResult,
};
impl CardInfo {
- pub async fn find_by_iin(conn: &PgPooledConn, card_iin: &str) -> StorageResult<Option<Self>> {
+ pub async fn find_by_iin(
+ conn: &DatabaseConnectionWithContext<'_>,
+ card_iin: &str,
+ ) -> StorageResult<Option<Self>> {
generics::generic_find_by_id_optional::<<Self as HasTable>::Table, _, _>(
conn,
card_iin.to_owned(),
)
.await
}
- pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Self> {
+ pub async fn insert(self, conn: &DatabaseConnectionWithContext<'_>) -> StorageResult<Self> {
generics::generic_insert(conn, self).await
}
pub async fn update(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
card_iin: String,
data: UpdateCardInfo,
) -> StorageResult<Self> {
diff --git a/crates/diesel_models/src/query/configs.rs b/crates/diesel_models/src/query/configs.rs
index b7745b3187..9850ee2e41 100644
--- a/crates/diesel_models/src/query/configs.rs
+++ b/crates/diesel_models/src/query/configs.rs
@@ -5,22 +5,25 @@ use crate::{
configs::{Config, ConfigNew, ConfigUpdate, ConfigUpdateInternal},
errors,
schema::configs::dsl,
- PgPooledConn, StorageResult,
+ DatabaseConnectionWithContext, StorageResult,
};
impl ConfigNew {
- pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Config> {
+ pub async fn insert(self, conn: &DatabaseConnectionWithContext<'_>) -> StorageResult<Config> {
generics::generic_insert(conn, self).await
}
}
impl Config {
- pub async fn find_by_key(conn: &PgPooledConn, key: &str) -> StorageResult<Self> {
+ pub async fn find_by_key(
+ conn: &DatabaseConnectionWithContext<'_>,
+ key: &str,
+ ) -> StorageResult<Self> {
generics::generic_find_by_id::<<Self as HasTable>::Table, _, _>(conn, key.to_owned()).await
}
pub async fn update_by_key(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
key: &str,
config_update: ConfigUpdate,
) -> StorageResult<Self> {
@@ -45,7 +48,10 @@ impl Config {
}
}
- pub async fn delete_by_key(conn: &PgPooledConn, key: &str) -> StorageResult<Self> {
+ pub async fn delete_by_key(
+ conn: &DatabaseConnectionWithContext<'_>,
+ key: &str,
+ ) -> StorageResult<Self> {
generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>(
conn,
dsl::key.eq(key.to_owned()),
diff --git a/crates/diesel_models/src/query/connector_response.rs b/crates/diesel_models/src/query/connector_response.rs
index c60a67a2fa..e3df6252c1 100644
--- a/crates/diesel_models/src/query/connector_response.rs
+++ b/crates/diesel_models/src/query/connector_response.rs
@@ -10,12 +10,12 @@ use crate::{
errors,
payment_attempt::{PaymentAttempt, PaymentAttemptUpdate, PaymentAttemptUpdateInternal},
schema::{connector_response::dsl, payment_attempt::dsl as pa_dsl},
- PgPooledConn, StorageResult,
+ DatabaseConnectionWithContext, StorageResult,
};
impl ConnectorResponseNew {
#[instrument(skip(conn))]
- pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<ConnectorResponse> {
+ pub async fn insert(self, conn: &DatabaseConnectionWithContext<'_>) -> StorageResult<ConnectorResponse> {
let payment_attempt_update = PaymentAttemptUpdate::ConnectorResponse {
authentication_data: self.authentication_data.clone(),
encoded_data: self.encoded_data.clone(),
@@ -54,7 +54,7 @@ impl ConnectorResponse {
#[instrument(skip(conn))]
pub async fn update(
self,
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
connector_response: ConnectorResponseUpdate,
) -> StorageResult<Self> {
let payment_attempt_update = match connector_response.clone() {
@@ -135,7 +135,7 @@ impl ConnectorResponse {
#[instrument(skip(conn))]
pub async fn find_by_payment_id_merchant_id_attempt_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
payment_id: &common_utils::id_type::PaymentId,
merchant_id: &common_utils::id_type::MerchantId,
attempt_id: &str,
diff --git a/crates/diesel_models/src/query/customers.rs b/crates/diesel_models/src/query/customers.rs
index 7e121bd518..76e50fd84e 100644
--- a/crates/diesel_models/src/query/customers.rs
+++ b/crates/diesel_models/src/query/customers.rs
@@ -17,17 +17,17 @@ use crate::schema::customers::dsl;
use crate::schema_v2::customers::dsl;
use crate::{
customers::{Customer, CustomerNew, CustomerUpdateInternal},
- errors, kv, PgPooledConn, StorageResult,
+ errors, kv, DatabaseConnectionWithContext, StorageResult,
};
impl CustomerNew {
- pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Customer> {
+ pub async fn insert(self, conn: &DatabaseConnectionWithContext<'_>) -> StorageResult<Customer> {
generics::generic_insert(conn, self).await
}
pub async fn generate_drainer_insert_query(
self,
- conn: &mut PgPooledConn,
+ conn: &mut DatabaseConnectionWithContext<'_>,
) -> StorageResult<kv::SerializableQuery> {
kv::generate_insert_query(conn, self)
.await
@@ -45,7 +45,7 @@ pub struct CustomerListConstraints {
impl Customer {
#[cfg(feature = "v2")]
pub async fn find_by_merchant_id_customer_id_for_global_id_migration(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &id_type::MerchantId,
customer_id: &id_type::CustomerId,
) -> StorageResult<CustomerGlobalIdMigrationRow> {
@@ -62,7 +62,7 @@ impl Customer {
));
match query
- .first_async::<CustomerGlobalIdMigrationRow>(conn)
+ .first_async::<CustomerGlobalIdMigrationRow>(conn.raw_connection())
.await
{
Ok(row) => Ok(row),
@@ -76,7 +76,7 @@ impl Customer {
#[cfg(feature = "v2")]
pub async fn update_global_id_for_migration(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &id_type::MerchantId,
customer_id: &id_type::CustomerId,
new_id: id_type::GlobalCustomerId,
@@ -98,7 +98,7 @@ impl Customer {
));
match query
- .get_result_async::<CustomerGlobalIdMigrationRow>(conn)
+ .get_result_async::<CustomerGlobalIdMigrationRow>(conn.raw_connection())
.await
{
Ok(row) => Ok(row),
@@ -112,7 +112,7 @@ impl Customer {
#[cfg(feature = "v2")]
pub async fn update_by_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
id: id_type::GlobalCustomerId,
customer: CustomerUpdateInternal,
) -> StorageResult<Self> {
@@ -135,7 +135,7 @@ impl Customer {
#[cfg(feature = "v2")]
pub async fn find_by_global_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
id: &id_type::GlobalCustomerId,
) -> StorageResult<Self> {
generics::generic_find_by_id::<<Self as HasTable>::Table, _, _>(conn, id.to_owned()).await
@@ -143,7 +143,7 @@ impl Customer {
#[cfg(feature = "v2")]
pub async fn find_by_global_id_merchant_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
id: &id_type::GlobalCustomerId,
merchant_id: &id_type::MerchantId,
) -> StorageResult<Self> {
@@ -158,7 +158,7 @@ impl Customer {
#[cfg(feature = "v1")]
pub async fn get_customer_count_by_merchant_id_and_constraints(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &id_type::MerchantId,
customer_list_constraints: CustomerListConstraints,
) -> StorageResult<usize> {
@@ -188,7 +188,7 @@ impl Customer {
#[cfg(feature = "v2")]
pub async fn get_customer_count_by_merchant_id_and_constraints(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &id_type::MerchantId,
customer_list_constraints: CustomerListConstraints,
) -> StorageResult<usize> {
@@ -218,7 +218,7 @@ impl Customer {
#[cfg(feature = "v1")]
pub async fn list_customers_by_merchant_id_and_constraints(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &id_type::MerchantId,
constraints: CustomerListConstraints,
) -> StorageResult<Vec<Self>> {
@@ -266,7 +266,7 @@ impl Customer {
#[cfg(feature = "v2")]
pub async fn list_customers_by_merchant_id_and_constraints(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &id_type::MerchantId,
constraints: CustomerListConstraints,
) -> StorageResult<Vec<Self>> {
@@ -314,7 +314,7 @@ impl Customer {
#[cfg(feature = "v2")]
pub async fn find_optional_by_merchant_id_merchant_reference_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
) -> StorageResult<Option<Self>> {
@@ -329,7 +329,7 @@ impl Customer {
#[cfg(feature = "v1")]
pub async fn find_optional_by_customer_id_merchant_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
) -> StorageResult<Option<Self>> {
@@ -342,7 +342,7 @@ impl Customer {
#[cfg(feature = "v1")]
pub async fn update_by_customer_id_merchant_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
customer_id: id_type::CustomerId,
merchant_id: id_type::MerchantId,
customer: CustomerUpdateInternal,
@@ -370,7 +370,7 @@ impl Customer {
#[cfg(feature = "v1")]
pub async fn delete_by_customer_id_merchant_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
) -> StorageResult<bool> {
@@ -385,7 +385,7 @@ impl Customer {
#[cfg(feature = "v2")]
pub async fn find_by_merchant_reference_id_merchant_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_reference_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
) -> StorageResult<Self> {
@@ -400,7 +400,7 @@ impl Customer {
#[cfg(feature = "v1")]
pub async fn find_by_customer_id_merchant_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
) -> StorageResult<Self> {
@@ -416,7 +416,7 @@ impl CustomerUpdateInternal {
#[cfg(feature = "v1")]
pub async fn generate_drainer_update_query(
self,
- conn: &mut PgPooledConn,
+ conn: &mut DatabaseConnectionWithContext<'_>,
customer_id: id_type::CustomerId,
merchant_id: id_type::MerchantId,
) -> StorageResult<kv::SerializableQuery> {
@@ -432,7 +432,7 @@ impl CustomerUpdateInternal {
#[cfg(feature = "v2")]
pub async fn generate_drainer_update_query(
self,
- conn: &mut PgPooledConn,
+ conn: &mut DatabaseConnectionWithContext<'_>,
id: id_type::GlobalCustomerId,
) -> StorageResult<kv::SerializableQuery> {
kv::generate_update_query_by_id::<<Customer as HasTable>::Table, _, _>(conn, id, self)
diff --git a/crates/diesel_models/src/query/dashboard_metadata.rs b/crates/diesel_models/src/query/dashboard_metadata.rs
index 8d39618134..6d70ccba45 100644
--- a/crates/diesel_models/src/query/dashboard_metadata.rs
+++ b/crates/diesel_models/src/query/dashboard_metadata.rs
@@ -10,7 +10,7 @@ use crate::{
DashboardMetadata, DashboardMetadataNew, DashboardMetadataUpdate,
DashboardMetadataUpdateInternal,
},
- PgPooledConn, StorageResult,
+ DatabaseConnectionWithContext, StorageResult,
};
macro_rules! dashboard_metadata_filter {
@@ -57,14 +57,17 @@ macro_rules! dashboard_metadata_filter {
}
impl DashboardMetadataNew {
- pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<DashboardMetadata> {
+ pub async fn insert(
+ self,
+ conn: &DatabaseConnectionWithContext<'_>,
+ ) -> StorageResult<DashboardMetadata> {
generics::generic_insert(conn, self).await
}
}
impl DashboardMetadata {
pub async fn update(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
user_id: Option<String>,
merchant_id: id_type::MerchantId,
org_id: id_type::OrganizationId,
@@ -99,7 +102,7 @@ impl DashboardMetadata {
}
pub async fn find_user_scoped_dashboard_metadata(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
user_id: String,
merchant_id: id_type::MerchantId,
org_id: id_type::OrganizationId,
@@ -122,7 +125,7 @@ impl DashboardMetadata {
}
pub async fn find_merchant_scoped_dashboard_metadata(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: id_type::MerchantId,
org_id: id_type::OrganizationId,
data_types: Vec<enums::DashboardMetadata>,
@@ -143,7 +146,7 @@ impl DashboardMetadata {
}
pub async fn find_dashboard_metadata_by_user_merchant_org_profile_key(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
user_id: String,
merchant_id: id_type::MerchantId,
org_id: id_type::OrganizationId,
@@ -167,7 +170,7 @@ impl DashboardMetadata {
}
pub async fn delete_all_user_scoped_dashboard_metadata_by_merchant_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
user_id: String,
merchant_id: id_type::MerchantId,
) -> StorageResult<bool> {
@@ -181,7 +184,7 @@ impl DashboardMetadata {
}
pub async fn delete_user_scoped_dashboard_metadata_by_merchant_id_data_key(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
user_id: String,
merchant_id: id_type::MerchantId,
data_key: enums::DashboardMetadata,
@@ -197,7 +200,7 @@ impl DashboardMetadata {
}
pub async fn delete_all_by_user_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
user_id: String,
) -> StorageResult<bool> {
match generics::generic_delete::<<Self as HasTable>::Table, _>(
diff --git a/crates/diesel_models/src/query/dispute.rs b/crates/diesel_models/src/query/dispute.rs
index ce4861e54f..7a9f6ee627 100644
--- a/crates/diesel_models/src/query/dispute.rs
+++ b/crates/diesel_models/src/query/dispute.rs
@@ -6,17 +6,17 @@ use crate::{
dispute::{Dispute, DisputeNew, DisputeUpdate, DisputeUpdateInternal},
errors, kv,
schema::dispute::dsl,
- PgPooledConn, StorageResult,
+ DatabaseConnectionWithContext, StorageResult,
};
impl DisputeNew {
- pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Dispute> {
+ pub async fn insert(self, conn: &DatabaseConnectionWithContext<'_>) -> StorageResult<Dispute> {
generics::generic_insert(conn, self).await
}
pub async fn generate_drainer_insert_query(
self,
- conn: &mut PgPooledConn,
+ conn: &mut DatabaseConnectionWithContext<'_>,
) -> StorageResult<kv::SerializableQuery> {
kv::generate_insert_query(conn, self)
.await
@@ -26,7 +26,7 @@ impl DisputeNew {
impl Dispute {
pub async fn find_optional_by_processor_merchant_id_payment_id_connector_dispute_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
processor_merchant_id: &common_utils::id_type::MerchantId,
payment_id: &common_utils::id_type::PaymentId,
connector_dispute_id: &str,
@@ -42,7 +42,7 @@ impl Dispute {
}
pub async fn find_by_processor_merchant_id_dispute_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
processor_merchant_id: &common_utils::id_type::MerchantId,
dispute_id: &str,
) -> StorageResult<Self> {
@@ -56,7 +56,7 @@ impl Dispute {
}
pub async fn find_by_processor_merchant_id_payment_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
processor_merchant_id: &common_utils::id_type::MerchantId,
payment_id: &common_utils::id_type::PaymentId,
) -> StorageResult<Vec<Self>> {
@@ -82,7 +82,7 @@ impl Dispute {
// Fallback function for stagger release - finds by merchant_id when processor_merchant_id is NULL
pub async fn find_optional_by_merchant_id_payment_id_connector_dispute_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
processor_merchant_id: &common_utils::id_type::MerchantId,
payment_id: &common_utils::id_type::PaymentId,
connector_dispute_id: &str,
@@ -99,7 +99,7 @@ impl Dispute {
// Fallback function for stagger release - finds by merchant_id when processor_merchant_id is NULL
pub async fn find_by_merchant_id_dispute_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
processor_merchant_id: &common_utils::id_type::MerchantId,
dispute_id: &str,
) -> StorageResult<Self> {
@@ -114,7 +114,7 @@ impl Dispute {
// Fallback function for stagger release - finds by merchant_id when processor_merchant_id is NULL
pub async fn find_by_merchant_id_payment_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
processor_merchant_id: &common_utils::id_type::MerchantId,
payment_id: &common_utils::id_type::PaymentId,
) -> StorageResult<Vec<Self>> {
@@ -135,7 +135,11 @@ impl Dispute {
.await
}
- pub async fn update(self, conn: &PgPooledConn, dispute: DisputeUpdate) -> StorageResult<Self> {
+ pub async fn update(
+ self,
+ conn: &DatabaseConnectionWithContext<'_>,
+ dispute: DisputeUpdate,
+ ) -> StorageResult<Self> {
match generics::generic_update_with_unique_predicate_get_result::<
<Self as HasTable>::Table,
_,
@@ -160,7 +164,7 @@ impl Dispute {
impl DisputeUpdateInternal {
pub async fn generate_drainer_update_query(
self,
- conn: &mut PgPooledConn,
+ conn: &mut DatabaseConnectionWithContext<'_>,
dispute_id: String,
) -> StorageResult<kv::SerializableQuery> {
kv::generate_update_query_with_predicate::<<Dispute as HasTable>::Table, _, _>(
diff --git a/crates/diesel_models/src/query/dynamic_routing_stats.rs b/crates/diesel_models/src/query/dynamic_routing_stats.rs
index bf4cd706a6..43620e12a8 100644
--- a/crates/diesel_models/src/query/dynamic_routing_stats.rs
+++ b/crates/diesel_models/src/query/dynamic_routing_stats.rs
@@ -8,18 +8,21 @@ use crate::{
},
errors,
schema::dynamic_routing_stats::dsl,
- PgPooledConn, StorageResult,
+ DatabaseConnectionWithContext, StorageResult,
};
impl DynamicRoutingStatsNew {
- pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<DynamicRoutingStats> {
+ pub async fn insert(
+ self,
+ conn: &DatabaseConnectionWithContext<'_>,
+ ) -> StorageResult<DynamicRoutingStats> {
generics::generic_insert(conn, self).await
}
}
impl DynamicRoutingStats {
pub async fn find_optional_by_attempt_id_merchant_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
attempt_id: String,
merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Option<Self>> {
@@ -33,7 +36,7 @@ impl DynamicRoutingStats {
}
pub async fn update(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
attempt_id: String,
merchant_id: &common_utils::id_type::MerchantId,
dynamic_routing_stat: DynamicRoutingStatsUpdate,
diff --git a/crates/diesel_models/src/query/events.rs b/crates/diesel_models/src/query/events.rs
index 91ded0bd29..bc54200535 100644
--- a/crates/diesel_models/src/query/events.rs
+++ b/crates/diesel_models/src/query/events.rs
@@ -16,17 +16,20 @@ use crate::{
errors::DatabaseError,
events::{Event, EventNew, EventUpdateInternal},
schema::events::dsl,
- PgPooledConn, StorageResult,
+ DatabaseConnectionWithContext, StorageResult,
};
impl EventNew {
- pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Event> {
+ pub async fn insert(self, conn: &DatabaseConnectionWithContext<'_>) -> StorageResult<Event> {
generics::generic_insert(conn, self).await
}
}
impl Event {
- pub async fn find_by_event_id(conn: &PgPooledConn, event_id: &str) -> StorageResult<Self> {
+ pub async fn find_by_event_id(
+ conn: &DatabaseConnectionWithContext<'_>,
+ event_id: &str,
+ ) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::event_id.eq(event_id.to_owned()),
@@ -35,7 +38,7 @@ impl Event {
}
pub async fn find_by_merchant_id_event_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
event_id: &str,
) -> StorageResult<Self> {
@@ -49,7 +52,7 @@ impl Event {
}
pub async fn find_by_merchant_id_idempotent_event_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
idempotent_event_id: &str,
) -> StorageResult<Self> {
@@ -63,7 +66,7 @@ impl Event {
}
pub async fn find_by_initiator_merchant_id_idempotent_event_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
initiator_merchant_id: &common_utils::id_type::MerchantId,
idempotent_event_id: &str,
) -> StorageResult<Self> {
@@ -85,7 +88,7 @@ impl Event {
}
pub async fn list_initial_attempts_by_merchant_id_primary_object_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
primary_object_id: &str,
event_recipient: Option<common_enums::EventRecipient>,
@@ -106,14 +109,19 @@ impl Event {
logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());
- track_database_call::<Self, _, _>(query.get_results_async(conn), DatabaseOperation::Filter)
- .await
- .change_context(DatabaseError::Others) // Query returns empty Vec when no records are found
- .attach_printable("Error filtering events by constraints")
+ track_database_call::<Self, _, _>(
+ conn.request_id(),
+ conn.event_emitter(),
+ DatabaseOperation::Filter,
+ query.get_results_async(conn.raw_connection()),
+ )
+ .await
+ .change_context(DatabaseError::Others) // Query returns empty Vec when no records are found
+ .attach_printable("Error filtering events by constraints")
}
pub async fn find_initial_attempt_by_merchant_id_initial_attempt_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
initial_attempt_id: &str,
) -> StorageResult<Option<Self>> {
@@ -135,7 +143,7 @@ impl Event {
#[allow(clippy::too_many_arguments)]
pub async fn list_initial_attempts_by_merchant_id_constraints(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
created_after: time::PrimitiveDateTime,
created_before: time::PrimitiveDateTime,
@@ -169,14 +177,19 @@ impl Event {
logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());
- track_database_call::<Self, _, _>(query.get_results_async(conn), DatabaseOperation::Filter)
- .await
- .change_context(DatabaseError::Others) // Query returns empty Vec when no records are found
- .attach_printable("Error filtering events by constraints")
+ track_database_call::<Self, _, _>(
+ conn.request_id(),
+ conn.event_emitter(),
+ DatabaseOperation::Filter,
+ query.get_results_async(conn.raw_connection()),
+ )
+ .await
+ .change_context(DatabaseError::Others) // Query returns empty Vec when no records are found
+ .attach_printable("Error filtering events by constraints")
}
pub async fn list_by_merchant_id_initial_attempt_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
initial_attempt_id: &str,
event_recipient: Option<common_enums::EventRecipient>,
@@ -195,14 +208,19 @@ impl Event {
logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());
- track_database_call::<Self, _, _>(query.get_results_async(conn), DatabaseOperation::Filter)
- .await
- .change_context(DatabaseError::Others) // Query returns empty Vec when no records are found
- .attach_printable("Error filtering events by constraints")
+ track_database_call::<Self, _, _>(
+ conn.request_id(),
+ conn.event_emitter(),
+ DatabaseOperation::Filter,
+ query.get_results_async(conn.raw_connection()),
+ )
+ .await
+ .change_context(DatabaseError::Others) // Query returns empty Vec when no records are found
+ .attach_printable("Error filtering events by constraints")
}
pub async fn list_initial_attempts_by_initiator_merchant_id_primary_object_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
initiator_merchant_id: &common_utils::id_type::MerchantId,
primary_object_id: &str,
profile_id: Option<common_utils::id_type::ProfileId>,
@@ -238,17 +256,22 @@ impl Event {
logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());
- track_database_call::<Self, _, _>(query.get_results_async(conn), DatabaseOperation::Filter)
- .await
- .change_context(DatabaseError::Others)
- .attach_printable(
- "Error filtering initial events by initiator merchant ID and primary object ID",
- )
+ track_database_call::<Self, _, _>(
+ conn.request_id(),
+ conn.event_emitter(),
+ DatabaseOperation::Filter,
+ query.get_results_async(conn.raw_connection()),
+ )
+ .await
+ .change_context(DatabaseError::Others)
+ .attach_printable(
+ "Error filtering initial events by initiator merchant ID and primary object ID",
+ )
}
#[allow(clippy::too_many_arguments)]
pub async fn list_initial_attempts_by_initiator_merchant_id_constraints(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
initiator_merchant_id: &common_utils::id_type::MerchantId,
created_after: time::PrimitiveDateTime,
created_before: time::PrimitiveDateTime,
@@ -292,14 +315,19 @@ impl Event {
logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());
- track_database_call::<Self, _, _>(query.get_results_async(conn), DatabaseOperation::Filter)
- .await
- .change_context(DatabaseError::Others) // Query returns empty Vec when no records are found
- .attach_printable("Error filtering events by constraints")
+ track_database_call::<Self, _, _>(
+ conn.request_id(),
+ conn.event_emitter(),
+ DatabaseOperation::Filter,
+ query.get_results_async(conn.raw_connection()),
+ )
+ .await
+ .change_context(DatabaseError::Others) // Query returns empty Vec when no records are found
+ .attach_printable("Error filtering events by constraints")
}
pub async fn list_by_initiator_merchant_id_initial_attempt_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
initial_attempt_id: &str,
initiator_merchant_id: &common_utils::id_type::MerchantId,
event_recipient: Option<common_enums::EventRecipient>,
@@ -327,14 +355,19 @@ impl Event {
logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());
- track_database_call::<Self, _, _>(query.get_results_async(conn), DatabaseOperation::Filter)
- .await
- .change_context(DatabaseError::Others) // Query returns empty Vec when no records are found
- .attach_printable("Error filtering events by constraints")
+ track_database_call::<Self, _, _>(
+ conn.request_id(),
+ conn.event_emitter(),
+ DatabaseOperation::Filter,
+ query.get_results_async(conn.raw_connection()),
+ )
+ .await
+ .change_context(DatabaseError::Others) // Query returns empty Vec when no records are found
+ .attach_printable("Error filtering events by constraints")
}
pub async fn list_initial_attempts_by_profile_id_primary_object_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
profile_id: &common_utils::id_type::ProfileId,
primary_object_id: &str,
event_recipient: Option<common_enums::EventRecipient>,
@@ -355,14 +388,19 @@ impl Event {
logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());
- track_database_call::<Self, _, _>(query.get_results_async(conn), DatabaseOperation::Filter)
- .await
- .change_context(DatabaseError::Others) // Query returns empty Vec when no records are found
- .attach_printable("Error filtering events by constraints")
+ track_database_call::<Self, _, _>(
+ conn.request_id(),
+ conn.event_emitter(),
+ DatabaseOperation::Filter,
+ query.get_results_async(conn.raw_connection()),
+ )
+ .await
+ .change_context(DatabaseError::Others) // Query returns empty Vec when no records are found
+ .attach_printable("Error filtering events by constraints")
}
pub async fn find_initial_attempt_by_profile_id_initial_attempt_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
profile_id: &common_utils::id_type::ProfileId,
initial_attempt_id: &str,
) -> StorageResult<Option<Self>> {
@@ -384,7 +422,7 @@ impl Event {
#[allow(clippy::too_many_arguments)]
pub async fn list_initial_attempts_by_profile_id_constraints(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
profile_id: &common_utils::id_type::ProfileId,
created_after: time::PrimitiveDateTime,
created_before: time::PrimitiveDateTime,
@@ -418,14 +456,19 @@ impl Event {
logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());
- track_database_call::<Self, _, _>(query.get_results_async(conn), DatabaseOperation::Filter)
- .await
- .change_context(DatabaseError::Others) // Query returns empty Vec when no records are found
- .attach_printable("Error filtering events by constraints")
+ track_database_call::<Self, _, _>(
+ conn.request_id(),
+ conn.event_emitter(),
+ DatabaseOperation::Filter,
+ query.get_results_async(conn.raw_connection()),
+ )
+ .await
+ .change_context(DatabaseError::Others) // Query returns empty Vec when no records are found
+ .attach_printable("Error filtering events by constraints")
}
pub async fn list_by_profile_id_initial_attempt_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
profile_id: &common_utils::id_type::ProfileId,
initial_attempt_id: &str,
) -> StorageResult<Vec<Self>> {
@@ -442,7 +485,7 @@ impl Event {
}
pub async fn update_by_event_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
event_id: &str,
event: EventUpdateInternal,
) -> StorageResult<Self> {
@@ -456,7 +499,7 @@ impl Event {
}
pub async fn update_by_merchant_id_event_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
event_id: &str,
event: EventUpdateInternal,
@@ -594,7 +637,7 @@ impl Event {
#[allow(clippy::too_many_arguments)]
pub async fn count_initial_attempts_by_constraints(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
profile_id: Option<common_utils::id_type::ProfileId>,
created_after: time::PrimitiveDateTime,
@@ -626,8 +669,10 @@ impl Event {
logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());
track_database_call::<Self, _, _>(
- query.get_result_async::<i64>(conn),
+ conn.request_id(),
+ conn.event_emitter(),
DatabaseOperation::Count,
+ query.get_result_async::<i64>(conn.raw_connection()),
)
.await
.change_context(DatabaseError::Others)
@@ -635,7 +680,7 @@ impl Event {
}
pub async fn count_initial_attempts_by_profile_id_constraints(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
profile_id: &common_utils::id_type::ProfileId,
created_after: time::PrimitiveDateTime,
created_before: time::PrimitiveDateTime,
@@ -666,8 +711,10 @@ impl Event {
logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());
track_database_call::<Self, _, _>(
- query.get_result_async::<i64>(conn),
+ conn.request_id(),
+ conn.event_emitter(),
DatabaseOperation::Count,
+ query.get_result_async::<i64>(conn.raw_connection()),
)
.await
.change_context(DatabaseError::Others)
@@ -676,7 +723,7 @@ impl Event {
#[allow(clippy::too_many_arguments)]
pub async fn count_initial_attempts_by_initiator_merchant_id_constraints(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
initiator_merchant_id: &common_utils::id_type::MerchantId,
profile_id: Option<common_utils::id_type::ProfileId>,
created_after: time::PrimitiveDateTime,
@@ -718,8 +765,10 @@ impl Event {
logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());
track_database_call::<Self, _, _>(
- query.get_result_async::<i64>(conn),
+ conn.request_id(),
+ conn.event_emitter(),
DatabaseOperation::Count,
+ query.get_result_async::<i64>(conn.raw_connection()),
)
.await
.change_context(DatabaseError::Others)
diff --git a/crates/diesel_models/src/query/file.rs b/crates/diesel_models/src/query/file.rs
index b970bb97d8..41084571fd 100644
--- a/crates/diesel_models/src/query/file.rs
+++ b/crates/diesel_models/src/query/file.rs
@@ -5,18 +5,21 @@ use crate::{
errors,
file::{FileMetadata, FileMetadataNew, FileMetadataUpdate, FileMetadataUpdateInternal},
schema::file_metadata::dsl,
- PgPooledConn, StorageResult,
+ DatabaseConnectionWithContext, StorageResult,
};
impl FileMetadataNew {
- pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<FileMetadata> {
+ pub async fn insert(
+ self,
+ conn: &DatabaseConnectionWithContext<'_>,
+ ) -> StorageResult<FileMetadata> {
generics::generic_insert(conn, self).await
}
}
impl FileMetadata {
pub async fn find_by_processor_merchant_id_file_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
processor_merchant_id: &common_utils::id_type::MerchantId,
file_id: &str,
) -> StorageResult<Self> {
@@ -31,7 +34,7 @@ impl FileMetadata {
// Fallback function for stagger release - finds by merchant_id when processor_merchant_id is NULL
pub async fn find_by_merchant_id_file_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
processor_merchant_id: &common_utils::id_type::MerchantId,
file_id: &str,
) -> StorageResult<Self> {
@@ -45,7 +48,7 @@ impl FileMetadata {
}
pub async fn delete_by_processor_merchant_id_file_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
processor_merchant_id: &common_utils::id_type::MerchantId,
file_id: &str,
) -> StorageResult<bool> {
@@ -60,7 +63,7 @@ impl FileMetadata {
// Fallback function for stagger release - deletes by merchant_id when processor_merchant_id is NULL
pub async fn delete_by_merchant_id_file_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
processor_merchant_id: &common_utils::id_type::MerchantId,
file_id: &str,
) -> StorageResult<bool> {
@@ -75,7 +78,7 @@ impl FileMetadata {
pub async fn update(
self,
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
file_metadata: FileMetadataUpdate,
) -> StorageResult<Self> {
match generics::generic_update_with_unique_predicate_get_result::<
diff --git a/crates/diesel_models/src/query/fraud_check.rs b/crates/diesel_models/src/query/fraud_check.rs
index b60c078d75..0cc85c19c0 100644
--- a/crates/diesel_models/src/query/fraud_check.rs
+++ b/crates/diesel_models/src/query/fraud_check.rs
@@ -1,11 +1,15 @@
use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods};
use crate::{
- errors, fraud_check::*, query::generics, schema::fraud_check::dsl, PgPooledConn, StorageResult,
+ errors, fraud_check::*, query::generics, schema::fraud_check::dsl,
+ DatabaseConnectionWithContext, StorageResult,
};
impl FraudCheckNew {
- pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<FraudCheck> {
+ pub async fn insert(
+ self,
+ conn: &DatabaseConnectionWithContext<'_>,
+ ) -> StorageResult<FraudCheck> {
generics::generic_insert(conn, self).await
}
}
@@ -13,7 +17,7 @@ impl FraudCheckNew {
impl FraudCheck {
pub async fn update_with_attempt_id(
self,
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
fraud_check: FraudCheckUpdate,
) -> StorageResult<Self> {
match generics::generic_update_with_unique_predicate_get_result::<
@@ -39,7 +43,7 @@ impl FraudCheck {
}
pub async fn get_with_payment_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
payment_id: common_utils::id_type::PaymentId,
merchant_id: common_utils::id_type::MerchantId,
) -> StorageResult<Self> {
@@ -53,7 +57,7 @@ impl FraudCheck {
}
pub async fn get_with_payment_id_if_present(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
payment_id: common_utils::id_type::PaymentId,
merchant_id: common_utils::id_type::MerchantId,
) -> StorageResult<Option<Self>> {
diff --git a/crates/diesel_models/src/query/generic_link.rs b/crates/diesel_models/src/query/generic_link.rs
index 96966e1454..5bca744236 100644
--- a/crates/diesel_models/src/query/generic_link.rs
+++ b/crates/diesel_models/src/query/generic_link.rs
@@ -10,11 +10,14 @@ use crate::{
PaymentMethodCollectLink, PayoutLink, PayoutLinkUpdate,
},
schema::generic_link::dsl,
- PgPooledConn, StorageResult,
+ DatabaseConnectionWithContext, StorageResult,
};
impl GenericLinkNew {
- pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<GenericLinkState> {
+ pub async fn insert(
+ self,
+ conn: &DatabaseConnectionWithContext<'_>,
+ ) -> StorageResult<GenericLinkState> {
generics::generic_insert(conn, self)
.await
.and_then(|res: GenericLink| {
@@ -26,7 +29,7 @@ impl GenericLinkNew {
pub async fn insert_pm_collect_link(
self,
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
) -> StorageResult<PaymentMethodCollectLink> {
generics::generic_insert(conn, self)
.await
@@ -37,7 +40,10 @@ impl GenericLinkNew {
})
}
- pub async fn insert_payout_link(self, conn: &PgPooledConn) -> StorageResult<PayoutLink> {
+ pub async fn insert_payout_link(
+ self,
+ conn: &DatabaseConnectionWithContext<'_>,
+ ) -> StorageResult<PayoutLink> {
generics::generic_insert(conn, self)
.await
.and_then(|res: GenericLink| {
@@ -50,7 +56,7 @@ impl GenericLinkNew {
impl GenericLink {
pub async fn find_generic_link_by_link_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
link_id: &str,
) -> StorageResult<GenericLinkState> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
@@ -66,7 +72,7 @@ impl GenericLink {
}
pub async fn find_pm_collect_link_by_link_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
link_id: &str,
) -> StorageResult<PaymentMethodCollectLink> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
@@ -82,7 +88,7 @@ impl GenericLink {
}
pub async fn find_payout_link_by_link_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
link_id: &str,
) -> StorageResult<PayoutLink> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
@@ -101,7 +107,7 @@ impl GenericLink {
impl PayoutLink {
pub async fn update_payout_link(
self,
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
payout_link_update: PayoutLinkUpdate,
) -> StorageResult<Self> {
generics::generic_update_with_results::<<Self as HasTable>::Table, _, _, _>(
diff --git a/crates/diesel_models/src/query/generics.rs b/crates/diesel_models/src/query/generics.rs
index 1428afcc90..ca74226e4f 100644
--- a/crates/diesel_models/src/query/generics.rs
+++ b/crates/diesel_models/src/query/generics.rs
@@ -25,9 +25,15 @@ use hyperswitch_masking::PeekInterface;
use hyperswitch_masking::Secret;
use router_env::logger;
-use crate::{errors, query::utils::GetPrimaryKey, DejaPgConnection, PgPooledConn, StorageResult};
+use crate::{
+ errors, query::utils::GetPrimaryKey, DatabaseConnectionWithContext, DejaPgConnection,
+ StorageResult,
+};
pub mod db_metrics {
+ use common_utils::external_service::{ExternalServiceCall, ExternalServiceEventEmitter};
+ use diesel::result::Error as DieselError;
+
#[derive(Debug)]
pub enum DatabaseOperation {
FindOne,
@@ -41,10 +47,65 @@ pub mod db_metrics {
Count,
}
+ pub trait DatabaseCallStatus {
+ fn is_success(&self) -> bool;
+ }
+
+ impl<T> DatabaseCallStatus for Result<T, DieselError> {
+ fn is_success(&self) -> bool {
+ matches!(self, Ok(_) | Err(DieselError::NotFound))
+ }
+ }
+
+ /// Row-returning executors resolve to the `(result, wire)` pair under `deja` (see
+ /// `Captured` in this module); success is determined by the inner result alone.
+ #[cfg(feature = "deja")]
+ impl<T> DatabaseCallStatus for (Result<T, DieselError>, Option<Vec<deja::db::WireRow>>) {
+ fn is_success(&self) -> bool {
+ self.0.is_success()
+ }
+ }
+
+ fn emit_database_call_event<U>(
+ request_id: Option<&str>,
+ event_emitter: &dyn ExternalServiceEventEmitter,
+ table_name: &str,
+ operation: &DatabaseOperation,
+ time_elapsed: std::time::Duration,
+ output: &U,
+ ) where
+ U: DatabaseCallStatus,
+ {
+ if let Some(request_id) = request_id {
+ let success = output.is_success();
+ event_emitter.emit_external_service_call(ExternalServiceCall {
+ service_name: "database".to_string(),
+ endpoint: table_name.to_string(),
+ method: format!("{operation:?}"),
+ request_id: request_id.to_string(),
+ status_code: if success { 200 } else { 500 },
+ success,
+ latency_ms: time_elapsed.as_millis(),
+ created_at_timestamp: common_utils::date_time::now_unix_timestamp_nanos(),
+ });
+ }
+ }
+
+ /// Times a single database call, records its latency metric, and emits one
+ /// `ExternalServiceCall` event reflecting that call.
+ ///
+ /// When `request_id` is absent (background work, drainer, scheduler) no event is emitted: the
+ /// correlator joins on `request_id` and cannot place request-less rows.
#[inline]
- pub async fn track_database_call<T, Fut, U>(future: Fut, operation: DatabaseOperation) -> U
+ pub async fn track_database_call<T, Fut, U>(
+ request_id: Option<&str>,
+ event_emitter: &dyn ExternalServiceEventEmitter,
+ operation: DatabaseOperation,
+ future: Fut,
+ ) -> U
where
Fut: std::future::Future<Output = U>,
+ U: DatabaseCallStatus,
{
let start = std::time::Instant::now();
let output = future.await;
@@ -60,6 +121,15 @@ pub mod db_metrics {
crate::metrics::DATABASE_CALLS_COUNT.add(1, attributes);
crate::metrics::DATABASE_CALL_TIME.record(time_elapsed.as_secs_f64(), attributes);
+ emit_database_call_event(
+ request_id,
+ event_emitter,
+ table_name.unwrap_or("undefined"),
+ &operation,
+ time_elapsed,
+ &output,
+ );
+
output
}
}
@@ -553,7 +623,10 @@ where
// Public builders (signatures identical to pre-fold — zero call-site changes)
// ---------------------------------------------------------------------------
-pub async fn generic_insert<T, V, R>(conn: &PgPooledConn, values: V) -> StorageResult<R>
+pub async fn generic_insert<T, V, R>(
+ conn: &DatabaseConnectionWithContext<'_>,
+ values: V,
+) -> StorageResult<R>
where
T: HasTable<Table = T> + Table + 'static + Debug,
V: Debug + Insertable<T>,
@@ -574,12 +647,18 @@ where
#[cfg(feature = "deja")]
let fut = track_database_call::<T, _, _>(
- deja::db::get_result_captured(conn, query),
+ conn.request_id(),
+ conn.event_emitter(),
DatabaseOperation::Insert,
+ deja::db::get_result_captured(conn.raw_connection(), query),
);
#[cfg(not(feature = "deja"))]
- let fut =
- track_database_call::<T, _, _>(query.get_result_async(conn), DatabaseOperation::Insert);
+ let fut = track_database_call::<T, _, _>(
+ conn.request_id(),
+ conn.event_emitter(),
+ DatabaseOperation::Insert,
+ query.get_result_async(conn.raw_connection()),
+ );
let output = execute_generic_insert(
fut,
@@ -594,7 +673,7 @@ where
}
pub async fn generic_update<T, V, P>(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
predicate: P,
values: V,
) -> StorageResult<usize>
@@ -619,7 +698,12 @@ where
});
execute_generic_update(
- track_database_call::<T, _, _>(query.execute_async(conn), DatabaseOperation::Update),
+ track_database_call::<T, _, _>(
+ conn.request_id(),
+ conn.event_emitter(),
+ DatabaseOperation::Update,
+ query.execute_async(conn.raw_connection()),
+ ),
table_name::<T>(),
Secret::new(sql),
Secret::new(inputs),
@@ -629,7 +713,7 @@ where
}
pub async fn generic_update_with_results<T, V, P, R>(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
predicate: P,
values: V,
) -> StorageResult<Vec<R>>
@@ -662,13 +746,17 @@ where
#[cfg(feature = "deja")]
let fut = track_database_call::<T, _, _>(
- deja::db::get_results_captured(conn, query.to_owned()),
+ conn.request_id(),
+ conn.event_emitter(),
DatabaseOperation::UpdateWithResults,
+ deja::db::get_results_captured(conn.raw_connection(), query.to_owned()),
);
#[cfg(not(feature = "deja"))]
let fut = track_database_call::<T, _, _>(
- query.to_owned().get_results_async(conn),
+ conn.request_id(),
+ conn.event_emitter(),
DatabaseOperation::UpdateWithResults,
+ query.to_owned().get_results_async(conn.raw_connection()),
);
let output = execute_generic_update_with_results(
@@ -684,7 +772,7 @@ where
}
pub async fn generic_update_with_unique_predicate_get_result<T, V, P, R>(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
predicate: P,
values: V,
) -> StorageResult<R>
@@ -720,7 +808,7 @@ where
}
pub async fn generic_update_by_id<T, V, Pk, R>(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
id: Pk,
values: V,
) -> StorageResult<R>
@@ -757,13 +845,17 @@ where
#[cfg(feature = "deja")]
let fut = track_database_call::<T, _, _>(
- deja::db::get_result_captured(conn, query.to_owned()),
+ conn.request_id(),
+ conn.event_emitter(),
DatabaseOperation::UpdateOne,
+ deja::db::get_result_captured(conn.raw_connection(), query.to_owned()),
);
#[cfg(not(feature = "deja"))]
let fut = track_database_call::<T, _, _>(
- query.to_owned().get_result_async(conn),
+ conn.request_id(),
+ conn.event_emitter(),
DatabaseOperation::UpdateOne,
+ query.to_owned().get_result_async(conn.raw_connection()),
);
let output = execute_generic_update_by_id(
@@ -778,7 +870,10 @@ where
output.attach_printable_lazy(|| format!("Error while updating by ID {debug_values}"))
}
-pub async fn generic_delete<T, P>(conn: &PgPooledConn, predicate: P) -> StorageResult<bool>
+pub async fn generic_delete<T, P>(
+ conn: &DatabaseConnectionWithContext<'_>,
+ predicate: P,
+) -> StorageResult<bool>
where
T: FilterDsl<P> + HasTable<Table = T> + Table + 'static,
Filter<T, P>: IntoUpdateTarget,
@@ -795,7 +890,12 @@ where
});
execute_generic_delete(
- track_database_call::<T, _, _>(query.execute_async(conn), DatabaseOperation::Delete),
+ track_database_call::<T, _, _>(
+ conn.request_id(),
+ conn.event_emitter(),
+ DatabaseOperation::Delete,
+ query.execute_async(conn.raw_connection()),
+ ),
table_name::<T>(),
Secret::new(sql),
Secret::new(inputs),
@@ -804,7 +904,7 @@ where
}
pub async fn generic_delete_one_with_result<T, P, R>(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
predicate: P,
) -> StorageResult<R>
where
@@ -825,13 +925,17 @@ where
#[cfg(feature = "deja")]
let fut = track_database_call::<T, _, _>(
- deja::db::get_results_captured(conn, query),
+ conn.request_id(),
+ conn.event_emitter(),
DatabaseOperation::DeleteWithResult,
+ deja::db::get_results_captured(conn.raw_connection(), query),
);
#[cfg(not(feature = "deja"))]
let fut = track_database_call::<T, _, _>(
- query.get_results_async(conn),
+ conn.request_id(),
+ conn.event_emitter(),
DatabaseOperation::DeleteWithResult,
+ query.get_results_async(conn.raw_connection()),
);
let output = execute_generic_delete_one_with_result(
@@ -846,7 +950,10 @@ where
output
}
-async fn generic_find_by_id_core<T, Pk, R>(conn: &PgPooledConn, id: Pk) -> StorageResult<R>
+async fn generic_find_by_id_core<T, Pk, R>(
+ conn: &DatabaseConnectionWithContext<'_>,
+ id: Pk,
+) -> StorageResult<R>
where
T: FindDsl<Pk> + HasTable<Table = T> + LimitDsl + Table + 'static,
Find<T, Pk>: LimitDsl + QueryFragment<Pg> + RunQueryDsl<DejaPgConnection> + Send + 'static,
@@ -863,11 +970,18 @@ where
#[cfg(feature = "deja")]
let fut = track_database_call::<T, _, _>(
- deja::db::first_captured(conn, query),
+ conn.request_id(),
+ conn.event_emitter(),
DatabaseOperation::FindOne,
+ deja::db::first_captured(conn.raw_connection(), query),
);
#[cfg(not(feature = "deja"))]
- let fut = track_database_call::<T, _, _>(query.first_async(conn), DatabaseOperation::FindOne);
+ let fut = track_database_call::<T, _, _>(
+ conn.request_id(),
+ conn.event_emitter(),
+ DatabaseOperation::FindOne,
+ query.first_async(conn.raw_connection()),
+ );
let output = execute_generic_find_by_id(
fut,
@@ -881,7 +995,10 @@ where
output.attach_printable_lazy(|| format!("Error finding record by primary key: {id:?}"))
}
-pub async fn generic_find_by_id<T, Pk, R>(conn: &PgPooledConn, id: Pk) -> StorageResult<R>
+pub async fn generic_find_by_id<T, Pk, R>(
+ conn: &DatabaseConnectionWithContext<'_>,
+ id: Pk,
+) -> StorageResult<R>
where
T: FindDsl<Pk> + HasTable<Table = T> + LimitDsl + Table + 'static,
Find<T, Pk>: LimitDsl + QueryFragment<Pg> + RunQueryDsl<DejaPgConnection> + Send + 'static,
@@ -893,7 +1010,7 @@ where
}
pub async fn generic_find_by_id_optional<T, Pk, R>(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
id: Pk,
) -> StorageResult<Option<R>>
where
@@ -907,7 +1024,10 @@ where
to_optional(generic_find_by_id_core::<T, _, _>(conn, id).await)
}
-async fn generic_find_one_core<T, P, R>(conn: &PgPooledConn, predicate: P) -> StorageResult<R>
+async fn generic_find_one_core<T, P, R>(
+ conn: &DatabaseConnectionWithContext<'_>,
+ predicate: P,
+) -> StorageResult<R>
where
T: FilterDsl<P> + HasTable<Table = T> + Table + 'static,
Filter<T, P>: LoadQuery<'static, DejaPgConnection, R> + QueryFragment<Pg> + Send + 'static,
@@ -922,12 +1042,18 @@ where
#[cfg(feature = "deja")]
let fut = track_database_call::<T, _, _>(
- deja::db::get_result_captured(conn, query),
+ conn.request_id(),
+ conn.event_emitter(),
DatabaseOperation::FindOne,
+ deja::db::get_result_captured(conn.raw_connection(), query),
);
#[cfg(not(feature = "deja"))]
- let fut =
- track_database_call::<T, _, _>(query.get_result_async(conn), DatabaseOperation::FindOne);
+ let fut = track_database_call::<T, _, _>(
+ conn.request_id(),
+ conn.event_emitter(),
+ DatabaseOperation::FindOne,
+ query.get_result_async(conn.raw_connection()),
+ );
let output = execute_generic_find_one(
fut,
@@ -941,7 +1067,10 @@ where
output
}
-pub async fn generic_find_one<T, P, R>(conn: &PgPooledConn, predicate: P) -> StorageResult<R>
+pub async fn generic_find_one<T, P, R>(
+ conn: &DatabaseConnectionWithContext<'_>,
+ predicate: P,
+) -> StorageResult<R>
where
T: FilterDsl<P> + HasTable<Table = T> + Table + 'static,
Filter<T, P>: LoadQuery<'static, DejaPgConnection, R> + QueryFragment<Pg> + Send + 'static,
@@ -951,7 +1080,7 @@ where
}
pub async fn generic_find_one_optional<T, P, R>(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
predicate: P,
) -> StorageResult<Option<R>>
where
@@ -963,7 +1092,7 @@ where
}
pub(super) async fn generic_filter<T, P, O, R>(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
predicate: P,
limit: Option<i64>,
offset: Option<i64>,
@@ -1009,12 +1138,18 @@ where
#[cfg(feature = "deja")]
let fut = track_database_call::<T, _, _>(
- deja::db::get_results_captured(conn, query),
+ conn.request_id(),
+ conn.event_emitter(),
DatabaseOperation::Filter,
+ deja::db::get_results_captured(conn.raw_connection(), query),
);
#[cfg(not(feature = "deja"))]
- let fut =
- track_database_call::<T, _, _>(query.get_results_async(conn), DatabaseOperation::Filter);
+ let fut = track_database_call::<T, _, _>(
+ conn.request_id(),
+ conn.event_emitter(),
+ DatabaseOperation::Filter,
+ query.get_results_async(conn.raw_connection()),
+ );
let output = execute_generic_filter(
fut,
@@ -1028,7 +1163,10 @@ where
output
}
-pub async fn generic_count<T, P>(conn: &PgPooledConn, predicate: P) -> StorageResult<usize>
+pub async fn generic_count<T, P>(
+ conn: &DatabaseConnectionWithContext<'_>,
+ predicate: P,
+) -> StorageResult<usize>
where
T: FilterDsl<P> + HasTable<Table = T> + Table + SelectDsl<count_star> + 'static,
Filter<T, P>: SelectDsl<count_star>,
@@ -1046,7 +1184,12 @@ where
});
execute_generic_count(
- track_database_call::<T, _, _>(query.get_result_async(conn), DatabaseOperation::Count),
+ track_database_call::<T, _, _>(
+ conn.request_id(),
+ conn.event_emitter(),
+ DatabaseOperation::Count,
+ query.get_result_async(conn.raw_connection()),
+ ),
table_name::<T>(),
Secret::new(sql),
Secret::new(inputs),
diff --git a/crates/diesel_models/src/query/gsm.rs b/crates/diesel_models/src/query/gsm.rs
index bd44ce4dc3..580ca1b7bd 100644
--- a/crates/diesel_models/src/query/gsm.rs
+++ b/crates/diesel_models/src/query/gsm.rs
@@ -2,18 +2,22 @@ use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods};
use error_stack::report;
use crate::{
- errors, gsm::*, query::generics, schema::gateway_status_map::dsl, PgPooledConn, StorageResult,
+ errors, gsm::*, query::generics, schema::gateway_status_map::dsl,
+ DatabaseConnectionWithContext, StorageResult,
};
impl GatewayStatusMappingNew {
- pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<GatewayStatusMap> {
+ pub async fn insert(
+ self,
+ conn: &DatabaseConnectionWithContext<'_>,
+ ) -> StorageResult<GatewayStatusMap> {
generics::generic_insert(conn, self).await
}
}
impl GatewayStatusMap {
pub async fn find(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
connector: String,
flow: String,
sub_flow: String,
@@ -33,7 +37,7 @@ impl GatewayStatusMap {
}
pub async fn retrieve_decision(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
connector: String,
flow: String,
sub_flow: String,
@@ -46,7 +50,7 @@ impl GatewayStatusMap {
}
pub async fn update(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
connector: String,
flow: String,
sub_flow: String,
@@ -79,7 +83,7 @@ impl GatewayStatusMap {
}
pub async fn delete(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
connector: String,
flow: String,
sub_flow: String,
diff --git a/crates/diesel_models/src/query/hyperswitch_ai_interaction.rs b/crates/diesel_models/src/query/hyperswitch_ai_interaction.rs
index 91db3ec468..3421aa82a9 100644
--- a/crates/diesel_models/src/query/hyperswitch_ai_interaction.rs
+++ b/crates/diesel_models/src/query/hyperswitch_ai_interaction.rs
@@ -4,18 +4,21 @@ use crate::{
hyperswitch_ai_interaction::{HyperswitchAiInteraction, HyperswitchAiInteractionNew},
query::generics,
schema::hyperswitch_ai_interaction::dsl,
- PgPooledConn, StorageResult,
+ DatabaseConnectionWithContext, StorageResult,
};
impl HyperswitchAiInteractionNew {
- pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<HyperswitchAiInteraction> {
+ pub async fn insert(
+ self,
+ conn: &DatabaseConnectionWithContext<'_>,
+ ) -> StorageResult<HyperswitchAiInteraction> {
generics::generic_insert(conn, self).await
}
}
impl HyperswitchAiInteraction {
pub async fn filter_by_optional_merchant_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: Option<&common_utils::id_type::MerchantId>,
limit: i64,
offset: i64,
diff --git a/crates/diesel_models/src/query/invoice.rs b/crates/diesel_models/src/query/invoice.rs
index 6e62d9b5b5..65b788b0d2 100644
--- a/crates/diesel_models/src/query/invoice.rs
+++ b/crates/diesel_models/src/query/invoice.rs
@@ -4,18 +4,18 @@ use super::generics;
use crate::{
invoice::{Invoice, InvoiceNew, InvoiceUpdate},
schema::invoice::dsl,
- PgPooledConn, StorageResult,
+ DatabaseConnectionWithContext, StorageResult,
};
impl InvoiceNew {
- pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Invoice> {
+ pub async fn insert(self, conn: &DatabaseConnectionWithContext<'_>) -> StorageResult<Invoice> {
generics::generic_insert(conn, self).await
}
}
impl Invoice {
pub async fn find_invoice_by_id_invoice_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
id: String,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
@@ -26,7 +26,7 @@ impl Invoice {
}
pub async fn update_invoice_entry(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
id: String,
invoice_update: InvoiceUpdate,
) -> StorageResult<Self> {
@@ -40,7 +40,7 @@ impl Invoice {
}
pub async fn list_invoices_by_subscription_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
subscription_id: String,
limit: Option<i64>,
offset: Option<i64>,
@@ -68,7 +68,7 @@ impl Invoice {
}
pub async fn get_invoice_by_subscription_id_connector_invoice_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
subscription_id: String,
connector_invoice_id: common_utils::id_type::InvoiceId,
) -> StorageResult<Option<Self>> {
diff --git a/crates/diesel_models/src/query/locker_mock_up.rs b/crates/diesel_models/src/query/locker_mock_up.rs
index 4ce52cfc40..d7d73faa50 100644
--- a/crates/diesel_models/src/query/locker_mock_up.rs
+++ b/crates/diesel_models/src/query/locker_mock_up.rs
@@ -4,17 +4,23 @@ use super::generics;
use crate::{
locker_mock_up::{LockerMockUp, LockerMockUpNew},
schema::locker_mock_up::dsl,
- PgPooledConn, StorageResult,
+ DatabaseConnectionWithContext, StorageResult,
};
impl LockerMockUpNew {
- pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<LockerMockUp> {
+ pub async fn insert(
+ self,
+ conn: &DatabaseConnectionWithContext<'_>,
+ ) -> StorageResult<LockerMockUp> {
generics::generic_insert(conn, self).await
}
}
impl LockerMockUp {
- pub async fn find_by_card_id(conn: &PgPooledConn, card_id: &str) -> StorageResult<Self> {
+ pub async fn find_by_card_id(
+ conn: &DatabaseConnectionWithContext<'_>,
+ card_id: &str,
+ ) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::card_id.eq(card_id.to_owned()),
@@ -22,7 +28,10 @@ impl LockerMockUp {
.await
}
- pub async fn delete_by_card_id(conn: &PgPooledConn, card_id: &str) -> StorageResult<Self> {
+ pub async fn delete_by_card_id(
+ conn: &DatabaseConnectionWithContext<'_>,
+ card_id: &str,
+ ) -> StorageResult<Self> {
generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>(
conn,
dsl::card_id.eq(card_id.to_owned()),
diff --git a/crates/diesel_models/src/query/mandate.rs b/crates/diesel_models/src/query/mandate.rs
index 4b25d4baf5..d7e2222b76 100644
--- a/crates/diesel_models/src/query/mandate.rs
+++ b/crates/diesel_models/src/query/mandate.rs
@@ -2,16 +2,18 @@ use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods, T
use error_stack::{report, ResultExt};
use super::generics;
-use crate::{errors, kv, mandate::*, schema::mandate::dsl, PgPooledConn, StorageResult};
+use crate::{
+ errors, kv, mandate::*, schema::mandate::dsl, DatabaseConnectionWithContext, StorageResult,
+};
impl MandateNew {
- pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Mandate> {
+ pub async fn insert(self, conn: &DatabaseConnectionWithContext<'_>) -> StorageResult<Mandate> {
generics::generic_insert(conn, self).await
}
pub async fn generate_drainer_insert_query(
self,
- conn: &mut PgPooledConn,
+ conn: &mut DatabaseConnectionWithContext<'_>,
) -> StorageResult<kv::SerializableQuery> {
kv::generate_insert_query(conn, self)
.await
@@ -21,7 +23,7 @@ impl MandateNew {
impl Mandate {
pub async fn find_by_merchant_id_mandate_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
mandate_id: &str,
) -> StorageResult<Self> {
@@ -35,7 +37,7 @@ impl Mandate {
}
pub async fn find_by_merchant_id_connector_mandate_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
connector_mandate_id: &str,
) -> StorageResult<Self> {
@@ -49,7 +51,7 @@ impl Mandate {
}
pub async fn find_by_merchant_id_customer_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
customer_id: &common_utils::id_type::CustomerId,
) -> StorageResult<Vec<Self>> {
@@ -73,7 +75,7 @@ impl Mandate {
//Fix this function once V2 mandate is schema is being built
#[cfg(feature = "v2")]
pub async fn find_by_global_customer_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
customer_id: &common_utils::id_type::GlobalCustomerId,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<
@@ -92,7 +94,7 @@ impl Mandate {
}
pub async fn update_by_merchant_id_mandate_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
mandate_id: &str,
mandate: MandateUpdateInternal,
@@ -117,7 +119,7 @@ impl Mandate {
impl MandateUpdateInternal {
pub async fn generate_drainer_update_query(
self,
- conn: &mut PgPooledConn,
+ conn: &mut DatabaseConnectionWithContext<'_>,
merchant_id: common_utils::id_type::MerchantId,
mandate_id: String,
) -> StorageResult<kv::SerializableQuery> {
diff --git a/crates/diesel_models/src/query/merchant_account.rs b/crates/diesel_models/src/query/merchant_account.rs
index f7e47663ce..394e1c2a6c 100644
--- a/crates/diesel_models/src/query/merchant_account.rs
+++ b/crates/diesel_models/src/query/merchant_account.rs
@@ -12,11 +12,14 @@ use crate::schema_v2::merchant_account::dsl;
use crate::{
errors,
merchant_account::{MerchantAccount, MerchantAccountNew, MerchantAccountUpdateInternal},
- PgPooledConn, StorageResult,
+ DatabaseConnectionWithContext, StorageResult,
};
impl MerchantAccountNew {
- pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<MerchantAccount> {
+ pub async fn insert(
+ self,
+ conn: &DatabaseConnectionWithContext<'_>,
+ ) -> StorageResult<MerchantAccount> {
Box::pin(generics::generic_insert(conn, self)).await
}
}
@@ -25,7 +28,7 @@ impl MerchantAccountNew {
impl MerchantAccount {
pub async fn update(
self,
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_account: MerchantAccountUpdateInternal,
) -> StorageResult<Self> {
match Box::pin(generics::generic_update_by_id::<
@@ -45,7 +48,7 @@ impl MerchantAccount {
}
pub async fn update_with_specific_fields(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
identifier: &common_utils::id_type::MerchantId,
merchant_account: MerchantAccountUpdateInternal,
) -> StorageResult<Self> {
@@ -63,7 +66,7 @@ impl MerchantAccount {
}
pub async fn delete_by_merchant_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
identifier: &common_utils::id_type::MerchantId,
) -> StorageResult<bool> {
generics::generic_delete::<<Self as HasTable>::Table, _>(
@@ -74,7 +77,7 @@ impl MerchantAccount {
}
pub async fn find_by_merchant_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
identifier: &common_utils::id_type::MerchantId,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
@@ -85,7 +88,7 @@ impl MerchantAccount {
}
pub async fn find_by_publishable_key(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
publishable_key: &str,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
@@ -96,7 +99,7 @@ impl MerchantAccount {
}
pub async fn list_by_organization_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
organization_id: &common_utils::id_type::OrganizationId,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<
@@ -117,7 +120,7 @@ impl MerchantAccount {
}
pub async fn list_multiple_merchant_accounts(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_ids: Vec<common_utils::id_type::MerchantId>,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<
@@ -136,7 +139,7 @@ impl MerchantAccount {
}
pub async fn list_all_merchant_accounts(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
limit: u32,
offset: Option<u32>,
) -> StorageResult<Vec<Self>> {
@@ -156,7 +159,7 @@ impl MerchantAccount {
}
pub async fn update_all_merchant_accounts(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_account: MerchantAccountUpdateInternal,
) -> StorageResult<Vec<Self>> {
Box::pin(generics::generic_update_with_results::<
@@ -175,7 +178,7 @@ impl MerchantAccount {
impl MerchantAccount {
pub async fn update(
self,
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_account: MerchantAccountUpdateInternal,
) -> StorageResult<Self> {
match generics::generic_update_by_id::<<Self as HasTable>::Table, _, _, _>(
@@ -194,7 +197,7 @@ impl MerchantAccount {
}
pub async fn update_with_specific_fields(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
identifier: &common_utils::id_type::MerchantId,
merchant_account: MerchantAccountUpdateInternal,
) -> StorageResult<Self> {
@@ -208,7 +211,7 @@ impl MerchantAccount {
}
pub async fn delete_by_merchant_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
identifier: &common_utils::id_type::MerchantId,
) -> StorageResult<bool> {
generics::generic_delete::<<Self as HasTable>::Table, _>(
@@ -219,7 +222,7 @@ impl MerchantAccount {
}
pub async fn find_by_merchant_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
identifier: &common_utils::id_type::MerchantId,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
@@ -230,7 +233,7 @@ impl MerchantAccount {
}
pub async fn find_by_publishable_key(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
publishable_key: &str,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
@@ -241,7 +244,7 @@ impl MerchantAccount {
}
pub async fn list_by_organization_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
organization_id: &common_utils::id_type::OrganizationId,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<
@@ -260,7 +263,7 @@ impl MerchantAccount {
}
pub async fn list_multiple_merchant_accounts(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_ids: Vec<common_utils::id_type::MerchantId>,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<
@@ -273,7 +276,7 @@ impl MerchantAccount {
}
pub async fn list_all_merchant_accounts(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
limit: u32,
offset: Option<u32>,
) -> StorageResult<Vec<Self>> {
@@ -293,7 +296,7 @@ impl MerchantAccount {
}
pub async fn update_all_merchant_accounts(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_account: MerchantAccountUpdateInternal,
) -> StorageResult<Vec<Self>> {
generics::generic_update_with_results::<<Self as HasTable>::Table, _, _, _>(
diff --git a/crates/diesel_models/src/query/merchant_connector_account.rs b/crates/diesel_models/src/query/merchant_connector_account.rs
index 2305a1ea56..7e6f7a4f28 100644
--- a/crates/diesel_models/src/query/merchant_connector_account.rs
+++ b/crates/diesel_models/src/query/merchant_connector_account.rs
@@ -11,11 +11,14 @@ use crate::{
MerchantConnectorAccount, MerchantConnectorAccountNew,
MerchantConnectorAccountUpdateInternal,
},
- PgPooledConn, StorageResult,
+ DatabaseConnectionWithContext, StorageResult,
};
impl MerchantConnectorAccountNew {
- pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<MerchantConnectorAccount> {
+ pub async fn insert(
+ self,
+ conn: &DatabaseConnectionWithContext<'_>,
+ ) -> StorageResult<MerchantConnectorAccount> {
generics::generic_insert(conn, self).await
}
}
@@ -24,7 +27,7 @@ impl MerchantConnectorAccountNew {
impl MerchantConnectorAccount {
pub async fn update(
self,
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_connector_account: MerchantConnectorAccountUpdateInternal,
) -> StorageResult<Self> {
match generics::generic_update_by_id::<<Self as HasTable>::Table, _, _, _>(
@@ -43,7 +46,7 @@ impl MerchantConnectorAccount {
}
pub async fn delete_by_merchant_id_merchant_connector_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
merchant_connector_id: &common_utils::id_type::MerchantConnectorAccountId,
) -> StorageResult<bool> {
@@ -57,7 +60,7 @@ impl MerchantConnectorAccount {
}
pub async fn find_by_merchant_id_connector(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
connector_label: &str,
) -> StorageResult<Self> {
@@ -71,7 +74,7 @@ impl MerchantConnectorAccount {
}
pub async fn find_by_profile_id_connector_name(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
profile_id: &common_utils::id_type::ProfileId,
connector_name: &str,
) -> StorageResult<Self> {
@@ -85,7 +88,7 @@ impl MerchantConnectorAccount {
}
pub async fn find_by_merchant_id_connector_name(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
connector_name: &str,
) -> StorageResult<Vec<Self>> {
@@ -107,7 +110,7 @@ impl MerchantConnectorAccount {
}
pub async fn find_by_merchant_id_merchant_connector_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
merchant_connector_id: &common_utils::id_type::MerchantConnectorAccountId,
) -> StorageResult<Self> {
@@ -121,7 +124,7 @@ impl MerchantConnectorAccount {
}
pub async fn find_by_merchant_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
get_disabled: bool,
) -> StorageResult<Vec<Self>> {
@@ -154,7 +157,7 @@ impl MerchantConnectorAccount {
}
pub async fn list_enabled_by_profile_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
profile_id: &common_utils::id_type::ProfileId,
connector_type: common_enums::ConnectorType,
) -> StorageResult<Vec<Self>> {
@@ -172,7 +175,7 @@ impl MerchantConnectorAccount {
}
pub async fn list_merchant_connector_accounts_without_encrypted_including_disabled_by_merchant_id_profile_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
profile_id: &common_utils::id_type::ProfileId,
) -> StorageResult<Vec<Self>> {
@@ -194,7 +197,7 @@ impl MerchantConnectorAccount {
}
pub async fn list_enabled_merchant_connector_accounts_without_encrypted_by_merchant_id_profile_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
profile_id: &common_utils::id_type::ProfileId,
) -> StorageResult<Vec<Self>> {
@@ -221,7 +224,7 @@ impl MerchantConnectorAccount {
impl MerchantConnectorAccount {
pub async fn update(
self,
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_connector_account: MerchantConnectorAccountUpdateInternal,
) -> StorageResult<Self> {
match generics::generic_update_by_id::<<Self as HasTable>::Table, _, _, _>(
@@ -240,7 +243,7 @@ impl MerchantConnectorAccount {
}
pub async fn delete_by_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
id: &common_utils::id_type::MerchantConnectorAccountId,
) -> StorageResult<bool> {
generics::generic_delete::<<Self as HasTable>::Table, _>(conn, dsl::id.eq(id.to_owned()))
@@ -248,7 +251,7 @@ impl MerchantConnectorAccount {
}
pub async fn find_by_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
id: &common_utils::id_type::MerchantConnectorAccountId,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
@@ -259,7 +262,7 @@ impl MerchantConnectorAccount {
}
pub async fn find_by_merchant_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
get_disabled: bool,
) -> StorageResult<Vec<Self>> {
@@ -292,7 +295,7 @@ impl MerchantConnectorAccount {
}
pub async fn list_by_profile_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
profile_id: &common_utils::id_type::ProfileId,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
@@ -306,7 +309,7 @@ impl MerchantConnectorAccount {
}
pub async fn list_merchant_connector_accounts_without_encrypted_including_disabled_by_merchant_id_profile_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
profile_id: &common_utils::id_type::ProfileId,
) -> StorageResult<Vec<Self>> {
@@ -328,7 +331,7 @@ impl MerchantConnectorAccount {
}
pub async fn list_enabled_merchant_connector_accounts_without_encrypted_by_merchant_id_profile_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
profile_id: &common_utils::id_type::ProfileId,
) -> StorageResult<Vec<Self>> {
@@ -351,7 +354,7 @@ impl MerchantConnectorAccount {
}
pub async fn list_enabled_by_profile_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
profile_id: &common_utils::id_type::ProfileId,
connector_type: common_enums::ConnectorType,
) -> StorageResult<Vec<Self>> {
diff --git a/crates/diesel_models/src/query/merchant_key_store.rs b/crates/diesel_models/src/query/merchant_key_store.rs
index 4b35a43efd..3f3366ee0c 100644
--- a/crates/diesel_models/src/query/merchant_key_store.rs
+++ b/crates/diesel_models/src/query/merchant_key_store.rs
@@ -4,18 +4,21 @@ use super::generics;
use crate::{
merchant_key_store::{MerchantKeyStore, MerchantKeyStoreNew},
schema::merchant_key_store::dsl,
- PgPooledConn, StorageResult,
+ DatabaseConnectionWithContext, StorageResult,
};
impl MerchantKeyStoreNew {
- pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<MerchantKeyStore> {
+ pub async fn insert(
+ self,
+ conn: &DatabaseConnectionWithContext<'_>,
+ ) -> StorageResult<MerchantKeyStore> {
generics::generic_insert(conn, self).await
}
}
impl MerchantKeyStore {
pub async fn find_by_merchant_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
@@ -26,7 +29,7 @@ impl MerchantKeyStore {
}
pub async fn delete_by_merchant_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<bool> {
generics::generic_delete::<<Self as HasTable>::Table, _>(
@@ -37,7 +40,7 @@ impl MerchantKeyStore {
}
pub async fn list_multiple_key_stores(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_ids: Vec<common_utils::id_type::MerchantId>,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<
@@ -56,7 +59,7 @@ impl MerchantKeyStore {
}
pub async fn list_all_key_stores(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
from: u32,
limit: u32,
) -> StorageResult<Vec<Self>> {
diff --git a/crates/diesel_models/src/query/organization.rs b/crates/diesel_models/src/query/organization.rs
index f8f6cf8cbf..2342d8eecf 100644
--- a/crates/diesel_models/src/query/organization.rs
+++ b/crates/diesel_models/src/query/organization.rs
@@ -5,17 +5,20 @@ use diesel::{associations::HasTable, ExpressionMethods};
use crate::schema::organization::dsl::org_id as dsl_identifier;
#[cfg(feature = "v2")]
use crate::schema_v2::organization::dsl::id as dsl_identifier;
-use crate::{organization::*, query::generics, PgPooledConn, StorageResult};
+use crate::{organization::*, query::generics, DatabaseConnectionWithContext, StorageResult};
impl OrganizationNew {
- pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Organization> {
+ pub async fn insert(
+ self,
+ conn: &DatabaseConnectionWithContext<'_>,
+ ) -> StorageResult<Organization> {
generics::generic_insert(conn, self).await
}
}
impl Organization {
pub async fn find_by_org_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
org_id: id_type::OrganizationId,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
@@ -26,7 +29,7 @@ impl Organization {
}
pub async fn update_by_org_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
org_id: id_type::OrganizationId,
update: OrganizationUpdate,
) -> StorageResult<Self> {
diff --git a/crates/diesel_models/src/query/payment_attempt.rs b/crates/diesel_models/src/query/payment_attempt.rs
index 37d1adc205..eb6c736bfd 100644
--- a/crates/diesel_models/src/query/payment_attempt.rs
+++ b/crates/diesel_models/src/query/payment_attempt.rs
@@ -20,19 +20,22 @@ use crate::{
kv,
payment_attempt::{PaymentAttempt, PaymentAttemptNew, PaymentAttemptUpdateInternal},
query::generics::db_metrics,
- PgPooledConn, StorageResult,
+ DatabaseConnectionWithContext, StorageResult,
};
#[cfg(feature = "v1")]
use crate::{enums::IntentStatus, payment_attempt::PaymentAttemptUpdate, PaymentIntent};
impl PaymentAttemptNew {
- pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<PaymentAttempt> {
+ pub async fn insert(
+ self,
+ conn: &DatabaseConnectionWithContext<'_>,
+ ) -> StorageResult<PaymentAttempt> {
Box::pin(generics::generic_insert(conn, self)).await
}
pub async fn generate_drainer_insert_query(
self,
- conn: &mut PgPooledConn,
+ conn: &mut DatabaseConnectionWithContext<'_>,
) -> StorageResult<kv::SerializableQuery> {
kv::generate_insert_query(conn, self)
.await
@@ -44,7 +47,7 @@ impl PaymentAttempt {
#[cfg(feature = "v1")]
pub async fn update_with_attempt_id(
self,
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
payment_attempt: PaymentAttemptUpdate,
) -> StorageResult<Self> {
match Box::pin(generics::generic_update_with_unique_predicate_get_result::<
@@ -72,7 +75,7 @@ impl PaymentAttempt {
#[cfg(feature = "v2")]
pub async fn update_with_attempt_id(
self,
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
payment_attempt: PaymentAttemptUpdateInternal,
) -> StorageResult<Self> {
match Box::pin(generics::generic_update_with_unique_predicate_get_result::<
@@ -95,7 +98,7 @@ impl PaymentAttempt {
#[cfg(feature = "v1")]
pub async fn find_optional_by_payment_id_processor_merchant_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
payment_id: &common_utils::id_type::PaymentId,
processor_merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Option<Self>> {
@@ -110,7 +113,7 @@ impl PaymentAttempt {
#[cfg(feature = "v1")]
pub async fn find_by_connector_transaction_id_payment_id_processor_merchant_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
connector_transaction_id: &common_utils::types::ConnectorTransactionId,
payment_id: &common_utils::id_type::PaymentId,
processor_merchant_id: &common_utils::id_type::MerchantId,
@@ -127,7 +130,7 @@ impl PaymentAttempt {
#[cfg(feature = "v1")]
pub async fn find_last_successful_attempt_by_payment_id_processor_merchant_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
payment_id: &common_utils::id_type::PaymentId,
processor_merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Self> {
@@ -150,7 +153,7 @@ impl PaymentAttempt {
#[cfg(feature = "v1")]
pub async fn find_last_successful_or_partially_captured_attempt_by_payment_id_processor_merchant_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
payment_id: &common_utils::id_type::PaymentId,
processor_merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Self> {
@@ -177,7 +180,7 @@ impl PaymentAttempt {
#[cfg(feature = "v2")]
pub async fn find_last_successful_or_partially_captured_attempt_by_payment_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
payment_id: &common_utils::id_type::GlobalPaymentId,
) -> StorageResult<Self> {
// perform ordering on the application level instead of database level
@@ -200,7 +203,7 @@ impl PaymentAttempt {
#[cfg(feature = "v1")]
pub async fn find_by_processor_merchant_id_connector_txn_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
processor_merchant_id: &common_utils::id_type::MerchantId,
connector_txn_id: &str,
) -> StorageResult<Self> {
@@ -224,7 +227,7 @@ impl PaymentAttempt {
#[cfg(feature = "v2")]
pub async fn find_by_profile_id_connector_transaction_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
profile_id: &common_utils::id_type::ProfileId,
connector_txn_id: &str,
) -> StorageResult<Self> {
@@ -248,7 +251,7 @@ impl PaymentAttempt {
#[cfg(feature = "v1")]
pub async fn find_by_processor_merchant_id_attempt_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
processor_merchant_id: &common_utils::id_type::MerchantId,
attempt_id: &str,
) -> StorageResult<Self> {
@@ -263,7 +266,7 @@ impl PaymentAttempt {
#[cfg(feature = "v2")]
pub async fn find_by_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
id: &common_utils::id_type::GlobalAttemptId,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
@@ -275,7 +278,7 @@ impl PaymentAttempt {
#[cfg(feature = "v2")]
pub async fn find_by_payment_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
payment_id: &common_utils::id_type::GlobalPaymentId,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
@@ -290,7 +293,7 @@ impl PaymentAttempt {
#[cfg(feature = "v1")]
pub async fn find_by_processor_merchant_id_preprocessing_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
processor_merchant_id: &common_utils::id_type::MerchantId,
preprocessing_id: &str,
) -> StorageResult<Self> {
@@ -305,7 +308,7 @@ impl PaymentAttempt {
#[cfg(feature = "v1")]
pub async fn find_by_payment_id_processor_merchant_id_attempt_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
payment_id: &common_utils::id_type::PaymentId,
processor_merchant_id: &common_utils::id_type::MerchantId,
attempt_id: &str,
@@ -323,7 +326,7 @@ impl PaymentAttempt {
#[cfg(feature = "v1")]
pub async fn find_by_processor_merchant_id_payment_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
processor_merchant_id: &common_utils::id_type::MerchantId,
payment_id: &common_utils::id_type::PaymentId,
) -> StorageResult<Vec<Self>> {
@@ -346,7 +349,7 @@ impl PaymentAttempt {
#[cfg(feature = "v1")]
pub async fn get_filters_for_payments(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
pi: &[PaymentIntent],
processor_merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<(
@@ -377,7 +380,7 @@ impl PaymentAttempt {
.clone()
.select(dsl::connector)
.distinct()
- .get_results_async::<Option<String>>(conn)
+ .get_results_async::<Option<String>>(conn.raw_connection())
.await
.change_context(DatabaseError::Others)
.attach_printable("Error filtering records by connector")?
@@ -389,7 +392,7 @@ impl PaymentAttempt {
.clone()
.select(dsl::currency)
.distinct()
- .get_results_async::<Option<enums::Currency>>(conn)
+ .get_results_async::<Option<enums::Currency>>(conn.raw_connection())
.await
.change_context(DatabaseError::Others)
.attach_printable("Error filtering records by currency")?
@@ -401,7 +404,7 @@ impl PaymentAttempt {
.clone()
.select(dsl::payment_method)
.distinct()
- .get_results_async::<Option<enums::PaymentMethod>>(conn)
+ .get_results_async::<Option<enums::PaymentMethod>>(conn.raw_connection())
.await
.change_context(DatabaseError::Others)
.attach_printable("Error filtering records by payment method")?
@@ -413,7 +416,7 @@ impl PaymentAttempt {
.clone()
.select(dsl::payment_method_type)
.distinct()
- .get_results_async::<Option<enums::PaymentMethodType>>(conn)
+ .get_results_async::<Option<enums::PaymentMethodType>>(conn.raw_connection())
.await
.change_context(DatabaseError::Others)
.attach_printable("Error filtering records by payment method type")?
@@ -425,7 +428,7 @@ impl PaymentAttempt {
.clone()
.select(dsl::authentication_type)
.distinct()
- .get_results_async::<Option<enums::AuthenticationType>>(conn)
+ .get_results_async::<Option<enums::AuthenticationType>>(conn.raw_connection())
.await
.change_context(DatabaseError::Others)
.attach_printable("Error filtering records by authentication type")?
@@ -446,7 +449,7 @@ impl PaymentAttempt {
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
pub async fn get_total_count_of_attempts(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
active_attempt_ids: &[String],
connector: Option<Vec<String>>,
@@ -489,8 +492,10 @@ impl PaymentAttempt {
let start_time = std::time::Instant::now();
router_env::logger::debug!("Executing count query start_time: {:?}", start_time);
let result = db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>(
- filter.get_result_async::<i64>(conn),
+ conn.request_id(),
+ conn.event_emitter(),
db_metrics::DatabaseOperation::Filter,
+ filter.get_result_async::<i64>(conn.raw_connection()),
)
.await
.change_context(DatabaseError::Others)
@@ -505,7 +510,7 @@ impl PaymentAttempt {
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
pub async fn get_total_count_of_attempts(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
processor_merchant_id: &common_utils::id_type::MerchantId,
active_attempt_ids: &[String],
connector: Option<Vec<String>>,
@@ -552,8 +557,10 @@ impl PaymentAttempt {
let start_time = std::time::Instant::now();
router_env::logger::debug!("Executing count query start_time: {:?}", start_time);
let result = db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>(
- filter.get_result_async::<i64>(conn),
+ conn.request_id(),
+ conn.event_emitter(),
db_metrics::DatabaseOperation::Filter,
+ filter.get_result_async::<i64>(conn.raw_connection()),
)
.await
.change_context(DatabaseError::Others)
@@ -570,7 +577,7 @@ impl PaymentAttempt {
impl PaymentAttemptUpdate {
pub async fn generate_drainer_update_query(
self,
- conn: &mut PgPooledConn,
+ conn: &mut DatabaseConnectionWithContext<'_>,
source_payment_attempt: &PaymentAttempt,
) -> StorageResult<kv::SerializableQuery> {
kv::generate_update_query_with_predicate::<<PaymentAttempt as HasTable>::Table, _, _>(
@@ -593,7 +600,7 @@ impl PaymentAttemptUpdate {
impl PaymentAttemptUpdateInternal {
pub async fn generate_drainer_update_query(
self,
- conn: &mut PgPooledConn,
+ conn: &mut DatabaseConnectionWithContext<'_>,
id: common_utils::id_type::GlobalAttemptId,
) -> StorageResult<kv::SerializableQuery> {
kv::generate_update_query_with_predicate::<<PaymentAttempt as HasTable>::Table, _, _>(
diff --git a/crates/diesel_models/src/query/payment_intent.rs b/crates/diesel_models/src/query/payment_intent.rs
index cbe87351a4..89ba099584 100644
--- a/crates/diesel_models/src/query/payment_intent.rs
+++ b/crates/diesel_models/src/query/payment_intent.rs
@@ -9,17 +9,20 @@ use crate::schema_v2::payment_intent::dsl;
use crate::{
errors, kv,
payment_intent::{self, PaymentIntent, PaymentIntentNew},
- PgPooledConn, StorageResult,
+ DatabaseConnectionWithContext, StorageResult,
};
impl PaymentIntentNew {
- pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<PaymentIntent> {
+ pub async fn insert(
+ self,
+ conn: &DatabaseConnectionWithContext<'_>,
+ ) -> StorageResult<PaymentIntent> {
Box::pin(generics::generic_insert(conn, self)).await
}
pub async fn generate_drainer_insert_query(
self,
- conn: &mut PgPooledConn,
+ conn: &mut DatabaseConnectionWithContext<'_>,
) -> StorageResult<kv::SerializableQuery> {
kv::generate_insert_query(conn, self)
.await
@@ -31,7 +34,7 @@ impl PaymentIntent {
#[cfg(feature = "v2")]
pub async fn update(
self,
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
payment_intent_update: payment_intent::PaymentIntentUpdateInternal,
) -> StorageResult<Self> {
match Box::pin(generics::generic_update_by_id::<
@@ -52,7 +55,7 @@ impl PaymentIntent {
#[cfg(feature = "v2")]
pub async fn find_by_global_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
id: &common_utils::id_type::GlobalPaymentId,
) -> StorageResult<Self> {
generics::generic_find_by_id::<<Self as HasTable>::Table, _, _>(conn, id.to_owned()).await
@@ -61,7 +64,7 @@ impl PaymentIntent {
#[cfg(feature = "v1")]
pub async fn update(
self,
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
payment_intent: payment_intent::PaymentIntentUpdate,
) -> StorageResult<Self> {
match Box::pin(generics::generic_update_with_results::<
@@ -90,7 +93,7 @@ impl PaymentIntent {
#[cfg(feature = "v2")]
pub async fn find_by_merchant_reference_id_merchant_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_reference_id: &str,
merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Self> {
@@ -107,7 +110,7 @@ impl PaymentIntent {
// In an active-active setup, a lookup table should be implemented, and the merchant reference ID will serve as the idempotency key.
#[cfg(feature = "v2")]
pub async fn find_by_merchant_reference_id_profile_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_reference_id: &common_utils::id_type::PaymentReferenceId,
profile_id: &common_utils::id_type::ProfileId,
) -> StorageResult<Self> {
@@ -122,7 +125,7 @@ impl PaymentIntent {
#[cfg(feature = "v1")]
pub async fn find_by_payment_id_processor_merchant_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
payment_id: &common_utils::id_type::PaymentId,
processor_merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Self> {
@@ -137,7 +140,7 @@ impl PaymentIntent {
#[cfg(feature = "v2")]
pub async fn find_optional_by_merchant_reference_id_merchant_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_reference_id: &str,
merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Option<Self>> {
@@ -152,7 +155,7 @@ impl PaymentIntent {
#[cfg(feature = "v1")]
pub async fn find_optional_by_payment_id_processor_merchant_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
payment_id: &common_utils::id_type::PaymentId,
processor_merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Option<Self>> {
@@ -170,7 +173,7 @@ impl PaymentIntent {
impl payment_intent::PaymentIntentUpdate {
pub async fn generate_drainer_update_query(
self,
- conn: &mut PgPooledConn,
+ conn: &mut DatabaseConnectionWithContext<'_>,
payment_id: common_utils::id_type::PaymentId,
processor_merchant_id: Option<common_utils::id_type::MerchantId>,
) -> StorageResult<kv::SerializableQuery> {
@@ -190,7 +193,7 @@ impl payment_intent::PaymentIntentUpdate {
impl payment_intent::PaymentIntentUpdateInternal {
pub async fn generate_drainer_update_query(
self,
- conn: &mut PgPooledConn,
+ conn: &mut DatabaseConnectionWithContext<'_>,
id: common_utils::id_type::GlobalPaymentId,
) -> StorageResult<kv::SerializableQuery> {
kv::generate_update_query_by_id::<<PaymentIntent as HasTable>::Table, _, _>(conn, id, self)
diff --git a/crates/diesel_models/src/query/payment_link.rs b/crates/diesel_models/src/query/payment_link.rs
index 154e753699..cf615a6e79 100644
--- a/crates/diesel_models/src/query/payment_link.rs
+++ b/crates/diesel_models/src/query/payment_link.rs
@@ -4,18 +4,21 @@ use super::generics;
use crate::{
payment_link::{PaymentLink, PaymentLinkNew},
schema::payment_link::dsl,
- PgPooledConn, StorageResult,
+ DatabaseConnectionWithContext, StorageResult,
};
impl PaymentLinkNew {
- pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<PaymentLink> {
+ pub async fn insert(
+ self,
+ conn: &DatabaseConnectionWithContext<'_>,
+ ) -> StorageResult<PaymentLink> {
generics::generic_insert(conn, self).await
}
}
impl PaymentLink {
pub async fn find_link_by_payment_link_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
payment_link_id: &str,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
diff --git a/crates/diesel_models/src/query/payment_method.rs b/crates/diesel_models/src/query/payment_method.rs
index 1b89980c94..7b5fea1f10 100644
--- a/crates/diesel_models/src/query/payment_method.rs
+++ b/crates/diesel_models/src/query/payment_method.rs
@@ -14,17 +14,20 @@ use crate::schema_v2::payment_methods::dsl::{self, id as pm_id};
use crate::{
enums as storage_enums, errors, kv,
payment_method::{self, PaymentMethod, PaymentMethodNew},
- PgPooledConn, StorageResult,
+ DatabaseConnectionWithContext, StorageResult,
};
impl PaymentMethodNew {
- pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<PaymentMethod> {
+ pub async fn insert(
+ self,
+ conn: &DatabaseConnectionWithContext<'_>,
+ ) -> StorageResult<PaymentMethod> {
Box::pin(generics::generic_insert(conn, self)).await
}
pub async fn generate_drainer_insert_query(
self,
- conn: &mut PgPooledConn,
+ conn: &mut DatabaseConnectionWithContext<'_>,
) -> StorageResult<kv::SerializableQuery> {
kv::generate_insert_query(conn, self)
.await
@@ -35,7 +38,7 @@ impl PaymentMethodNew {
#[cfg(feature = "v1")]
impl PaymentMethod {
pub async fn delete_by_payment_method_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
payment_method_id: String,
) -> StorageResult<Self> {
generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, Self>(
@@ -46,7 +49,7 @@ impl PaymentMethod {
}
pub async fn delete_by_merchant_id_payment_method_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
payment_method_id: &str,
) -> StorageResult<Self> {
@@ -59,7 +62,10 @@ impl PaymentMethod {
.await
}
- pub async fn find_by_locker_id(conn: &PgPooledConn, locker_id: &str) -> StorageResult<Self> {
+ pub async fn find_by_locker_id(
+ conn: &DatabaseConnectionWithContext<'_>,
+ locker_id: &str,
+ ) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::locker_id.eq(locker_id.to_owned()),
@@ -68,7 +74,7 @@ impl PaymentMethod {
}
pub async fn find_by_payment_method_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
payment_method_id: &str,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
@@ -79,7 +85,7 @@ impl PaymentMethod {
}
pub async fn find_by_merchant_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<
@@ -98,7 +104,7 @@ impl PaymentMethod {
}
pub async fn find_by_customer_id_merchant_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
customer_id: &common_utils::id_type::CustomerId,
merchant_id: &common_utils::id_type::MerchantId,
limit: Option<i64>,
@@ -116,7 +122,7 @@ impl PaymentMethod {
}
pub async fn find_by_merchant_id_payment_method_ids(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
payment_method_ids: &[String],
limit: Option<i64>,
@@ -137,7 +143,7 @@ impl PaymentMethod {
}
pub async fn get_count_by_customer_id_merchant_id_status(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
customer_id: &common_utils::id_type::CustomerId,
merchant_id: &common_utils::id_type::MerchantId,
status: common_enums::PaymentMethodStatus,
@@ -154,8 +160,10 @@ impl PaymentMethod {
router_env::logger::debug!(query = %debug_query::<Pg, _>(&filter).to_string());
generics::db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>(
- filter.get_result_async::<i64>(conn),
+ conn.request_id(),
+ conn.event_emitter(),
generics::db_metrics::DatabaseOperation::Count,
+ filter.get_result_async::<i64>(conn.raw_connection()),
)
.await
.change_context(errors::DatabaseError::Others)
@@ -163,7 +171,7 @@ impl PaymentMethod {
}
pub async fn get_count_by_merchant_id_status(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
status: common_enums::PaymentMethodStatus,
) -> StorageResult<i64> {
@@ -176,8 +184,10 @@ impl PaymentMethod {
router_env::logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());
generics::db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>(
- query.get_result_async::<i64>(conn),
+ conn.request_id(),
+ conn.event_emitter(),
generics::db_metrics::DatabaseOperation::Count,
+ query.get_result_async::<i64>(conn.raw_connection()),
)
.await
.change_context(errors::DatabaseError::Others)
@@ -185,7 +195,7 @@ impl PaymentMethod {
}
pub async fn find_by_customer_id_merchant_id_status(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
customer_id: &common_utils::id_type::CustomerId,
merchant_id: &common_utils::id_type::MerchantId,
status: storage_enums::PaymentMethodStatus,
@@ -205,7 +215,7 @@ impl PaymentMethod {
}
pub async fn find_by_customer_id_merchant_id_status_pm_type(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
customer_id: &common_utils::id_type::CustomerId,
merchant_id: &common_utils::id_type::MerchantId,
status: storage_enums::PaymentMethodStatus,
@@ -228,7 +238,7 @@ impl PaymentMethod {
pub async fn update_with_payment_method_id(
self,
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
payment_method: payment_method::PaymentMethodUpdateInternal,
) -> StorageResult<Self> {
match generics::generic_update_with_unique_predicate_get_result::<
@@ -252,7 +262,7 @@ impl PaymentMethod {
}
pub async fn find_by_fingerprint_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
fingerprint_id: &str,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
@@ -266,7 +276,7 @@ impl PaymentMethod {
#[cfg(feature = "v2")]
impl PaymentMethod {
pub async fn find_by_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
id: &common_utils::id_type::GlobalPaymentMethodId,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(conn, pm_id.eq(id.to_owned()))
@@ -274,7 +284,7 @@ impl PaymentMethod {
}
pub async fn find_by_global_customer_id_merchant_id_statuses(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
customer_id: &common_utils::id_type::GlobalCustomerId,
merchant_id: &common_utils::id_type::MerchantId,
statuses: Vec<storage_enums::PaymentMethodStatus>,
@@ -294,7 +304,7 @@ impl PaymentMethod {
}
pub async fn find_by_global_customer_id_merchant_id_status(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
customer_id: &common_utils::id_type::GlobalCustomerId,
merchant_id: &common_utils::id_type::MerchantId,
status: storage_enums::PaymentMethodStatus,
@@ -314,7 +324,7 @@ impl PaymentMethod {
}
pub async fn find_by_global_customer_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
customer_id: &common_utils::id_type::GlobalCustomerId,
limit: Option<i64>,
) -> StorageResult<Vec<Self>> {
@@ -330,7 +340,7 @@ impl PaymentMethod {
pub async fn update_with_id(
self,
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
payment_method: payment_method::PaymentMethodUpdateInternal,
) -> StorageResult<Self> {
match generics::generic_update_with_unique_predicate_get_result::<
@@ -350,7 +360,7 @@ impl PaymentMethod {
}
pub async fn find_by_fingerprint_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
fingerprint_id: &str,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
@@ -361,7 +371,7 @@ impl PaymentMethod {
}
pub async fn get_count_by_merchant_id_status(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
status: common_enums::PaymentMethodStatus,
) -> StorageResult<i64> {
@@ -374,15 +384,20 @@ impl PaymentMethod {
router_env::logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());
generics::db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>(
- query.get_result_async::<i64>(conn),
+ conn.request_id(),
+ conn.event_emitter(),
generics::db_metrics::DatabaseOperation::Count,
+ query.get_result_async::<i64>(conn.raw_connection()),
)
.await
.change_context(errors::DatabaseError::Others)
.attach_printable("Failed to get a count of payment methods")
}
- pub async fn find_by_locker_id(conn: &PgPooledConn, locker_id: &str) -> StorageResult<Self> {
+ pub async fn find_by_locker_id(
+ conn: &DatabaseConnectionWithContext<'_>,
+ locker_id: &str,
+ ) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::locker_id.eq(locker_id.to_owned()),
@@ -395,7 +410,7 @@ impl payment_method::PaymentMethodUpdateInternal {
#[cfg(feature = "v1")]
pub async fn generate_drainer_update_query(
self,
- conn: &mut PgPooledConn,
+ conn: &mut DatabaseConnectionWithContext<'_>,
payment_method_id: String,
) -> StorageResult<kv::SerializableQuery> {
kv::generate_update_query_with_predicate::<<PaymentMethod as HasTable>::Table, _, _>(
@@ -410,7 +425,7 @@ impl payment_method::PaymentMethodUpdateInternal {
#[cfg(feature = "v2")]
pub async fn generate_drainer_update_query(
self,
- conn: &mut PgPooledConn,
+ conn: &mut DatabaseConnectionWithContext<'_>,
id: common_utils::id_type::GlobalPaymentMethodId,
) -> StorageResult<kv::SerializableQuery> {
kv::generate_update_query_with_predicate::<<PaymentMethod as HasTable>::Table, _, _>(
diff --git a/crates/diesel_models/src/query/payout_attempt.rs b/crates/diesel_models/src/query/payout_attempt.rs
index db01148920..34800f5e77 100644
--- a/crates/diesel_models/src/query/payout_attempt.rs
+++ b/crates/diesel_models/src/query/payout_attempt.rs
@@ -17,17 +17,20 @@ use crate::{
PayoutAttempt, PayoutAttemptNew, PayoutAttemptUpdate, PayoutAttemptUpdateInternal,
},
schema::{payout_attempt::dsl, payouts as payout_dsl},
- Payouts, PgPooledConn, StorageResult,
+ DatabaseConnectionWithContext, Payouts, StorageResult,
};
impl PayoutAttemptNew {
- pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<PayoutAttempt> {
+ pub async fn insert(
+ self,
+ conn: &DatabaseConnectionWithContext<'_>,
+ ) -> StorageResult<PayoutAttempt> {
generics::generic_insert(conn, self).await
}
pub async fn generate_drainer_insert_query(
self,
- conn: &mut PgPooledConn,
+ conn: &mut DatabaseConnectionWithContext<'_>,
) -> StorageResult<kv::SerializableQuery> {
kv::generate_insert_query(conn, self)
.await
@@ -38,7 +41,7 @@ impl PayoutAttemptNew {
impl PayoutAttempt {
pub async fn update_with_attempt_id(
self,
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
payout_attempt_update: PayoutAttemptUpdate,
) -> StorageResult<Self> {
match generics::generic_update_with_unique_predicate_get_result::<
@@ -64,7 +67,7 @@ impl PayoutAttempt {
}
pub async fn find_by_merchant_id_payout_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
payout_id: &common_utils::id_type::PayoutId,
) -> StorageResult<Vec<Self>> {
@@ -86,7 +89,7 @@ impl PayoutAttempt {
}
pub async fn find_by_merchant_id_payout_id_payout_attempt_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
payout_id: &common_utils::id_type::PayoutId,
payout_attempt_id: &str,
@@ -102,7 +105,7 @@ impl PayoutAttempt {
}
pub async fn find_by_merchant_id_payout_attempt_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
payout_attempt_id: &str,
) -> StorageResult<Self> {
@@ -116,7 +119,7 @@ impl PayoutAttempt {
}
pub async fn find_by_merchant_id_connector_payout_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
connector_payout_id: &str,
) -> StorageResult<Self> {
@@ -130,7 +133,7 @@ impl PayoutAttempt {
}
pub async fn find_by_merchant_id_merchant_order_reference_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id_input: &common_utils::id_type::MerchantId,
merchant_order_reference_id_input: &str,
) -> StorageResult<Self> {
@@ -144,7 +147,7 @@ impl PayoutAttempt {
}
pub async fn update_by_merchant_id_payout_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
payout_id: &common_utils::id_type::PayoutId,
payout: PayoutAttemptUpdate,
@@ -165,7 +168,7 @@ impl PayoutAttempt {
}
pub async fn update_by_merchant_id_payout_attempt_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
payout_attempt_id: &str,
payout: PayoutAttemptUpdate,
@@ -186,7 +189,7 @@ impl PayoutAttempt {
}
pub async fn get_filters_for_payouts(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
payouts: &[Payouts],
merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<(
@@ -230,7 +233,7 @@ impl PayoutAttempt {
.clone()
.select(dsl::connector)
.distinct()
- .get_results_async::<Option<String>>(conn)
+ .get_results_async::<Option<String>>(conn.raw_connection())
.await
.change_context(DatabaseError::Others)
.attach_printable("Error filtering records by connector")?
@@ -242,7 +245,7 @@ impl PayoutAttempt {
.clone()
.select(payout_dsl::destination_currency)
.distinct()
- .get_results_async::<enums::Currency>(conn)
+ .get_results_async::<enums::Currency>(conn.raw_connection())
.await
.change_context(DatabaseError::Others)
.attach_printable("Error filtering records by currency")?
@@ -253,7 +256,7 @@ impl PayoutAttempt {
.clone()
.select(payout_dsl::payout_type)
.distinct()
- .get_results_async::<Option<enums::PayoutType>>(conn)
+ .get_results_async::<Option<enums::PayoutType>>(conn.raw_connection())
.await
.change_context(DatabaseError::Others)
.attach_printable("Error filtering records by payout type")?
@@ -273,7 +276,7 @@ impl PayoutAttempt {
impl PayoutAttemptUpdate {
pub async fn generate_drainer_update_query(
self,
- conn: &mut PgPooledConn,
+ conn: &mut DatabaseConnectionWithContext<'_>,
payout_attempt_id: String,
merchant_id: common_utils::id_type::MerchantId,
) -> StorageResult<kv::SerializableQuery> {
diff --git a/crates/diesel_models/src/query/payouts.rs b/crates/diesel_models/src/query/payouts.rs
index 5324222a1c..bcd4edd659 100644
--- a/crates/diesel_models/src/query/payouts.rs
+++ b/crates/diesel_models/src/query/payouts.rs
@@ -11,17 +11,17 @@ use crate::{
payouts::{Payouts, PayoutsNew, PayoutsUpdate, PayoutsUpdateInternal},
query::generics::db_metrics,
schema::{payout_attempt, payouts::dsl},
- PgPooledConn, StorageResult,
+ DatabaseConnectionWithContext, StorageResult,
};
impl PayoutsNew {
- pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Payouts> {
+ pub async fn insert(self, conn: &DatabaseConnectionWithContext<'_>) -> StorageResult<Payouts> {
generics::generic_insert(conn, self).await
}
pub async fn generate_drainer_insert_query(
self,
- conn: &mut PgPooledConn,
+ conn: &mut DatabaseConnectionWithContext<'_>,
) -> StorageResult<kv::SerializableQuery> {
kv::generate_insert_query(conn, self)
.await
@@ -31,7 +31,7 @@ impl PayoutsNew {
impl Payouts {
pub async fn update(
self,
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
payout_update: PayoutsUpdate,
) -> StorageResult<Self> {
match generics::generic_update_with_results::<<Self as HasTable>::Table, _, _, _>(
@@ -54,7 +54,7 @@ impl Payouts {
}
pub async fn find_by_merchant_id_payout_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
payout_id: &common_utils::id_type::PayoutId,
) -> StorageResult<Self> {
@@ -68,7 +68,7 @@ impl Payouts {
}
pub async fn update_by_merchant_id_payout_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
payout_id: &common_utils::id_type::PayoutId,
payout: PayoutsUpdate,
@@ -89,7 +89,7 @@ impl Payouts {
}
pub async fn find_optional_by_merchant_id_payout_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
payout_id: &common_utils::id_type::PayoutId,
) -> StorageResult<Option<Self>> {
@@ -104,7 +104,7 @@ impl Payouts {
#[allow(clippy::too_many_arguments)]
pub async fn get_total_count_of_payouts(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
active_payout_ids: &[common_utils::id_type::PayoutId],
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
@@ -141,8 +141,10 @@ impl Payouts {
router_env::logger::debug!(query = %debug_query::<Pg, _>(&filter).to_string());
db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>(
- filter.get_result_async::<i64>(conn),
+ conn.request_id(),
+ conn.event_emitter(),
db_metrics::DatabaseOperation::Filter,
+ filter.get_result_async::<i64>(conn.raw_connection()),
)
.await
.change_context(errors::DatabaseError::Others)
@@ -153,7 +155,7 @@ impl Payouts {
impl PayoutsUpdate {
pub async fn generate_drainer_update_query(
self,
- conn: &mut PgPooledConn,
+ conn: &mut DatabaseConnectionWithContext<'_>,
payout_id: common_utils::id_type::PayoutId,
merchant_id: common_utils::id_type::MerchantId,
) -> StorageResult<kv::SerializableQuery> {
diff --git a/crates/diesel_models/src/query/process_tracker.rs b/crates/diesel_models/src/query/process_tracker.rs
index cedffbdea1..60e3580329 100644
--- a/crates/diesel_models/src/query/process_tracker.rs
+++ b/crates/diesel_models/src/query/process_tracker.rs
@@ -9,12 +9,15 @@ use crate::{
ProcessTracker, ProcessTrackerNew, ProcessTrackerUpdate, ProcessTrackerUpdateInternal,
},
schema::process_tracker::dsl,
- PgPooledConn, StorageResult,
+ DatabaseConnectionWithContext, StorageResult,
};
impl ProcessTrackerNew {
#[instrument(skip(conn))]
- pub async fn insert_process(self, conn: &PgPooledConn) -> StorageResult<ProcessTracker> {
+ pub async fn insert_process(
+ self,
+ conn: &DatabaseConnectionWithContext<'_>,
+ ) -> StorageResult<ProcessTracker> {
generics::generic_insert(conn, self).await
}
}
@@ -23,7 +26,7 @@ impl ProcessTracker {
#[instrument(skip(conn))]
pub async fn update(
self,
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
process: ProcessTrackerUpdate,
) -> StorageResult<Self> {
match generics::generic_update_by_id::<<Self as HasTable>::Table, _, _, _>(
@@ -43,7 +46,7 @@ impl ProcessTracker {
#[instrument(skip(conn))]
pub async fn update_process_status_by_ids(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
task_ids: Vec<String>,
task_update: ProcessTrackerUpdate,
) -> StorageResult<usize> {
@@ -56,7 +59,10 @@ impl ProcessTracker {
}
#[instrument(skip(conn))]
- pub async fn find_process_by_id(conn: &PgPooledConn, id: &str) -> StorageResult<Option<Self>> {
+ pub async fn find_process_by_id(
+ conn: &DatabaseConnectionWithContext<'_>,
+ id: &str,
+ ) -> StorageResult<Option<Self>> {
generics::generic_find_by_id_optional::<<Self as HasTable>::Table, _, _>(
conn,
id.to_owned(),
@@ -66,7 +72,7 @@ impl ProcessTracker {
#[instrument(skip(conn))]
pub async fn find_processes_by_time_status(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
time_lower_limit: PrimitiveDateTime,
time_upper_limit: PrimitiveDateTime,
status: enums::ProcessTrackerStatus,
@@ -93,7 +99,7 @@ impl ProcessTracker {
#[instrument(skip(conn))]
pub async fn find_processes_to_clean(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
time_lower_limit: PrimitiveDateTime,
time_upper_limit: PrimitiveDateTime,
runner: &str,
@@ -123,7 +129,7 @@ impl ProcessTracker {
#[instrument(skip(conn))]
pub async fn reinitialize_limbo_processes(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
ids: Vec<String>,
schedule_time: PrimitiveDateTime,
) -> StorageResult<usize> {
diff --git a/crates/diesel_models/src/query/refund.rs b/crates/diesel_models/src/query/refund.rs
index b764e90e4b..8707a50641 100644
--- a/crates/diesel_models/src/query/refund.rs
+++ b/crates/diesel_models/src/query/refund.rs
@@ -9,17 +9,17 @@ use crate::schema_v2::refund::dsl;
use crate::{
errors, kv,
refund::{Refund, RefundNew, RefundUpdate, RefundUpdateInternal},
- PgPooledConn, StorageResult,
+ DatabaseConnectionWithContext, StorageResult,
};
impl RefundNew {
- pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Refund> {
+ pub async fn insert(self, conn: &DatabaseConnectionWithContext<'_>) -> StorageResult<Refund> {
generics::generic_insert(conn, self).await
}
pub async fn generate_drainer_insert_query(
self,
- conn: &mut PgPooledConn,
+ conn: &mut DatabaseConnectionWithContext<'_>,
) -> StorageResult<kv::SerializableQuery> {
kv::generate_insert_query(conn, self)
.await
@@ -29,7 +29,11 @@ impl RefundNew {
#[cfg(feature = "v1")]
impl Refund {
- pub async fn update(self, conn: &PgPooledConn, refund: RefundUpdate) -> StorageResult<Self> {
+ pub async fn update(
+ self,
+ conn: &DatabaseConnectionWithContext<'_>,
+ refund: RefundUpdate,
+ ) -> StorageResult<Self> {
let processor_merchant_id = self
.processor_merchant_id
.clone()
@@ -59,7 +63,7 @@ impl Refund {
// Fallback function for stagger release - updates by merchant_id when processor_merchant_id is NULL
pub async fn update_by_merchant_id(
self,
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
refund: RefundUpdate,
) -> StorageResult<Self> {
let processor_merchant_id = self
@@ -90,7 +94,7 @@ impl Refund {
// This is required to be changed for KV.
pub async fn find_by_processor_merchant_id_refund_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
processor_merchant_id: &common_utils::id_type::MerchantId,
refund_id: &str,
) -> StorageResult<Self> {
@@ -105,7 +109,7 @@ impl Refund {
// Fallback function for stagger release - queries by merchant_id when processor_merchant_id is NULL
pub async fn find_by_merchant_id_refund_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
processor_merchant_id: &common_utils::id_type::MerchantId,
refund_id: &str,
) -> StorageResult<Self> {
@@ -119,7 +123,7 @@ impl Refund {
}
pub async fn find_by_processor_merchant_id_connector_refund_id_connector(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
processor_merchant_id: &common_utils::id_type::MerchantId,
connector_refund_id: &str,
connector: &str,
@@ -136,7 +140,7 @@ impl Refund {
// Fallback function for stagger release - queries by merchant_id when processor_merchant_id is NULL
pub async fn find_by_merchant_id_connector_refund_id_connector(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
processor_merchant_id: &common_utils::id_type::MerchantId,
connector_refund_id: &str,
connector: &str,
@@ -152,7 +156,7 @@ impl Refund {
}
pub async fn find_by_internal_reference_id_processor_merchant_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
internal_reference_id: &str,
processor_merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Self> {
@@ -167,7 +171,7 @@ impl Refund {
// Fallback function for stagger release - queries by merchant_id when processor_merchant_id is NULL
pub async fn find_by_internal_reference_id_merchant_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
internal_reference_id: &str,
processor_merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Self> {
@@ -181,7 +185,7 @@ impl Refund {
}
pub async fn find_by_processor_merchant_id_connector_transaction_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
processor_merchant_id: &common_utils::id_type::MerchantId,
connector_transaction_id: &str,
) -> StorageResult<Vec<Self>> {
@@ -206,7 +210,7 @@ impl Refund {
}
pub async fn find_by_payment_id_processor_merchant_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
payment_id: &common_utils::id_type::PaymentId,
processor_merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Vec<Self>> {
@@ -244,7 +248,7 @@ impl Refund {
impl Refund {
pub async fn update_with_id(
self,
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
refund: RefundUpdate,
) -> StorageResult<Self> {
match generics::generic_update_by_id::<<Self as HasTable>::Table, _, _, _>(
@@ -263,7 +267,7 @@ impl Refund {
}
pub async fn find_by_global_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
id: &common_utils::id_type::GlobalRefundId,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
@@ -274,7 +278,7 @@ impl Refund {
}
pub async fn find_by_merchant_id_connector_transaction_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
connector_transaction_id: &str,
) -> StorageResult<Vec<Self>> {
@@ -300,7 +304,7 @@ impl RefundUpdate {
#[cfg(feature = "v1")]
pub async fn generate_drainer_update_query(
self,
- conn: &mut PgPooledConn,
+ conn: &mut DatabaseConnectionWithContext<'_>,
refund_id: String,
processor_merchant_id: common_utils::id_type::MerchantId,
) -> StorageResult<kv::SerializableQuery> {
@@ -318,7 +322,7 @@ impl RefundUpdate {
#[cfg(feature = "v2")]
pub async fn generate_drainer_update_query(
self,
- conn: &mut PgPooledConn,
+ conn: &mut DatabaseConnectionWithContext<'_>,
id: common_utils::id_type::GlobalRefundId,
) -> StorageResult<kv::SerializableQuery> {
kv::generate_update_query_by_id::<<Refund as HasTable>::Table, _, _>(
diff --git a/crates/diesel_models/src/query/relay.rs b/crates/diesel_models/src/query/relay.rs
index 217f6fd734..73a2afcacc 100644
--- a/crates/diesel_models/src/query/relay.rs
+++ b/crates/diesel_models/src/query/relay.rs
@@ -5,11 +5,11 @@ use crate::{
errors,
relay::{Relay, RelayNew, RelayUpdateInternal},
schema::relay::dsl,
- PgPooledConn, StorageResult,
+ DatabaseConnectionWithContext, StorageResult,
};
impl RelayNew {
- pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Relay> {
+ pub async fn insert(self, conn: &DatabaseConnectionWithContext<'_>) -> StorageResult<Relay> {
generics::generic_insert(conn, self).await
}
}
@@ -17,7 +17,7 @@ impl RelayNew {
impl Relay {
pub async fn update(
self,
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
relay: RelayUpdateInternal,
) -> StorageResult<Self> {
match generics::generic_update_with_unique_predicate_get_result::<
@@ -37,7 +37,7 @@ impl Relay {
}
pub async fn find_by_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
id: &common_utils::id_type::RelayId,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
@@ -48,7 +48,7 @@ impl Relay {
}
pub async fn find_by_profile_id_connector_reference_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
profile_id: &common_utils::id_type::ProfileId,
connector_reference_id: &str,
) -> StorageResult<Self> {
diff --git a/crates/diesel_models/src/query/reverse_lookup.rs b/crates/diesel_models/src/query/reverse_lookup.rs
index d216d1c754..fe07a6cca6 100644
--- a/crates/diesel_models/src/query/reverse_lookup.rs
+++ b/crates/diesel_models/src/query/reverse_lookup.rs
@@ -6,17 +6,20 @@ use crate::{
kv,
reverse_lookup::{ReverseLookup, ReverseLookupNew},
schema::reverse_lookup::dsl,
- PgPooledConn, StorageResult,
+ DatabaseConnectionWithContext, StorageResult,
};
impl ReverseLookupNew {
- pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<ReverseLookup> {
+ pub async fn insert(
+ self,
+ conn: &DatabaseConnectionWithContext<'_>,
+ ) -> StorageResult<ReverseLookup> {
generics::generic_insert(conn, self).await
}
pub async fn batch_insert(
reverse_lookups: Vec<Self>,
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
) -> StorageResult<()> {
generics::generic_insert::<_, _, ReverseLookup>(conn, reverse_lookups).await?;
Ok(())
@@ -24,7 +27,7 @@ impl ReverseLookupNew {
pub async fn generate_drainer_insert_query(
self,
- conn: &mut PgPooledConn,
+ conn: &mut DatabaseConnectionWithContext<'_>,
) -> StorageResult<kv::SerializableQuery> {
kv::generate_insert_query(conn, self)
.await
@@ -32,7 +35,10 @@ impl ReverseLookupNew {
}
}
impl ReverseLookup {
- pub async fn find_by_lookup_id(lookup_id: &str, conn: &PgPooledConn) -> StorageResult<Self> {
+ pub async fn find_by_lookup_id(
+ lookup_id: &str,
+ conn: &DatabaseConnectionWithContext<'_>,
+ ) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::lookup_id.eq(lookup_id.to_owned()),
diff --git a/crates/diesel_models/src/query/role.rs b/crates/diesel_models/src/query/role.rs
index 09542dc7f9..18a357870a 100644
--- a/crates/diesel_models/src/query/role.rs
+++ b/crates/diesel_models/src/query/role.rs
@@ -9,12 +9,12 @@ use error_stack::{report, ResultExt};
use strum::IntoEnumIterator;
use crate::{
- enums::RoleScope, errors, query::generics, role::*, schema::roles::dsl, PgPooledConn,
- StorageResult,
+ enums::RoleScope, errors, query::generics, role::*, schema::roles::dsl,
+ DatabaseConnectionWithContext, StorageResult,
};
impl RoleNew {
- pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Role> {
+ pub async fn insert(self, conn: &DatabaseConnectionWithContext<'_>) -> StorageResult<Role> {
generics::generic_insert(conn, self).await
}
}
@@ -33,7 +33,10 @@ impl Role {
.unwrap_or(vec![current_entity])
}
- pub async fn find_by_role_id(conn: &PgPooledConn, role_id: &str) -> StorageResult<Self> {
+ pub async fn find_by_role_id(
+ conn: &DatabaseConnectionWithContext<'_>,
+ role_id: &str,
+ ) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::role_id.eq(role_id.to_owned()),
@@ -42,7 +45,7 @@ impl Role {
}
pub async fn find_by_role_id_in_lineage(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
role_id: &str,
merchant_id: &id_type::MerchantId,
org_id: &id_type::OrganizationId,
@@ -70,7 +73,7 @@ impl Role {
}
pub async fn find_by_role_id_org_id_tenant_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
role_id: &str,
org_id: &id_type::OrganizationId,
tenant_id: &id_type::TenantId,
@@ -86,7 +89,7 @@ impl Role {
}
pub async fn update_by_role_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
role_id: &str,
role_update: RoleUpdate,
) -> StorageResult<Self> {
@@ -103,7 +106,10 @@ impl Role {
.await
}
- pub async fn delete_by_role_id(conn: &PgPooledConn, role_id: &str) -> StorageResult<Self> {
+ pub async fn delete_by_role_id(
+ conn: &DatabaseConnectionWithContext<'_>,
+ role_id: &str,
+ ) -> StorageResult<Self> {
generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>(
conn,
dsl::role_id.eq(role_id.to_owned()),
@@ -113,7 +119,7 @@ impl Role {
//TODO: Remove once generic_list_roles_by_entity_type is stable
pub async fn generic_roles_list_for_org(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
tenant_id: id_type::TenantId,
org_id: id_type::OrganizationId,
merchant_id: Option<id_type::MerchantId>,
@@ -145,8 +151,10 @@ impl Role {
router_env::logger::debug!(query = %debug_query::<Pg,_>(&query).to_string());
match generics::db_metrics::track_database_call::<Self, _, _>(
- query.get_results_async(conn),
+ conn.request_id(),
+ conn.event_emitter(),
generics::db_metrics::DatabaseOperation::Filter,
+ query.get_results_async(conn.raw_connection()),
)
.await
{
@@ -161,7 +169,7 @@ impl Role {
}
pub async fn generic_list_roles_by_entity_type(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
payload: ListRolesByEntityPayload,
is_lineage_data_required: bool,
tenant_id: id_type::TenantId,
@@ -209,8 +217,10 @@ impl Role {
router_env::logger::debug!(query = %debug_query::<Pg,_>(&query).to_string());
match generics::db_metrics::track_database_call::<Self, _, _>(
- query.get_results_async(conn),
+ conn.request_id(),
+ conn.event_emitter(),
generics::db_metrics::DatabaseOperation::Filter,
+ query.get_results_async(conn.raw_connection()),
)
.await
{
diff --git a/crates/diesel_models/src/query/routing_algorithm.rs b/crates/diesel_models/src/query/routing_algorithm.rs
index fae45c9915..0ea6ff12e2 100644
--- a/crates/diesel_models/src/query/routing_algorithm.rs
+++ b/crates/diesel_models/src/query/routing_algorithm.rs
@@ -9,16 +9,16 @@ use crate::{
query::generics,
routing_algorithm::{RoutingAlgorithm, RoutingProfileMetadata},
schema::routing_algorithm::dsl,
- PgPooledConn, StorageResult,
+ DatabaseConnectionWithContext, StorageResult,
};
impl RoutingAlgorithm {
- pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Self> {
+ pub async fn insert(self, conn: &DatabaseConnectionWithContext<'_>) -> StorageResult<Self> {
generics::generic_insert(conn, self).await
}
pub async fn find_by_algorithm_id_merchant_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
algorithm_id: &common_utils::id_type::RoutingId,
merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Self> {
@@ -32,7 +32,7 @@ impl RoutingAlgorithm {
}
pub async fn find_by_algorithm_id_processor_merchant_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
algorithm_id: &common_utils::id_type::RoutingId,
processor_merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Self> {
@@ -46,7 +46,7 @@ impl RoutingAlgorithm {
}
pub async fn find_by_algorithm_id_profile_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
algorithm_id: &common_utils::id_type::RoutingId,
profile_id: &common_utils::id_type::ProfileId,
) -> StorageResult<Self> {
@@ -60,7 +60,7 @@ impl RoutingAlgorithm {
}
pub async fn find_metadata_by_algorithm_id_profile_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
algorithm_id: &common_utils::id_type::RoutingId,
profile_id: &common_utils::id_type::ProfileId,
) -> StorageResult<RoutingProfileMetadata> {
@@ -90,7 +90,7 @@ impl RoutingAlgorithm {
PrimitiveDateTime,
PrimitiveDateTime,
enums::TransactionType,
- )>(conn)
+ )>(conn.raw_connection())
.await
.change_context(DatabaseError::Others)?
.into_iter()
@@ -122,7 +122,7 @@ impl RoutingAlgorithm {
}
pub async fn list_metadata_by_profile_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
profile_id: &common_utils::id_type::ProfileId,
limit: i64,
offset: i64,
@@ -153,7 +153,7 @@ impl RoutingAlgorithm {
PrimitiveDateTime,
PrimitiveDateTime,
enums::TransactionType,
- )>(conn)
+ )>(conn.raw_connection())
.await
.change_context(DatabaseError::Others)?
.into_iter()
@@ -184,7 +184,7 @@ impl RoutingAlgorithm {
}
pub async fn list_metadata_by_merchant_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
limit: i64,
offset: i64,
@@ -220,7 +220,7 @@ impl RoutingAlgorithm {
PrimitiveDateTime,
PrimitiveDateTime,
enums::TransactionType,
- )>(conn)
+ )>(conn.raw_connection())
.await
.change_context(DatabaseError::Others)?
.into_iter()
@@ -251,7 +251,7 @@ impl RoutingAlgorithm {
}
pub async fn list_metadata_by_merchant_id_transaction_type(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
transaction_type: &enums::TransactionType,
limit: i64,
@@ -289,7 +289,7 @@ impl RoutingAlgorithm {
PrimitiveDateTime,
PrimitiveDateTime,
enums::TransactionType,
- )>(conn)
+ )>(conn.raw_connection())
.await
.change_context(DatabaseError::Others)?
.into_iter()
@@ -330,7 +330,7 @@ impl RoutingAlgorithm {
/// profile under what this returns, and under the provider there is no such profile. The
/// column is null on rules written before platform support, where the two are the same.
pub async fn rule_ids_for_profiles(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
profile_ids: &[common_utils::id_type::ProfileId],
) -> StorageResult<
Vec<(
@@ -356,7 +356,7 @@ impl RoutingAlgorithm {
common_utils::id_type::MerchantId,
common_utils::id_type::RoutingId,
enums::RoutingAlgorithmKind,
- )>(conn)
+ )>(conn.raw_connection())
.await
.change_context(DatabaseError::Others)
.map(|rows| {
@@ -378,7 +378,7 @@ impl RoutingAlgorithm {
/// A page of the profiles that hold routing rules. Grouped so the page is of profiles —
/// paginating per rule would split one across pages. Ordered so paging is stable.
pub async fn list_scope_page(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
limit: i64,
offset: i64,
) -> StorageResult<
@@ -396,7 +396,7 @@ impl RoutingAlgorithm {
.load_async::<(
common_utils::id_type::ProfileId,
common_utils::id_type::MerchantId,
- )>(conn)
+ )>(conn.raw_connection())
.await
.change_context(DatabaseError::Others)
}
diff --git a/crates/diesel_models/src/query/subscription.rs b/crates/diesel_models/src/query/subscription.rs
index 1a7593c40e..f0bf6db771 100644
--- a/crates/diesel_models/src/query/subscription.rs
+++ b/crates/diesel_models/src/query/subscription.rs
@@ -6,18 +6,21 @@ use crate::{
errors,
schema::subscription::dsl,
subscription::{Subscription, SubscriptionNew, SubscriptionUpdate},
- PgPooledConn, StorageResult,
+ DatabaseConnectionWithContext, StorageResult,
};
impl SubscriptionNew {
- pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Subscription> {
+ pub async fn insert(
+ self,
+ conn: &DatabaseConnectionWithContext<'_>,
+ ) -> StorageResult<Subscription> {
generics::generic_insert(conn, self).await
}
}
impl Subscription {
pub async fn find_by_merchant_id_subscription_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
id: String,
) -> StorageResult<Self> {
@@ -31,7 +34,7 @@ impl Subscription {
}
pub async fn update_subscription_entry(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
id: String,
subscription_update: SubscriptionUpdate,
@@ -58,7 +61,7 @@ impl Subscription {
}
pub async fn list_by_merchant_id_profile_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
profile_id: &common_utils::id_type::ProfileId,
limit: Option<i64>,
diff --git a/crates/diesel_models/src/query/tokenization.rs b/crates/diesel_models/src/query/tokenization.rs
index 2991b89ecf..502e6e69b3 100644
--- a/crates/diesel_models/src/query/tokenization.rs
+++ b/crates/diesel_models/src/query/tokenization.rs
@@ -6,17 +6,17 @@ use diesel::ExpressionMethods;
#[cfg(feature = "v2")]
use crate::{
errors, query::generics, schema_v2::tokenization, tokenization as tokenization_diesel,
- PgPooledConn, StorageResult,
+ DatabaseConnectionWithContext, StorageResult,
};
#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
impl tokenization_diesel::Tokenization {
- pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Self> {
+ pub async fn insert(self, conn: &DatabaseConnectionWithContext<'_>) -> StorageResult<Self> {
generics::generic_insert(conn, self).await
}
pub async fn find_by_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
id: &common_utils::id_type::GlobalTokenId,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
@@ -28,7 +28,7 @@ impl tokenization_diesel::Tokenization {
pub async fn update_with_id(
self,
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
tokenization_record: tokenization_diesel::TokenizationUpdateInternal,
) -> StorageResult<Self> {
match generics::generic_update_with_unique_predicate_get_result::<
diff --git a/crates/diesel_models/src/query/unified_translations.rs b/crates/diesel_models/src/query/unified_translations.rs
index 1b0d54cc75..35dc490b5a 100644
--- a/crates/diesel_models/src/query/unified_translations.rs
+++ b/crates/diesel_models/src/query/unified_translations.rs
@@ -6,18 +6,21 @@ use crate::{
query::generics,
schema::unified_translations::dsl,
unified_translations::{UnifiedTranslationsUpdateInternal, *},
- PgPooledConn, StorageResult,
+ DatabaseConnectionWithContext, StorageResult,
};
impl UnifiedTranslationsNew {
- pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<UnifiedTranslations> {
+ pub async fn insert(
+ self,
+ conn: &DatabaseConnectionWithContext<'_>,
+ ) -> StorageResult<UnifiedTranslations> {
generics::generic_insert(conn, self).await
}
}
impl UnifiedTranslations {
pub async fn find_by_unified_code_unified_message_locale(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
unified_code: String,
unified_message: String,
locale: String,
@@ -33,7 +36,7 @@ impl UnifiedTranslations {
}
pub async fn update_by_unified_code_unified_message_locale(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
unified_code: String,
unified_message: String,
locale: String,
@@ -62,7 +65,7 @@ impl UnifiedTranslations {
}
pub async fn delete_by_unified_code_unified_message_locale(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
unified_code: String,
unified_message: String,
locale: String,
diff --git a/crates/diesel_models/src/query/user.rs b/crates/diesel_models/src/query/user.rs
index 5d35a02f15..a14e01ccd7 100644
--- a/crates/diesel_models/src/query/user.rs
+++ b/crates/diesel_models/src/query/user.rs
@@ -5,18 +5,19 @@ pub mod sample_data;
pub mod theme;
use crate::{
- query::generics, schema::users::dsl as users_dsl, user::*, PgPooledConn, StorageResult,
+ query::generics, schema::users::dsl as users_dsl, user::*, DatabaseConnectionWithContext,
+ StorageResult,
};
impl UserNew {
- pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<User> {
+ pub async fn insert(self, conn: &DatabaseConnectionWithContext<'_>) -> StorageResult<User> {
generics::generic_insert(conn, self).await
}
}
impl User {
pub async fn find_active_by_user_email(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
user_email: &pii::Email,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
@@ -31,7 +32,7 @@ impl User {
}
pub async fn find_by_user_email(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
user_email: &pii::Email,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
@@ -41,7 +42,10 @@ impl User {
.await
}
- pub async fn find_active_by_user_id(conn: &PgPooledConn, user_id: &str) -> StorageResult<Self> {
+ pub async fn find_active_by_user_id(
+ conn: &DatabaseConnectionWithContext<'_>,
+ user_id: &str,
+ ) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
users_dsl::user_id.eq(user_id.to_owned()).and(
@@ -53,7 +57,10 @@ impl User {
.await
}
- pub async fn find_by_user_id(conn: &PgPooledConn, user_id: &str) -> StorageResult<Self> {
+ pub async fn find_by_user_id(
+ conn: &DatabaseConnectionWithContext<'_>,
+ user_id: &str,
+ ) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
users_dsl::user_id.eq(user_id.to_owned()),
@@ -62,7 +69,7 @@ impl User {
}
pub async fn update_active_by_user_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
user_id: &str,
user_update: UserUpdate,
) -> StorageResult<Self> {
@@ -84,7 +91,7 @@ impl User {
}
pub async fn update_active_by_user_email(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
user_email: &pii::Email,
user_update: UserUpdate,
) -> StorageResult<Self> {
@@ -106,7 +113,7 @@ impl User {
}
pub async fn find_active_users_by_user_ids(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
user_ids: Vec<String>,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<
@@ -129,7 +136,7 @@ impl User {
}
pub async fn list_users_by_user_ids(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
user_ids: Vec<String>,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<
@@ -142,7 +149,7 @@ impl User {
}
pub async fn reactivate_by_user_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
user_id: &str,
user_update: ReactivateUserUpdate,
) -> StorageResult<Self> {
diff --git a/crates/diesel_models/src/query/user/sample_data.rs b/crates/diesel_models/src/query/user/sample_data.rs
index 40cd264c05..73a7ff0e47 100644
--- a/crates/diesel_models/src/query/user/sample_data.rs
+++ b/crates/diesel_models/src/query/user/sample_data.rs
@@ -14,15 +14,15 @@ use crate::schema_v2::{
refund::dsl as refund_dsl,
};
use crate::{
- errors, schema::dispute::dsl as dispute_dsl, Dispute, DisputeNew, PaymentAttempt,
- PaymentIntent, PgPooledConn, Refund, RefundNew, StorageResult,
+ errors, schema::dispute::dsl as dispute_dsl, DatabaseConnectionWithContext, Dispute,
+ DisputeNew, PaymentAttempt, PaymentIntent, Refund, RefundNew, StorageResult,
};
#[cfg(feature = "v1")]
use crate::{user, PaymentIntentNew};
#[cfg(feature = "v1")]
pub async fn insert_payment_intents(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
batch: Vec<PaymentIntentNew>,
) -> StorageResult<Vec<PaymentIntent>> {
let query = diesel::insert_into(<PaymentIntent>::table()).values(batch);
@@ -30,7 +30,7 @@ pub async fn insert_payment_intents(
logger::debug!(query = %debug_query::<diesel::pg::Pg,_>(&query).to_string());
query
- .get_results_async(conn)
+ .get_results_async(conn.raw_connection())
.await
.change_context(errors::DatabaseError::Others)
.attach_printable("Error while inserting payment intents")
@@ -38,7 +38,7 @@ pub async fn insert_payment_intents(
#[cfg(feature = "v1")]
pub async fn insert_payment_attempts(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
batch: Vec<user::sample_data::PaymentAttemptBatchNew>,
) -> StorageResult<Vec<PaymentAttempt>> {
let query = diesel::insert_into(<PaymentAttempt>::table()).values(batch);
@@ -46,14 +46,14 @@ pub async fn insert_payment_attempts(
logger::debug!(query = %debug_query::<diesel::pg::Pg,_>(&query).to_string());
query
- .get_results_async(conn)
+ .get_results_async(conn.raw_connection())
.await
.change_context(errors::DatabaseError::Others)
.attach_printable("Error while inserting payment attempts")
}
pub async fn insert_refunds(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
batch: Vec<RefundNew>,
) -> StorageResult<Vec<Refund>> {
let query = diesel::insert_into(<Refund>::table()).values(batch);
@@ -61,14 +61,14 @@ pub async fn insert_refunds(
logger::debug!(query = %debug_query::<diesel::pg::Pg,_>(&query).to_string());
query
- .get_results_async(conn)
+ .get_results_async(conn.raw_connection())
.await
.change_context(errors::DatabaseError::Others)
.attach_printable("Error while inserting refunds")
}
pub async fn insert_disputes(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
batch: Vec<DisputeNew>,
) -> StorageResult<Vec<Dispute>> {
let query = diesel::insert_into(<Dispute>::table()).values(batch);
@@ -76,7 +76,7 @@ pub async fn insert_disputes(
logger::debug!(query = %debug_query::<diesel::pg::Pg,_>(&query).to_string());
query
- .get_results_async(conn)
+ .get_results_async(conn.raw_connection())
.await
.change_context(errors::DatabaseError::Others)
.attach_printable("Error while inserting disputes")
@@ -84,7 +84,7 @@ pub async fn insert_disputes(
#[cfg(feature = "v1")]
pub async fn delete_payment_intents(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Vec<PaymentIntent>> {
let query = diesel::delete(<PaymentIntent>::table())
@@ -94,7 +94,7 @@ pub async fn delete_payment_intents(
logger::debug!(query = %debug_query::<diesel::pg::Pg,_>(&query).to_string());
query
- .get_results_async(conn)
+ .get_results_async(conn.raw_connection())
.await
.change_context(errors::DatabaseError::Others)
.attach_printable("Error while deleting payment intents")
@@ -111,7 +111,7 @@ pub async fn delete_payment_intents(
#[cfg(feature = "v2")]
pub async fn delete_payment_intents(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Vec<PaymentIntent>> {
let query = diesel::delete(<PaymentIntent>::table())
@@ -121,7 +121,7 @@ pub async fn delete_payment_intents(
logger::debug!(query = %debug_query::<diesel::pg::Pg,_>(&query).to_string());
query
- .get_results_async(conn)
+ .get_results_async(conn.raw_connection())
.await
.change_context(errors::DatabaseError::Others)
.attach_printable("Error while deleting payment intents")
@@ -136,7 +136,7 @@ pub async fn delete_payment_intents(
})
}
pub async fn delete_payment_attempts(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Vec<PaymentAttempt>> {
let query = diesel::delete(<PaymentAttempt>::table())
@@ -146,7 +146,7 @@ pub async fn delete_payment_attempts(
logger::debug!(query = %debug_query::<diesel::pg::Pg,_>(&query).to_string());
query
- .get_results_async(conn)
+ .get_results_async(conn.raw_connection())
.await
.change_context(errors::DatabaseError::Others)
.attach_printable("Error while deleting payment attempts")
@@ -162,7 +162,7 @@ pub async fn delete_payment_attempts(
}
pub async fn delete_refunds(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Vec<Refund>> {
let query = diesel::delete(<Refund>::table())
@@ -172,7 +172,7 @@ pub async fn delete_refunds(
logger::debug!(query = %debug_query::<diesel::pg::Pg,_>(&query).to_string());
query
- .get_results_async(conn)
+ .get_results_async(conn.raw_connection())
.await
.change_context(errors::DatabaseError::Others)
.attach_printable("Error while deleting refunds")
@@ -188,7 +188,7 @@ pub async fn delete_refunds(
}
pub async fn delete_disputes(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Vec<Dispute>> {
let query = diesel::delete(<Dispute>::table())
@@ -198,7 +198,7 @@ pub async fn delete_disputes(
logger::debug!(query = %debug_query::<diesel::pg::Pg,_>(&query).to_string());
query
- .get_results_async(conn)
+ .get_results_async(conn.raw_connection())
.await
.change_context(errors::DatabaseError::Others)
.attach_printable("Error while deleting disputes")
diff --git a/crates/diesel_models/src/query/user/theme.rs b/crates/diesel_models/src/query/user/theme.rs
index 68b225eaf6..18c4288a3f 100644
--- a/crates/diesel_models/src/query/user/theme.rs
+++ b/crates/diesel_models/src/query/user/theme.rs
@@ -19,11 +19,11 @@ use crate::{
},
schema::themes::dsl,
user::theme::{Theme, ThemeNew, ThemeUpdate, ThemeUpdateInternal},
- PgPooledConn, StorageResult,
+ DatabaseConnectionWithContext, StorageResult,
};
impl ThemeNew {
- pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Theme> {
+ pub async fn insert(self, conn: &DatabaseConnectionWithContext<'_>) -> StorageResult<Theme> {
generics::generic_insert(conn, self).await
}
}
@@ -119,7 +119,10 @@ impl Theme {
}
}
- pub async fn find_by_theme_id(conn: &PgPooledConn, theme_id: String) -> StorageResult<Self> {
+ pub async fn find_by_theme_id(
+ conn: &DatabaseConnectionWithContext<'_>,
+ theme_id: String,
+ ) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::theme_id.eq(theme_id),
@@ -128,7 +131,7 @@ impl Theme {
}
pub async fn find_most_specific_theme_in_lineage(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
lineage: ThemeLineage,
) -> StorageResult<Self> {
let query = crate::list::into_boxed_list(<Self as HasTable>::table());
@@ -145,8 +148,10 @@ impl Theme {
logger::debug!(query = %debug_query::<Pg,_>(&query).to_string());
let data: Vec<Self> = match track_database_call::<Self, _, _>(
- query.get_results_async(conn),
+ conn.request_id(),
+ conn.event_emitter(),
DatabaseOperation::Filter,
+ query.get_results_async(conn.raw_connection()),
)
.await
{
@@ -163,7 +168,7 @@ impl Theme {
}
pub async fn find_by_lineage(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
lineage: ThemeLineage,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
@@ -174,7 +179,7 @@ impl Theme {
}
pub async fn update_by_theme_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
theme_id: String,
update: ThemeUpdate,
) -> StorageResult<Self> {
@@ -191,7 +196,7 @@ impl Theme {
}
pub async fn delete_by_theme_id_and_lineage(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
theme_id: String,
lineage: ThemeLineage,
) -> StorageResult<Self> {
@@ -203,7 +208,10 @@ impl Theme {
)
.await
}
- pub async fn delete_by_theme_id(conn: &PgPooledConn, theme_id: String) -> StorageResult<Self> {
+ pub async fn delete_by_theme_id(
+ conn: &DatabaseConnectionWithContext<'_>,
+ theme_id: String,
+ ) -> StorageResult<Self> {
generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>(
conn,
dsl::theme_id.eq(theme_id),
@@ -212,7 +220,7 @@ impl Theme {
}
/// Finds all themes that match the specified lineage hierarchy.
pub async fn find_all_by_lineage_hierarchy(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
lineage: ThemeLineage,
) -> StorageResult<Vec<Self>> {
let filter = Self::lineage_hierarchy_filter(lineage);
@@ -222,8 +230,10 @@ impl Theme {
logger::debug!(query = %debug_query::<Pg,_>(&query).to_string());
match track_database_call::<Self, _, _>(
- query.get_results_async(conn),
+ conn.request_id(),
+ conn.event_emitter(),
DatabaseOperation::Filter,
+ query.get_results_async(conn.raw_connection()),
)
.await
{
diff --git a/crates/diesel_models/src/query/user_authentication_method.rs b/crates/diesel_models/src/query/user_authentication_method.rs
index b9ed95e37c..6d1348ca44 100644
--- a/crates/diesel_models/src/query/user_authentication_method.rs
+++ b/crates/diesel_models/src/query/user_authentication_method.rs
@@ -2,25 +2,28 @@ use diesel::{associations::HasTable, ExpressionMethods};
use crate::{
query::generics, schema::user_authentication_methods::dsl, user_authentication_method::*,
- PgPooledConn, StorageResult,
+ DatabaseConnectionWithContext, StorageResult,
};
impl UserAuthenticationMethodNew {
- pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<UserAuthenticationMethod> {
+ pub async fn insert(
+ self,
+ conn: &DatabaseConnectionWithContext<'_>,
+ ) -> StorageResult<UserAuthenticationMethod> {
generics::generic_insert(conn, self).await
}
}
impl UserAuthenticationMethod {
pub async fn get_user_authentication_method_by_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
id: &str,
) -> StorageResult<Self> {
generics::generic_find_by_id::<<Self as HasTable>::Table, _, _>(conn, id.to_owned()).await
}
pub async fn list_user_authentication_methods_for_auth_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
auth_id: &str,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
@@ -34,7 +37,7 @@ impl UserAuthenticationMethod {
}
pub async fn list_user_authentication_methods_for_owner_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
owner_id: &str,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
@@ -48,7 +51,7 @@ impl UserAuthenticationMethod {
}
pub async fn update_user_authentication_method(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
id: &str,
user_authentication_method_update: UserAuthenticationMethodUpdate,
) -> StorageResult<Self> {
@@ -66,7 +69,7 @@ impl UserAuthenticationMethod {
}
pub async fn list_user_authentication_methods_for_email_domain(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
email_domain: &str,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
diff --git a/crates/diesel_models/src/query/user_key_store.rs b/crates/diesel_models/src/query/user_key_store.rs
index 78d1648b47..0225d5f166 100644
--- a/crates/diesel_models/src/query/user_key_store.rs
+++ b/crates/diesel_models/src/query/user_key_store.rs
@@ -4,18 +4,21 @@ use super::generics;
use crate::{
schema::user_key_store::dsl,
user_key_store::{UserKeyStore, UserKeyStoreNew},
- PgPooledConn, StorageResult,
+ DatabaseConnectionWithContext, StorageResult,
};
impl UserKeyStoreNew {
- pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<UserKeyStore> {
+ pub async fn insert(
+ self,
+ conn: &DatabaseConnectionWithContext<'_>,
+ ) -> StorageResult<UserKeyStore> {
generics::generic_insert(conn, self).await
}
}
impl UserKeyStore {
pub async fn get_all_user_key_stores(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
from: u32,
limit: u32,
) -> StorageResult<Vec<Self>> {
@@ -34,7 +37,10 @@ impl UserKeyStore {
.await
}
- pub async fn find_by_user_id(conn: &PgPooledConn, user_id: &str) -> StorageResult<Self> {
+ pub async fn find_by_user_id(
+ conn: &DatabaseConnectionWithContext<'_>,
+ user_id: &str,
+ ) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::user_id.eq(user_id.to_owned()),
diff --git a/crates/diesel_models/src/query/user_role.rs b/crates/diesel_models/src/query/user_role.rs
index 38774f6650..fa05476b0e 100644
--- a/crates/diesel_models/src/query/user_role.rs
+++ b/crates/diesel_models/src/query/user_role.rs
@@ -17,11 +17,11 @@ use crate::{
query::generics,
schema::user_roles::dsl,
user_role::*,
- PgPooledConn, StorageResult,
+ DatabaseConnectionWithContext, StorageResult,
};
impl UserRoleNew {
- pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<UserRole> {
+ pub async fn insert(self, conn: &DatabaseConnectionWithContext<'_>) -> StorageResult<UserRole> {
generics::generic_insert(conn, self).await
}
}
@@ -77,7 +77,7 @@ impl UserRole {
}
pub async fn find_by_user_id_tenant_id_org_id_merchant_id_profile_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
user_id: String,
tenant_id: id_type::TenantId,
org_id: id_type::OrganizationId,
@@ -148,7 +148,7 @@ impl UserRole {
}
pub async fn find_by_user_id_tenant_id_org_id_merchant_id_profile_id_with_entity_type(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
user_id: String,
tenant_id: id_type::TenantId,
org_id: id_type::OrganizationId,
@@ -173,7 +173,7 @@ impl UserRole {
#[allow(clippy::too_many_arguments)]
pub async fn update_by_user_id_tenant_id_org_id_merchant_id_profile_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
user_id: String,
tenant_id: id_type::TenantId,
org_id: id_type::OrganizationId,
@@ -227,7 +227,7 @@ impl UserRole {
}
pub async fn delete_by_user_id_tenant_id_org_id_merchant_id_profile_id(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
user_id: String,
tenant_id: id_type::TenantId,
org_id: id_type::OrganizationId,
@@ -253,7 +253,7 @@ impl UserRole {
#[allow(clippy::too_many_arguments)]
pub async fn generic_user_roles_list_for_user(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
user_id: String,
tenant_id: id_type::TenantId,
org_id: Option<id_type::OrganizationId>,
@@ -300,8 +300,10 @@ impl UserRole {
router_env::logger::debug!(query = %debug_query::<Pg,_>(&query).to_string());
match generics::db_metrics::track_database_call::<Self, _, _>(
- query.get_results_async(conn),
+ conn.request_id(),
+ conn.event_emitter(),
generics::db_metrics::DatabaseOperation::Filter,
+ query.get_results_async(conn.raw_connection()),
)
.await
{
@@ -317,7 +319,7 @@ impl UserRole {
#[allow(clippy::too_many_arguments)]
pub async fn generic_user_roles_list_for_org_and_extra(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
user_id: Option<String>,
tenant_id: id_type::TenantId,
org_id: id_type::OrganizationId,
@@ -359,8 +361,10 @@ impl UserRole {
router_env::logger::debug!(query = %debug_query::<Pg,_>(&query).to_string());
match generics::db_metrics::track_database_call::<Self, _, _>(
- query.get_results_async(conn),
+ conn.request_id(),
+ conn.event_emitter(),
generics::db_metrics::DatabaseOperation::Filter,
+ query.get_results_async(conn.raw_connection()),
)
.await
{
@@ -375,7 +379,7 @@ impl UserRole {
}
pub async fn list_user_roles_by_user_id_across_tenants(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
user_id: String,
limit: Option<u32>,
) -> StorageResult<Vec<Self>> {
@@ -389,8 +393,10 @@ impl UserRole {
router_env::logger::debug!(query = %debug_query::<Pg,_>(&query).to_string());
match generics::db_metrics::track_database_call::<Self, _, _>(
- query.get_results_async(conn),
+ conn.request_id(),
+ conn.event_emitter(),
generics::db_metrics::DatabaseOperation::Filter,
+ query.get_results_async(conn.raw_connection()),
)
.await
{
diff --git a/crates/drainer/Cargo.toml b/crates/drainer/Cargo.toml
index 2cdc747156..be4e5481bc 100644
--- a/crates/drainer/Cargo.toml
+++ b/crates/drainer/Cargo.toml
@@ -11,10 +11,10 @@ license.workspace = true
default = ["redis-rs"]
release = ["vergen", "external_services/aws_kms"]
vergen = ["router_env/vergen"]
-v1 = ["diesel_models/v1", "external_services/v1", "hyperswitch_interfaces/v1", "common_utils/v1"]
-v2 = ["diesel_models/v2", "external_services/v2", "hyperswitch_interfaces/v2", "common_utils/v2"]
-fred = ["redis_interface/fred", "redis_interface/metrics"]
-redis-rs = ["redis_interface/redis-rs", "redis_interface/metrics"]
+v1 = ["diesel_models/v1", "external_services/v1", "hyperswitch_interfaces/v1", "common_utils/v1", "storage_impl/v1", "storage_impl/olap"]
+v2 = ["diesel_models/v2", "external_services/v2", "hyperswitch_interfaces/v2", "common_utils/v2", "storage_impl/v2"]
+fred = ["redis_interface/fred", "redis_interface/metrics", "storage_impl/fred"]
+redis-rs = ["redis_interface/redis-rs", "redis_interface/metrics", "storage_impl/redis-rs"]
[dependencies]
actix-web = "4.11.0"
@@ -41,6 +41,7 @@ hyperswitch_interfaces = { version = "0.1.0", path = "../hyperswitch_interfaces"
hyperswitch_masking = "0.0.1"
redis_interface = { version = "0.1.0", path = "../redis_interface", default-features = false }
router_env = { version = "0.1.0", path = "../router_env", features = ["log_extra_implicit_fields", "log_custom_entries_to_extra"] }
+storage_impl = { version = "0.1.0", path = "../storage_impl", features = ["payouts"], default-features = false }
[build-dependencies]
router_env = { version = "0.1.0", path = "../router_env", default-features = false }
diff --git a/crates/drainer/src/connection.rs b/crates/drainer/src/connection.rs
index a14ee63b58..c6694db655 100644
--- a/crates/drainer/src/connection.rs
+++ b/crates/drainer/src/connection.rs
@@ -1,11 +1,9 @@
-use bb8::PooledConnection;
use common_utils::DbConnectionParams;
use diesel_models::DejaPgConnection;
+use storage_impl::database::store::{DatabaseConnectionWithContext, PgPool};
use crate::{settings::Database, Settings};
-pub type PgPool = bb8::Pool<async_bb8_diesel::ConnectionManager<DejaPgConnection>>;
-
#[allow(clippy::expect_used)]
pub async fn redis_connection(conf: &Settings) -> redis_interface::RedisConnectionPool {
redis_interface::RedisConnectionPool::new_without_event_emitter(&conf.redis)
@@ -29,16 +27,23 @@ pub async fn diesel_make_pg_pool(
.max_size(database.pool_size)
.connection_timeout(std::time::Duration::from_secs(database.connection_timeout));
- pool.build(manager)
+ let raw_pool = pool
+ .build(manager)
.await
- .expect("Failed to create PostgreSQL connection pool")
+ .expect("Failed to create PostgreSQL connection pool");
+
+ PgPool::new_without_event_emitter(raw_pool)
}
#[allow(clippy::expect_used)]
-pub async fn pg_connection(
- pool: &PgPool,
-) -> PooledConnection<'_, async_bb8_diesel::ConnectionManager<DejaPgConnection>> {
- pool.get()
+pub async fn pg_connection<'a>(pool: &'a PgPool) -> DatabaseConnectionWithContext<'a> {
+ let connection = pool
+ .pg_pool
+ .get()
.await
- .expect("Couldn't retrieve PostgreSQL connection")
+ .expect("Couldn't retrieve PostgreSQL connection");
+
+ // The drainer serves no API request, so its queries carry no request id and emit no external
+ // service call events.
+ DatabaseConnectionWithContext::new(connection, None, pool.event_emitter.clone())
}
diff --git a/crates/drainer/src/health_check.rs b/crates/drainer/src/health_check.rs
index a114502a88..6f6ef8f7c5 100644
--- a/crates/drainer/src/health_check.rs
+++ b/crates/drainer/src/health_check.rs
@@ -119,15 +119,21 @@ impl HealthCheckInterface for Store {
async fn health_check_db(&self) -> CustomResult<(), HealthCheckDBError> {
let conn = pg_connection(&self.master_pool).await;
- conn
- .transaction_async(|conn| {
+ // The connection handed to the closure is another handle to the connection `conn` already
+ // holds, so queries issued through `conn` run within this transaction.
+ let conn = &conn;
+ conn.raw_connection()
+ .transaction_async(move |_| {
Box::pin(async move {
let query =
diesel::select(diesel::dsl::sql::<diesel::sql_types::Integer>("1 + 1"));
- let _x: i32 = query.get_result_async(&conn).await.map_err(|err| {
- logger::error!(read_err=?err,"Error while reading element in the database");
- HealthCheckDBError::DbReadError
- })?;
+ let _x: i32 = query
+ .get_result_async(conn.raw_connection())
+ .await
+ .map_err(|err| {
+ logger::error!(read_err=?err,"Error while reading element in the database");
+ HealthCheckDBError::DbReadError
+ })?;
logger::debug!("Database read was successful");
@@ -136,14 +142,14 @@ impl HealthCheckInterface for Store {
config: "test_value".to_string(),
};
- config.insert(&conn).await.map_err(|err| {
+ config.insert(conn).await.map_err(|err| {
logger::error!(write_err=?err,"Error while writing to database");
HealthCheckDBError::DbWriteError
})?;
logger::debug!("Database write was successful");
- Config::delete_by_key(&conn, "test_key").await.map_err(|err| {
+ Config::delete_by_key(conn, "test_key").await.map_err(|err| {
logger::error!(delete_err=?err,"Error while deleting element in the database");
HealthCheckDBError::DbDeleteError
})?;
diff --git a/crates/drainer/src/services.rs b/crates/drainer/src/services.rs
index 0030d740ba..258b88ad11 100644
--- a/crates/drainer/src/services.rs
+++ b/crates/drainer/src/services.rs
@@ -4,12 +4,9 @@ use actix_web::{body, HttpResponse, ResponseError};
use common_utils::request_context::RequestContext;
use error_stack::Report;
use redis_interface::RedisConnectionPool;
+use storage_impl::database::store::PgPool;
-use crate::{
- connection::{diesel_make_pg_pool, PgPool},
- logger,
- settings::Tenant,
-};
+use crate::{connection::diesel_make_pg_pool, logger, settings::Tenant};
#[derive(Clone)]
pub struct Store {
diff --git a/crates/router/src/connection.rs b/crates/router/src/connection.rs
index 7643911867..a79d3b0120 100644
--- a/crates/router/src/connection.rs
+++ b/crates/router/src/connection.rs
@@ -1,14 +1,13 @@
+#[cfg(feature = "deja")]
use bb8::PooledConnection;
+use common_utils::request_context::RequestContext;
+pub use diesel_models::DatabaseConnectionWithContext;
+#[cfg(feature = "deja")]
use diesel_models::DejaPgConnection;
use error_stack::ResultExt;
-use storage_impl::errors as storage_errors;
+use storage_impl::{errors as storage_errors, DatabaseStore};
use crate::errors;
-
-pub type PgPool = bb8::Pool<async_bb8_diesel::ConnectionManager<DejaPgConnection>>;
-
-pub type PgPooledConn = async_bb8_diesel::Connection<DejaPgConnection>;
-
// Deja replay (R1): the minimal replay DB routing hook. On a just-leased pg
// connection during replay, route it to the active correlation's schema so
// per-test-case reads/writes stay isolated. The correlation is read from the
@@ -19,7 +18,7 @@ pub type PgPooledConn = async_bb8_diesel::Connection<DejaPgConnection>;
// No-op outside replay / when the store carries no request id. The `SET` SQL is
// built by the library (`deja::replay_search_path_sql_for`).
#[cfg(feature = "deja")]
-async fn deja_route_replay_schema<T: storage_impl::DatabaseStore>(
+async fn deja_route_replay_schema<T: DatabaseStore>(
conn: &mut PooledConnection<'_, async_bb8_diesel::ConnectionManager<DejaPgConnection>>,
store: &T,
) {
@@ -35,12 +34,9 @@ async fn deja_route_replay_schema<T: storage_impl::DatabaseStore>(
}
}
-pub async fn pg_connection_read<T: storage_impl::DatabaseStore>(
- store: &T,
-) -> errors::CustomResult<
- PooledConnection<'_, async_bb8_diesel::ConnectionManager<DejaPgConnection>>,
- storage_errors::StorageError,
-> {
+pub async fn pg_connection_read<'a, T: DatabaseStore + RequestContext>(
+ store: &'a T,
+) -> errors::CustomResult<DatabaseConnectionWithContext<'a>, storage_errors::StorageError> {
// If only OLAP is enabled get replica pool.
#[cfg(all(feature = "olap", not(feature = "oltp")))]
let pool = store.get_replica_pool();
@@ -57,22 +53,25 @@ pub async fn pg_connection_read<T: storage_impl::DatabaseStore>(
let pool = store.get_master_pool();
#[cfg_attr(not(feature = "deja"), allow(unused_mut))]
- let mut conn = pool
+ let mut connection = pool
+ .pg_pool
.get()
.await
.change_context(storage_errors::StorageError::DatabaseConnectionError)?;
+
#[cfg(feature = "deja")]
- deja_route_replay_schema(&mut conn, store).await;
+ deja_route_replay_schema(&mut connection, store).await;
- Ok(conn)
+ Ok(DatabaseConnectionWithContext::new(
+ connection,
+ store.request_id().map(str::to_owned),
+ pool.event_emitter.clone(),
+ ))
}
-pub async fn pg_accounts_connection_read<T: storage_impl::DatabaseStore>(
- store: &T,
-) -> errors::CustomResult<
- PooledConnection<'_, async_bb8_diesel::ConnectionManager<DejaPgConnection>>,
- storage_errors::StorageError,
-> {
+pub async fn pg_accounts_connection_read<'a, T: DatabaseStore + RequestContext>(
+ store: &'a T,
+) -> errors::CustomResult<DatabaseConnectionWithContext<'a>, storage_errors::StorageError> {
// If only OLAP is enabled get replica pool.
#[cfg(all(feature = "olap", not(feature = "oltp")))]
let pool = store.get_accounts_replica_pool();
@@ -89,49 +88,64 @@ pub async fn pg_accounts_connection_read<T: storage_impl::DatabaseStore>(
let pool = store.get_accounts_master_pool();
#[cfg_attr(not(feature = "deja"), allow(unused_mut))]
- let mut conn = pool
+ let mut connection = pool
+ .pg_pool
.get()
.await
.change_context(storage_errors::StorageError::DatabaseConnectionError)?;
+
#[cfg(feature = "deja")]
- deja_route_replay_schema(&mut conn, store).await;
- Ok(conn)
+ deja_route_replay_schema(&mut connection, store).await;
+
+ Ok(DatabaseConnectionWithContext::new(
+ connection,
+ store.request_id().map(str::to_owned),
+ pool.event_emitter.clone(),
+ ))
}
-pub async fn pg_connection_write<T: storage_impl::DatabaseStore>(
- store: &T,
-) -> errors::CustomResult<
- PooledConnection<'_, async_bb8_diesel::ConnectionManager<DejaPgConnection>>,
- storage_errors::StorageError,
-> {
+pub async fn pg_connection_write<'a, T: DatabaseStore + RequestContext>(
+ store: &'a T,
+) -> errors::CustomResult<DatabaseConnectionWithContext<'a>, storage_errors::StorageError> {
// Since all writes should happen to master DB only choose master DB.
let pool = store.get_master_pool();
#[cfg_attr(not(feature = "deja"), allow(unused_mut))]
- let mut conn = pool
+ let mut connection = pool
+ .pg_pool
.get()
.await
.change_context(storage_errors::StorageError::DatabaseConnectionError)?;
+
#[cfg(feature = "deja")]
- deja_route_replay_schema(&mut conn, store).await;
- Ok(conn)
+ deja_route_replay_schema(&mut connection, store).await;
+
+ Ok(DatabaseConnectionWithContext::new(
+ connection,
+ store.request_id().map(str::to_owned),
+ pool.event_emitter.clone(),
+ ))
}
-pub async fn pg_accounts_connection_write<T: storage_impl::DatabaseStore>(
- store: &T,
-) -> errors::CustomResult<
- PooledConnection<'_, async_bb8_diesel::ConnectionManager<DejaPgConnection>>,
- storage_errors::StorageError,
-> {
+pub async fn pg_accounts_connection_write<'a, T: DatabaseStore + RequestContext>(
+ store: &'a T,
+) -> errors::CustomResult<DatabaseConnectionWithContext<'a>, storage_errors::StorageError> {
// Since all writes should happen to master DB only choose master DB.
let pool = store.get_accounts_master_pool();
#[cfg_attr(not(feature = "deja"), allow(unused_mut))]
- let mut conn = pool
+ let mut connection = pool
+ .pg_pool
.get()
.await
.change_context(storage_errors::StorageError::DatabaseConnectionError)?;
+
#[cfg(feature = "deja")]
- deja_route_replay_schema(&mut conn, store).await;
- Ok(conn)
+ deja_route_replay_schema(&mut connection, store).await;
+
+ Ok(DatabaseConnectionWithContext::new(
+ connection,
+ store.request_id().map(str::to_owned),
+ pool.event_emitter.clone(),
+ ))
}
diff --git a/crates/router/src/db/events.rs b/crates/router/src/db/events.rs
index cd69dd7164..c95e8d3878 100644
--- a/crates/router/src/db/events.rs
+++ b/crates/router/src/db/events.rs
@@ -4,7 +4,6 @@ use common_utils::ext_traits::AsyncExt;
use error_stack::{report, ResultExt};
use futures::future::try_join_all;
use router_env::{instrument, tracing};
-use storage_impl::DatabaseStore;
use super::{MockDb, Store};
use crate::{
@@ -335,11 +334,7 @@ impl EventInterface for Store {
merchant_key_store: &domain::MerchantKeyStore,
event_recipient: Option<common_enums::EventRecipient>,
) -> CustomResult<Vec<domain::Event>, errors::StorageError> {
- let conn = self
- .get_replica_pool()
- .get()
- .await
- .change_context(errors::StorageError::DatabaseConnectionError)?;
+ let conn = connection::pg_connection_read(self).await?;
storage::Event::list_initial_attempts_by_initiator_merchant_id_constraints(
&conn,
initiator_merchant_id,
@@ -420,11 +415,7 @@ impl EventInterface for Store {
merchant_key_store: &domain::MerchantKeyStore,
event_recipient: Option<common_enums::EventRecipient>,
) -> CustomResult<Vec<domain::Event>, errors::StorageError> {
- let conn = self
- .get_replica_pool()
- .get()
- .await
- .change_context(errors::StorageError::DatabaseConnectionError)?;
+ let conn = connection::pg_connection_read(self).await?;
storage::Event::list_by_initiator_merchant_id_initial_attempt_id(
&conn,
initial_attempt_id,
@@ -491,11 +482,7 @@ impl EventInterface for Store {
merchant_key_store: &domain::MerchantKeyStore,
event_recipient: Option<common_enums::EventRecipient>,
) -> CustomResult<Vec<domain::Event>, errors::StorageError> {
- let conn = self
- .get_replica_pool()
- .get()
- .await
- .change_context(errors::StorageError::DatabaseConnectionError)?;
+ let conn = connection::pg_connection_read(self).await?;
storage::Event::list_initial_attempts_by_initiator_merchant_id_primary_object_id(
&conn,
initiator_merchant_id,
@@ -601,11 +588,7 @@ impl EventInterface for Store {
merchant_key_store: &domain::MerchantKeyStore,
event_recipient: Option<common_enums::EventRecipient>,
) -> CustomResult<Vec<domain::Event>, errors::StorageError> {
- let conn = self
- .get_replica_pool()
- .get()
- .await
- .change_context(errors::StorageError::DatabaseConnectionError)?;
+ let conn = connection::pg_connection_read(self).await?;
storage::Event::list_initial_attempts_by_profile_id_constraints(
&conn,
profile_id,
@@ -758,11 +741,7 @@ impl EventInterface for Store {
is_delivered: Option<bool>,
event_recipient: Option<common_enums::EventRecipient>,
) -> CustomResult<i64, errors::StorageError> {
- let conn = self
- .get_replica_pool()
- .get()
- .await
- .change_context(errors::StorageError::DatabaseConnectionError)?;
+ let conn = connection::pg_connection_read(self).await?;
storage::Event::count_initial_attempts_by_profile_id_constraints(
&conn,
profile_id,
@@ -787,11 +766,7 @@ impl EventInterface for Store {
is_delivered: Option<bool>,
event_recipient: Option<common_enums::EventRecipient>,
) -> CustomResult<i64, errors::StorageError> {
- let conn = self
- .get_replica_pool()
- .get()
- .await
- .change_context(errors::StorageError::DatabaseConnectionError)?;
+ let conn = connection::pg_connection_read(self).await?;
storage::Event::count_initial_attempts_by_initiator_merchant_id_constraints(
&conn,
initiator_merchant_id,
diff --git a/crates/router/src/db/health_check.rs b/crates/router/src/db/health_check.rs
index 5423fef955..f418d835f9 100644
--- a/crates/router/src/db/health_check.rs
+++ b/crates/router/src/db/health_check.rs
@@ -23,39 +23,47 @@ impl HealthCheckDbInterface for Store {
.await
.change_context(errors::HealthCheckDBError::DBError)?;
- conn.transaction_async(|conn| async move {
- let query = diesel::select(diesel::dsl::sql::<diesel::sql_types::Integer>("1 + 1"));
- let _x: i32 = query.get_result_async(&conn).await.map_err(|err| {
- logger::error!(read_err=?err,"Error while reading element in the database");
- errors::HealthCheckDBError::DBReadError
- })?;
+ // The connection handed to the closure is another handle to the connection `conn` already
+ // holds, so queries issued through `conn` run within this transaction.
+ let conn = &conn;
+ conn.raw_connection()
+ .transaction_async(move |_| async move {
+ let query =
+ diesel::select(diesel::dsl::sql::<diesel::sql_types::Integer>("1 + 1"));
+ let _x: i32 = query
+ .get_result_async(conn.raw_connection())
+ .await
+ .map_err(|err| {
+ logger::error!(read_err=?err,"Error while reading element in the database");
+ errors::HealthCheckDBError::DBReadError
+ })?;
- logger::debug!("Database read was successful");
+ logger::debug!("Database read was successful");
- let config = ConfigNew {
- key: "test_key".to_string(),
- config: "test_value".to_string(),
- };
+ let config = ConfigNew {
+ key: "test_key".to_string(),
+ config: "test_value".to_string(),
+ };
- config.insert(&conn).await.map_err(|err| {
- logger::error!(write_err=?err,"Error while writing to database");
- errors::HealthCheckDBError::DBWriteError
- })?;
+ config.insert(conn).await.map_err(|err| {
+ logger::error!(write_err=?err,"Error while writing to database");
+ errors::HealthCheckDBError::DBWriteError
+ })?;
- logger::debug!("Database write was successful");
+ logger::debug!("Database write was successful");
- storage::Config::delete_by_key(&conn, "test_key")
- .await
- .map_err(|err| {
- logger::error!(delete_err=?err,"Error while deleting element in the database");
- errors::HealthCheckDBError::DBDeleteError
- })?;
+ storage::Config::delete_by_key(conn, "test_key")
+ .await
+ .map_err(|err| {
+ logger::error!(delete_err=?err,"Error while deleting element in the database");
+ errors::HealthCheckDBError::DBDeleteError
+ })?;
- logger::debug!("Database delete was successful");
+ logger::debug!("Database delete was successful");
- Ok::<_, errors::HealthCheckDBError>(())
- })
- .await?;
+ Ok::<_, errors::HealthCheckDBError>(())
+ })
+ .await?;
Ok(())
}
diff --git a/crates/router/src/services.rs b/crates/router/src/services.rs
index dc494eefae..94ddc20069 100644
--- a/crates/router/src/services.rs
+++ b/crates/router/src/services.rs
@@ -59,6 +59,7 @@ pub async fn get_store(
test_transaction: bool,
key_manager_state: keymanager::KeyManagerState,
) -> StorageResult<Store> {
+ let database_event_emitter = Arc::clone(&key_manager_state.event_emitter);
// Reads are served off a single replica pool regardless of tenant/accounts/global role.
#[cfg(feature = "olap")]
let replica_config = config.replica_database.clone().into_inner();
@@ -89,6 +90,7 @@ pub async fn get_store(
&config.redis,
master_enc_key,
Some(key_manager_state.clone()),
+ Arc::clone(&database_event_emitter),
)
.await?
} else {
@@ -99,6 +101,7 @@ pub async fn get_store(
cache_store,
storage_impl::redis::cache::IMC_INVALIDATION_CHANNEL,
Some(key_manager_state.clone()),
+ database_event_emitter,
)
.await?
};
diff --git a/crates/router/src/types/storage/dispute.rs b/crates/router/src/types/storage/dispute.rs
index d65c03837b..a3a3461e1a 100644
--- a/crates/router/src/types/storage/dispute.rs
+++ b/crates/router/src/types/storage/dispute.rs
@@ -6,18 +6,18 @@ use diesel_models::{errors, query::generics::db_metrics, schema::dispute::dsl};
use error_stack::ResultExt;
use hyperswitch_domain_models::disputes;
-use crate::{connection::PgPooledConn, logger};
+use crate::{connection::DatabaseConnectionWithContext, logger};
#[async_trait::async_trait]
pub trait DisputeDbExt: Sized {
async fn filter_by_constraints(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
processor_merchant_id: &common_utils::id_type::MerchantId,
dispute_list_constraints: &disputes::DisputeListConstraints,
) -> CustomResult<Vec<Self>, errors::DatabaseError>;
async fn get_dispute_status_with_count(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
processor_merchant_id: &common_utils::id_type::MerchantId,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
time_range: &common_utils::types::TimeRange,
@@ -27,7 +27,7 @@ pub trait DisputeDbExt: Sized {
#[async_trait::async_trait]
impl DisputeDbExt for Dispute {
async fn filter_by_constraints(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
processor_merchant_id: &common_utils::id_type::MerchantId,
dispute_list_constraints: &disputes::DisputeListConstraints,
) -> CustomResult<Vec<Self>, errors::DatabaseError> {
@@ -105,8 +105,10 @@ impl DisputeDbExt for Dispute {
logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg, _>(&filter).to_string());
db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>(
- filter.get_results_async(conn),
+ conn.request_id(),
+ conn.event_emitter(),
db_metrics::DatabaseOperation::Filter,
+ filter.get_results_async(conn.raw_connection()),
)
.await
.change_context(errors::DatabaseError::NotFound)
@@ -114,7 +116,7 @@ impl DisputeDbExt for Dispute {
}
async fn get_dispute_status_with_count(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
processor_merchant_id: &common_utils::id_type::MerchantId,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
time_range: &common_utils::types::TimeRange,
@@ -146,8 +148,10 @@ impl DisputeDbExt for Dispute {
logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg,_>(&query).to_string());
db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>(
- query.get_results_async::<(common_enums::DisputeStatus, i64)>(conn),
+ conn.request_id(),
+ conn.event_emitter(),
db_metrics::DatabaseOperation::Count,
+ query.get_results_async::<(common_enums::DisputeStatus, i64)>(conn.raw_connection()),
)
.await
.change_context(errors::DatabaseError::NotFound)
diff --git a/crates/router/src/types/storage/mandate.rs b/crates/router/src/types/storage/mandate.rs
index ca874e7e92..6a59f6e3f0 100644
--- a/crates/router/src/types/storage/mandate.rs
+++ b/crates/router/src/types/storage/mandate.rs
@@ -7,12 +7,12 @@ pub use diesel_models::mandate::{
use diesel_models::{errors, schema::mandate::dsl};
use error_stack::ResultExt;
-use crate::{connection::PgPooledConn, logger};
+use crate::{connection::DatabaseConnectionWithContext, logger};
#[async_trait::async_trait]
pub trait MandateDbExt: Sized {
async fn filter_by_constraints(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
mandate_list_constraints: api_models::mandates::MandateListConstraints,
) -> CustomResult<Vec<Self>, errors::DatabaseError>;
@@ -21,7 +21,7 @@ pub trait MandateDbExt: Sized {
#[async_trait::async_trait]
impl MandateDbExt for Mandate {
async fn filter_by_constraints(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
mandate_list_constraints: api_models::mandates::MandateListConstraints,
) -> CustomResult<Vec<Self>, errors::DatabaseError> {
@@ -62,7 +62,7 @@ impl MandateDbExt for Mandate {
logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg, _>(&filter).to_string());
filter
- .get_results_async(conn)
+ .get_results_async(conn.raw_connection())
.await
// The query built here returns an empty Vec when no records are found, and if any error does occur,
// it would be an internal database error, due to which we are raising a DatabaseError::Unknown error
diff --git a/crates/router/src/types/storage/payment_link.rs b/crates/router/src/types/storage/payment_link.rs
index dfd6dfefc7..a74b89efb1 100644
--- a/crates/router/src/types/storage/payment_link.rs
+++ b/crates/router/src/types/storage/payment_link.rs
@@ -7,7 +7,7 @@ pub use diesel_models::{
use error_stack::ResultExt;
use crate::{
- connection::PgPooledConn,
+ connection::DatabaseConnectionWithContext,
core::errors::{self, CustomResult},
logger,
};
@@ -15,7 +15,7 @@ use crate::{
#[async_trait::async_trait]
pub trait PaymentLinkDbExt: Sized {
async fn filter_by_constraints(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
processor_merchant_id: &common_utils::id_type::MerchantId,
payment_link_list_constraints: api_models::payments::PaymentLinkListConstraints,
) -> CustomResult<Vec<Self>, errors::DatabaseError>;
@@ -24,7 +24,7 @@ pub trait PaymentLinkDbExt: Sized {
#[async_trait::async_trait]
impl PaymentLinkDbExt for PaymentLink {
async fn filter_by_constraints(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
processor_merchant_id: &common_utils::id_type::MerchantId,
payment_link_list_constraints: api_models::payments::PaymentLinkListConstraints,
) -> CustomResult<Vec<Self>, errors::DatabaseError> {
@@ -62,7 +62,7 @@ impl PaymentLinkDbExt for PaymentLink {
logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg, _>(&filter).to_string());
filter
- .get_results_async(conn)
+ .get_results_async(conn.raw_connection())
.await
// The query built here returns an empty Vec when no records are found, and if any error does occur,
// it would be an internal database error, due to which we are raising a DatabaseError::Unknown error
diff --git a/crates/router/src/types/storage/refund.rs b/crates/router/src/types/storage/refund.rs
index ad5afc0f37..29b53d97fc 100644
--- a/crates/router/src/types/storage/refund.rs
+++ b/crates/router/src/types/storage/refund.rs
@@ -16,13 +16,13 @@ use diesel_models::{
use error_stack::ResultExt;
use hyperswitch_domain_models::refunds;
-use crate::{connection::PgPooledConn, logger};
+use crate::{connection::DatabaseConnectionWithContext, logger};
#[async_trait::async_trait]
pub trait RefundDbExt: Sized {
#[cfg(feature = "v1")]
async fn filter_by_constraints(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
processor_merchant_id: &common_utils::id_type::MerchantId,
refund_list_details: &refunds::RefundListConstraints,
limit: PageSize,
@@ -31,7 +31,7 @@ pub trait RefundDbExt: Sized {
#[cfg(feature = "v2")]
async fn filter_by_constraints(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
refund_list_details: refunds::RefundListConstraints,
limit: PageSize,
@@ -40,21 +40,21 @@ pub trait RefundDbExt: Sized {
#[cfg(feature = "v1")]
async fn filter_by_meta_constraints(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
processor_merchant_id: &common_utils::id_type::MerchantId,
refund_list_details: &common_utils::types::TimeRange,
) -> CustomResult<api_models::refunds::RefundListMetaData, errors::DatabaseError>;
#[cfg(feature = "v1")]
async fn get_refunds_count(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
processor_merchant_id: &common_utils::id_type::MerchantId,
refund_list_details: &refunds::RefundListConstraints,
) -> CustomResult<i64, errors::DatabaseError>;
#[cfg(feature = "v1")]
async fn get_refund_status_with_count(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
processor_merchant_id: &common_utils::id_type::MerchantId,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
time_range: &common_utils::types::TimeRange,
@@ -62,7 +62,7 @@ pub trait RefundDbExt: Sized {
#[cfg(feature = "v2")]
async fn get_refunds_count(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
refund_list_details: refunds::RefundListConstraints,
) -> CustomResult<i64, errors::DatabaseError>;
@@ -72,7 +72,7 @@ pub trait RefundDbExt: Sized {
impl RefundDbExt for Refund {
#[cfg(feature = "v1")]
async fn filter_by_constraints(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
processor_merchant_id: &common_utils::id_type::MerchantId,
refund_list_details: &refunds::RefundListConstraints,
limit: PageSize,
@@ -160,8 +160,10 @@ impl RefundDbExt for Refund {
logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg, _>(&filter).to_string());
db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>(
- filter.get_results_async(conn),
+ conn.request_id(),
+ conn.event_emitter(),
db_metrics::DatabaseOperation::Filter,
+ filter.get_results_async(conn.raw_connection()),
)
.await
.change_context(errors::DatabaseError::NotFound)
@@ -170,7 +172,7 @@ impl RefundDbExt for Refund {
#[cfg(feature = "v2")]
async fn filter_by_constraints(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
refund_list_details: refunds::RefundListConstraints,
limit: PageSize,
@@ -235,8 +237,10 @@ impl RefundDbExt for Refund {
logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg, _>(&filter).to_string());
db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>(
- filter.get_results_async(conn),
+ conn.request_id(),
+ conn.event_emitter(),
db_metrics::DatabaseOperation::Filter,
+ filter.get_results_async(conn.raw_connection()),
)
.await
.change_context(errors::DatabaseError::NotFound)
@@ -247,7 +251,7 @@ impl RefundDbExt for Refund {
#[cfg(feature = "v1")]
async fn filter_by_meta_constraints(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
processor_merchant_id: &common_utils::id_type::MerchantId,
refund_list_details: &common_utils::types::TimeRange,
) -> CustomResult<api_models::refunds::RefundListMetaData, errors::DatabaseError> {
@@ -274,7 +278,7 @@ impl RefundDbExt for Refund {
.select(dsl::connector)
.distinct()
.order_by(dsl::connector.asc())
- .get_results_async(conn)
+ .get_results_async(conn.raw_connection())
.await
.change_context(errors::DatabaseError::Others)
.attach_printable("Error filtering records by connector")?;
@@ -284,7 +288,7 @@ impl RefundDbExt for Refund {
.select(dsl::currency)
.distinct()
.order_by(dsl::currency.asc())
- .get_results_async(conn)
+ .get_results_async(conn.raw_connection())
.await
.change_context(errors::DatabaseError::Others)
.attach_printable("Error filtering records by currency")?;
@@ -293,7 +297,7 @@ impl RefundDbExt for Refund {
.select(dsl::refund_status)
.distinct()
.order_by(dsl::refund_status.asc())
- .get_results_async(conn)
+ .get_results_async(conn.raw_connection())
.await
.change_context(errors::DatabaseError::Others)
.attach_printable("Error filtering records by refund status")?;
@@ -309,7 +313,7 @@ impl RefundDbExt for Refund {
#[cfg(feature = "v1")]
async fn get_refunds_count(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
processor_merchant_id: &common_utils::id_type::MerchantId,
refund_list_details: &refunds::RefundListConstraints,
) -> CustomResult<i64, errors::DatabaseError> {
@@ -395,7 +399,7 @@ impl RefundDbExt for Refund {
logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg, _>(&filter).to_string());
filter
- .get_result_async::<i64>(conn)
+ .get_result_async::<i64>(conn.raw_connection())
.await
.change_context(errors::DatabaseError::NotFound)
.attach_printable_lazy(|| "Error filtering count of refunds")
@@ -403,7 +407,7 @@ impl RefundDbExt for Refund {
#[cfg(feature = "v2")]
async fn get_refunds_count(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &common_utils::id_type::MerchantId,
refund_list_details: refunds::RefundListConstraints,
) -> CustomResult<i64, errors::DatabaseError> {
@@ -464,7 +468,7 @@ impl RefundDbExt for Refund {
logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg, _>(&filter).to_string());
filter
- .get_result_async::<i64>(conn)
+ .get_result_async::<i64>(conn.raw_connection())
.await
.change_context(errors::DatabaseError::NotFound)
.attach_printable_lazy(|| "Error filtering count of refunds")
@@ -472,7 +476,7 @@ impl RefundDbExt for Refund {
#[cfg(feature = "v1")]
async fn get_refund_status_with_count(
- conn: &PgPooledConn,
+ conn: &DatabaseConnectionWithContext<'_>,
processor_merchant_id: &common_utils::id_type::MerchantId,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
time_range: &common_utils::types::TimeRange,
@@ -504,8 +508,10 @@ impl RefundDbExt for Refund {
logger::debug!(filter = %diesel::debug_query::<diesel::pg::Pg,_>(&query).to_string());
db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>(
- query.get_results_async::<(RefundStatus, i64)>(conn),
+ conn.request_id(),
+ conn.event_emitter(),
db_metrics::DatabaseOperation::Count,
+ query.get_results_async::<(RefundStatus, i64)>(conn.raw_connection()),
)
.await
.change_context(errors::DatabaseError::NotFound)
diff --git a/crates/storage_impl/src/connection.rs b/crates/storage_impl/src/connection.rs
index bc9dc2022f..cadcb86602 100644
--- a/crates/storage_impl/src/connection.rs
+++ b/crates/storage_impl/src/connection.rs
@@ -1,18 +1,14 @@
-use bb8::PooledConnection;
use common_utils::errors;
-use diesel_models::DejaPgConnection;
use error_stack::ResultExt;
-pub type PgPool = bb8::Pool<async_bb8_diesel::ConnectionManager<DejaPgConnection>>;
+use crate::{
+ database::store::DatabaseConnectionWithContext, errors::StorageError, DatabaseStore,
+ RequestContext,
+};
-pub type PgPooledConn = async_bb8_diesel::Connection<DejaPgConnection>;
-
-pub async fn pg_connection_read<T: crate::DatabaseStore>(
- store: &T,
-) -> errors::CustomResult<
- PooledConnection<'_, async_bb8_diesel::ConnectionManager<DejaPgConnection>>,
- crate::errors::StorageError,
-> {
+pub async fn pg_connection_read<'a, T: DatabaseStore + RequestContext>(
+ store: &'a T,
+) -> errors::CustomResult<DatabaseConnectionWithContext<'a>, StorageError> {
// If only OLAP is enabled get replica pool.
#[cfg(all(feature = "olap", not(feature = "oltp")))]
let pool = store.get_replica_pool();
@@ -29,30 +25,41 @@ pub async fn pg_connection_read<T: crate::DatabaseStore>(
let pool = store.get_master_pool();
#[cfg_attr(not(feature = "deja"), allow(unused_mut))]
- let mut conn = pool
+ let mut connection = pool
+ .pg_pool
.get()
.await
- .change_context(crate::errors::StorageError::DatabaseConnectionError)?;
+ .change_context(StorageError::DatabaseConnectionError)?;
+
#[cfg(feature = "deja")]
- crate::utils::deja_route_replay_schema(&mut conn, store).await;
- Ok(conn)
+ crate::utils::deja_route_replay_schema(&mut connection, store).await;
+
+ Ok(DatabaseConnectionWithContext::new(
+ connection,
+ store.request_id().map(str::to_owned),
+ pool.event_emitter.clone(),
+ ))
}
-pub async fn pg_connection_write<T: crate::DatabaseStore>(
- store: &T,
-) -> errors::CustomResult<
- PooledConnection<'_, async_bb8_diesel::ConnectionManager<DejaPgConnection>>,
- crate::errors::StorageError,
-> {
+pub async fn pg_connection_write<'a, T: DatabaseStore + RequestContext>(
+ store: &'a T,
+) -> errors::CustomResult<DatabaseConnectionWithContext<'a>, StorageError> {
// Since all writes should happen to master DB only choose master DB.
let pool = store.get_master_pool();
#[cfg_attr(not(feature = "deja"), allow(unused_mut))]
- let mut conn = pool
+ let mut connection = pool
+ .pg_pool
.get()
.await
- .change_context(crate::errors::StorageError::DatabaseConnectionError)?;
+ .change_context(StorageError::DatabaseConnectionError)?;
+
#[cfg(feature = "deja")]
- crate::utils::deja_route_replay_schema(&mut conn, store).await;
- Ok(conn)
+ crate::utils::deja_route_replay_schema(&mut connection, store).await;
+
+ Ok(DatabaseConnectionWithContext::new(
+ connection,
+ store.request_id().map(str::to_owned),
+ pool.event_emitter.clone(),
+ ))
}
diff --git a/crates/storage_impl/src/database/store.rs b/crates/storage_impl/src/database/store.rs
index 12c7c4cada..0629290c8a 100644
--- a/crates/storage_impl/src/database/store.rs
+++ b/crates/storage_impl/src/database/store.rs
@@ -1,10 +1,14 @@
+use std::sync::Arc;
+
use async_bb8_diesel::{AsyncConnection, ConnectionError};
use bb8::CustomizeConnection;
use common_utils::{
+ external_service::{ExternalServiceEventEmitter, NoOpEventEmitter},
types::{keymanager, TenantConfig},
DbConnectionParams,
};
-use diesel_models::DejaPgConnection;
+pub use diesel_models::DatabaseConnectionWithContext;
+use diesel_models::{DejaPgConnection, RawPgConnection};
use error_stack::ResultExt;
use crate::{
@@ -12,9 +16,32 @@ use crate::{
errors::{StorageError, StorageResult},
};
-pub type PgPool = bb8::Pool<async_bb8_diesel::ConnectionManager<DejaPgConnection>>;
-pub type PgPooledConn = async_bb8_diesel::Connection<DejaPgConnection>;
+pub type RawPgPool = bb8::Pool<async_bb8_diesel::ConnectionManager<DejaPgConnection>>;
+
+#[derive(Debug, Clone)]
+pub struct PgPool {
+ pub pg_pool: RawPgPool,
+ pub event_emitter: Arc<dyn ExternalServiceEventEmitter>,
+}
+
+impl PgPool {
+ pub fn new(pg_pool: RawPgPool, event_emitter: Arc<dyn ExternalServiceEventEmitter>) -> Self {
+ Self {
+ pg_pool,
+ event_emitter,
+ }
+ }
+
+ pub fn new_without_event_emitter(pool: RawPgPool) -> Self {
+ Self::new(pool, Arc::new(NoOpEventEmitter))
+ }
+}
+/// Shared database-pool ownership.
+///
+/// Request context is intentionally not part of this trait. Request-scoped wrappers such as
+/// `RouterStore` and `KVRouterStore` implement `RequestContext` separately, and the connection
+/// helpers in `crate::connection` combine the two when leasing a connection.
#[async_trait::async_trait]
pub trait DatabaseStore: Clone + Send + Sync {
type Config: Send;
@@ -23,6 +50,7 @@ pub trait DatabaseStore: Clone + Send + Sync {
tenant_config: &dyn TenantConfig,
test_transaction: bool,
key_manager_state: Option<keymanager::KeyManagerState>,
+ event_emitter: Arc<dyn ExternalServiceEventEmitter>,
) -> StorageResult<Self>;
fn get_master_pool(&self) -> &PgPool;
fn get_replica_pool(&self) -> &PgPool;
@@ -52,6 +80,7 @@ impl DatabaseStore for Store {
tenant_config: &dyn TenantConfig,
test_transaction: bool,
_key_manager_state: Option<keymanager::KeyManagerState>,
+ event_emitter: Arc<dyn ExternalServiceEventEmitter>,
) -> StorageResult<Self> {
let (master_config, accounts_config) = config;
Ok(Self {
@@ -59,12 +88,14 @@ impl DatabaseStore for Store {
&master_config,
tenant_config.get_schema(),
test_transaction,
+ Arc::clone(&event_emitter),
)
.await?,
accounts_pool: diesel_make_pg_pool(
&accounts_config,
tenant_config.get_accounts_schema(),
test_transaction,
+ event_emitter,
)
.await?,
})
@@ -104,17 +135,23 @@ impl DatabaseStore for ReplicaStore {
tenant_config: &dyn TenantConfig,
test_transaction: bool,
_key_manager_state: Option<keymanager::KeyManagerState>,
+ event_emitter: Arc<dyn ExternalServiceEventEmitter>,
) -> StorageResult<Self> {
let (master_config, replica_config, accounts_master_config, accounts_replica_config) =
config;
- let master_pool =
- diesel_make_pg_pool(&master_config, tenant_config.get_schema(), test_transaction)
- .await
- .attach_printable("failed to create master pool")?;
+ let master_pool = diesel_make_pg_pool(
+ &master_config,
+ tenant_config.get_schema(),
+ test_transaction,
+ Arc::clone(&event_emitter),
+ )
+ .await
+ .attach_printable("failed to create master pool")?;
let accounts_master_pool = diesel_make_pg_pool(
&accounts_master_config,
tenant_config.get_accounts_schema(),
test_transaction,
+ Arc::clone(&event_emitter),
)
.await
.attach_printable("failed to create accounts master pool")?;
@@ -122,6 +159,7 @@ impl DatabaseStore for ReplicaStore {
&replica_config,
tenant_config.get_schema(),
test_transaction,
+ Arc::clone(&event_emitter),
)
.await
.attach_printable("failed to create replica pool")?;
@@ -130,6 +168,7 @@ impl DatabaseStore for ReplicaStore {
&accounts_replica_config,
tenant_config.get_accounts_schema(),
test_transaction,
+ event_emitter,
)
.await
.attach_printable("failed to create accounts pool")?;
@@ -162,6 +201,7 @@ pub async fn diesel_make_pg_pool(
database: &Database,
schema: &str,
test_transaction: bool,
+ event_emitter: Arc<dyn ExternalServiceEventEmitter>,
) -> StorageResult<PgPool> {
let database_url = database.get_database_url(schema);
let manager = async_bb8_diesel::ConnectionManager::<DejaPgConnection>::new(database_url);
@@ -177,7 +217,7 @@ pub async fn diesel_make_pg_pool(
pool = pool.connection_customizer(Box::new(TestTransaction));
}
- let pool = pool
+ let raw_pool = pool
.build(manager)
.await
.change_context(StorageError::InitializationError)
@@ -190,7 +230,7 @@ pub async fn diesel_make_pg_pool(
if !deja::runtime_mode_is_disabled() {
use async_bb8_diesel::AsyncConnection;
use diesel::RunQueryDsl;
- if let Ok(connection) = pool.get().await {
+ if let Ok(connection) = raw_pool.get().await {
let rows = connection
.run(|conn| {
diesel::sql_query(deja::TABLE_IDENTITY_SQL)
@@ -214,16 +254,16 @@ pub async fn diesel_make_pg_pool(
}
}
- Ok(pool)
+ Ok(PgPool::new(raw_pool, event_emitter))
}
#[derive(Debug)]
struct TestTransaction;
#[async_trait::async_trait]
-impl CustomizeConnection<PgPooledConn, ConnectionError> for TestTransaction {
+impl CustomizeConnection<RawPgConnection, ConnectionError> for TestTransaction {
#[allow(clippy::unwrap_used)]
- async fn on_acquire(&self, conn: &mut PgPooledConn) -> Result<(), ConnectionError> {
+ async fn on_acquire(&self, conn: &mut RawPgConnection) -> Result<(), ConnectionError> {
use diesel::Connection;
conn.run(|conn| {
diff --git a/crates/storage_impl/src/kv_router_store.rs b/crates/storage_impl/src/kv_router_store.rs
index a7e6552423..86b1e42ee6 100644
--- a/crates/storage_impl/src/kv_router_store.rs
+++ b/crates/storage_impl/src/kv_router_store.rs
@@ -132,6 +132,9 @@ where
tenant_config: &dyn TenantConfig,
_test_transaction: bool,
key_manager_state: Option<KeyManagerState>,
+ _event_emitter: std::sync::Arc<
+ dyn common_utils::external_service::ExternalServiceEventEmitter,
+ >,
) -> StorageResult<Self> {
let (router_store, _, drainer_num_partitions, ttl_for_kv, soft_kill_mode) = config;
let drainer_stream_name = format!("{}_{}", tenant_config.get_schema(), config.1);
diff --git a/crates/storage_impl/src/lib.rs b/crates/storage_impl/src/lib.rs
index 7e439ce0aa..dde0acf18f 100644
--- a/crates/storage_impl/src/lib.rs
+++ b/crates/storage_impl/src/lib.rs
@@ -112,6 +112,7 @@ where
tenant_config: &dyn TenantConfig,
test_transaction: bool,
key_manager_state: Option<KeyManagerState>,
+ event_emitter: Arc<dyn ExternalServiceEventEmitter>,
) -> error_stack::Result<Self, StorageError> {
let (db_conf, cache_conf, encryption_key, cache_error_signal, inmemory_cache_stream) =
config;
@@ -122,6 +123,7 @@ where
&cache_conf,
encryption_key,
key_manager_state,
+ event_emitter,
)
.await
.attach_printable("failed to create test router store")
@@ -134,6 +136,7 @@ where
.await?,
inmemory_cache_stream,
key_manager_state,
+ event_emitter,
)
.await
.attach_printable("failed to create store")
@@ -175,8 +178,16 @@ impl<T: DatabaseStore> RouterStore<T> {
cache_store: Arc<RedisStore>,
inmemory_cache_stream: &str,
key_manager_state: Option<KeyManagerState>,
+ event_emitter: Arc<dyn ExternalServiceEventEmitter>,
) -> error_stack::Result<Self, StorageError> {
- let db_store = T::new(db_conf, tenant_config, false, key_manager_state.clone()).await?;
+ let db_store = T::new(
+ db_conf,
+ tenant_config,
+ false,
+ key_manager_state.clone(),
+ event_emitter,
+ )
+ .await?;
let cache_store = Arc::new(
cache_store
.clone()
@@ -419,9 +430,17 @@ impl<T: DatabaseStore> RouterStore<T> {
cache_conf: &redis_interface::RedisSettings,
encryption_key: StrongSecret<Vec<u8>>,
key_manager_state: Option<KeyManagerState>,
+ event_emitter: Arc<dyn ExternalServiceEventEmitter>,
) -> error_stack::Result<Self, StorageError> {
// TODO: create an error enum and return proper error here
- let db_store = T::new(db_conf, tenant_config, true, key_manager_state.clone()).await?;
+ let db_store = T::new(
+ db_conf,
+ tenant_config,
+ true,
+ key_manager_state.clone(),
+ event_emitter,
+ )
+ .await?;
let cache_store = RedisStore::new_without_event_emitter(cache_conf)
.await
.change_context(StorageError::InitializationError)
diff --git a/crates/storage_impl/src/lookup.rs b/crates/storage_impl/src/lookup.rs
index 5b6b00bef4..02644dba61 100644
--- a/crates/storage_impl/src/lookup.rs
+++ b/crates/storage_impl/src/lookup.rs
@@ -38,11 +38,7 @@ impl<T: DatabaseStore> ReverseLookupInterface for RouterStore<T> {
new: DieselReverseLookupNew,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<DieselReverseLookup, errors::StorageError> {
- let conn = self
- .get_master_pool()
- .get()
- .await
- .change_context(errors::StorageError::DatabaseConnectionError)?;
+ let conn = utils::pg_connection_write(self).await?;
new.insert(&conn).await.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
diff --git a/crates/storage_impl/src/merchant_connector_account.rs b/crates/storage_impl/src/merchant_connector_account.rs
index 829065830d..ec6c47e09f 100644
--- a/crates/storage_impl/src/merchant_connector_account.rs
+++ b/crates/storage_impl/src/merchant_connector_account.rs
@@ -729,7 +729,7 @@ impl<T: DatabaseStore> MerchantConnectorAccountInterface for RouterStore<T> {
let conn = pg_accounts_connection_write(self).await?;
async fn update_call(
- connection: &diesel_models::PgPooledConn,
+ connection: &diesel_models::DatabaseConnectionWithContext<'_>,
(merchant_connector_account, mca_update): (
domain::MerchantConnectorAccount,
storage::MerchantConnectorAccountUpdateInternal,
@@ -744,87 +744,92 @@ impl<T: DatabaseStore> MerchantConnectorAccountInterface for RouterStore<T> {
Ok(())
}
- conn.transaction_async(|connection_pool| async move {
- for (merchant_connector_account, update_merchant_connector_account) in
- merchant_connector_accounts
- {
- #[cfg(feature = "v1")]
- let _connector_name = merchant_connector_account.connector_name.clone();
+ // The connection handed to the closure is another handle to the connection `conn` already
+ // holds, so queries issued through `conn` run within this transaction.
+ let connection_pool = &conn;
+ conn.raw_connection()
+ .transaction_async(move |_| async move {
+ for (merchant_connector_account, update_merchant_connector_account) in
+ merchant_connector_accounts
+ {
+ #[cfg(feature = "v1")]
+ let _connector_name = merchant_connector_account.connector_name.clone();
- #[cfg(feature = "v2")]
- let _connector_name = merchant_connector_account.connector_name.to_string();
+ #[cfg(feature = "v2")]
+ let _connector_name = merchant_connector_account.connector_name.to_string();
- let _profile_id = merchant_connector_account.profile_id.clone();
+ let _profile_id = merchant_connector_account.profile_id.clone();
- let _merchant_id = merchant_connector_account.merchant_id.clone();
- let _merchant_connector_id = merchant_connector_account.get_id().clone();
+ let _merchant_id = merchant_connector_account.merchant_id.clone();
+ let _merchant_connector_id = merchant_connector_account.get_id().clone();
- let update = update_call(
- &connection_pool,
- (
- merchant_connector_account,
- update_merchant_connector_account,
- ),
- );
-
- #[cfg(feature = "accounts_cache")]
- // Redact all caches as any of might be used because of backwards compatibility
- Box::pin(cache::publish_and_redact_multiple(
- self,
- [
- cache::CacheKind::Accounts(
- format!("{}_{}", _profile_id.get_string_repr(), _connector_name).into(),
- ),
- cache::CacheKind::Accounts(
- format!(
- "{}_{}",
- _merchant_id.get_string_repr(),
- _merchant_connector_id.get_string_repr()
- )
- .into(),
- ),
- cache::CacheKind::CGraph(
- format!(
- "cgraph_{}_{}",
- _merchant_id.get_string_repr(),
- _profile_id.get_string_repr()
- )
- .into(),
+ let update = update_call(
+ connection_pool,
+ (
+ merchant_connector_account,
+ update_merchant_connector_account,
),
- ],
- || update,
- ))
- .await
- .map_err(|error| {
- // Returning `DatabaseConnectionError` after logging the actual error because
- // -> it is not possible to get the underlying from `error_stack::Report<C>`
- // -> it is not possible to write a `From` impl to convert the `diesel::result::Error` to `error_stack::Report<StorageError>`
- // because of Rust's orphan rules
- router_env::logger::error!(
- ?error,
- "DB transaction for updating multiple merchant connector account failed"
);
- Self::Error::DatabaseConnectionError
- })?;
- #[cfg(not(feature = "accounts_cache"))]
- {
- update.await.map_err(|error| {
+ #[cfg(feature = "accounts_cache")]
+ // Redact all caches as any of might be used because of backwards compatibility
+ Box::pin(cache::publish_and_redact_multiple(
+ self,
+ [
+ cache::CacheKind::Accounts(
+ format!("{}_{}", _profile_id.get_string_repr(), _connector_name)
+ .into(),
+ ),
+ cache::CacheKind::Accounts(
+ format!(
+ "{}_{}",
+ _merchant_id.get_string_repr(),
+ _merchant_connector_id.get_string_repr()
+ )
+ .into(),
+ ),
+ cache::CacheKind::CGraph(
+ format!(
+ "cgraph_{}_{}",
+ _merchant_id.get_string_repr(),
+ _profile_id.get_string_repr()
+ )
+ .into(),
+ ),
+ ],
+ || update,
+ ))
+ .await
+ .map_err(|error| {
// Returning `DatabaseConnectionError` after logging the actual error because
// -> it is not possible to get the underlying from `error_stack::Report<C>`
// -> it is not possible to write a `From` impl to convert the `diesel::result::Error` to `error_stack::Report<StorageError>`
// because of Rust's orphan rules
router_env::logger::error!(
+ ?error,
+ "DB transaction for updating multiple merchant connector account failed"
+ );
+ Self::Error::DatabaseConnectionError
+ })?;
+
+ #[cfg(not(feature = "accounts_cache"))]
+ {
+ update.await.map_err(|error| {
+ // Returning `DatabaseConnectionError` after logging the actual error because
+ // -> it is not possible to get the underlying from `error_stack::Report<C>`
+ // -> it is not possible to write a `From` impl to convert the `diesel::result::Error` to `error_stack::Report<StorageError>`
+ // because of Rust's orphan rules
+ router_env::logger::error!(
?error,
"DB transaction for updating multiple merchant connector account failed"
);
- Self::Error::DatabaseConnectionError
- })?;
+ Self::Error::DatabaseConnectionError
+ })?;
+ }
}
- }
- Ok::<_, Self::Error>(())
- })
- .await?;
+ Ok::<_, Self::Error>(())
+ })
+ .await?;
Ok(())
}
diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs
index 2daa5896dc..d67009d403 100644
--- a/crates/storage_impl/src/payments/payment_attempt.rs
+++ b/crates/storage_impl/src/payments/payment_attempt.rs
@@ -40,7 +40,10 @@ use crate::{
kv_router_store::KVRouterStore,
lookup::ReverseLookupInterface,
redis::kv_store::{decide_storage_scheme, kv_wrapper, KvOperation, Op, PartitionKey},
- utils::{pg_connection_read, pg_connection_write, try_redis_get_else_try_database_get},
+ utils::{
+ pg_connection_read, pg_connection_read_replica, pg_connection_write,
+ try_redis_get_else_try_database_get,
+ },
DataModelExt, DatabaseStore, RouterStore,
};
@@ -625,12 +628,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> {
card_discovery: Option<Vec<common_enums::CardDiscovery>>,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<i64, errors::StorageError> {
- let conn = self
- .db_store
- .get_replica_pool()
- .get()
- .await
- .change_context(errors::StorageError::DatabaseConnectionError)?;
+ let conn = pg_connection_read_replica(self).await?;
let connector_strings = connector.as_ref().map(|connector| {
connector
.iter()
@@ -669,12 +667,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> {
card_network: Option<Vec<common_enums::CardNetwork>>,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<i64, errors::StorageError> {
- let conn = self
- .db_store
- .get_replica_pool()
- .get()
- .await
- .change_context(errors::StorageError::DatabaseConnectionError)?;
+ let conn = pg_connection_read_replica(self).await?;
DieselPaymentAttempt::get_total_count_of_attempts(
&conn,
diff --git a/crates/storage_impl/src/payments/payment_intent.rs b/crates/storage_impl/src/payments/payment_intent.rs
index 9b058a4ac6..2244d62af9 100644
--- a/crates/storage_impl/src/payments/payment_intent.rs
+++ b/crates/storage_impl/src/payments/payment_intent.rs
@@ -1,7 +1,7 @@
#[cfg(feature = "olap")]
use api_models::payments::{AmountFilter, Order, SortBy, SortOn};
#[cfg(feature = "olap")]
-use async_bb8_diesel::{AsyncConnection, AsyncRunQueryDsl};
+use async_bb8_diesel::AsyncRunQueryDsl;
use common_utils::ext_traits::AsyncExt;
#[cfg(feature = "v2")]
use common_utils::{ext_traits::Encode, fallback_reverse_lookup_not_found};
@@ -385,10 +385,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> {
.await;
let database_call = || async {
- let conn: bb8::PooledConnection<
- '_,
- async_bb8_diesel::ConnectionManager<diesel_models::DejaPgConnection>,
- > = pg_connection_read(self).await?;
+ let conn = pg_connection_read(self).await?;
DieselPaymentIntent::find_by_global_id(&conn, id)
.await
@@ -832,7 +829,6 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
use futures::{future::try_join_all, FutureExt};
let conn = connection::pg_connection_read(self).await?;
- let conn = async_bb8_diesel::Connection::as_async_conn(&conn);
//[#350]: Replace this with Boxable Expression and pass it into generic filter
// when https://github.com/rust-lang/rust/issues/52662 becomes stable
@@ -916,8 +912,10 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
.attach_printable("Missing KeyManagerState")?;
logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg,_>(&query).to_string());
db_metrics::track_database_call::<<DieselPaymentIntent as HasTable>::Table, _, _>(
- query.get_results_async::<DieselPaymentIntent>(conn),
+ conn.request_id(),
+ conn.event_emitter(),
db_metrics::DatabaseOperation::Filter,
+ query.get_results_async::<DieselPaymentIntent>(conn.raw_connection()),
)
.await
.map(|payment_intents| {
@@ -967,7 +965,6 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
time_range: &common_utils::types::TimeRange,
) -> error_stack::Result<Vec<(common_enums::IntentStatus, i64)>, StorageError> {
let conn = connection::pg_connection_read(self).await?;
- let conn = async_bb8_diesel::Connection::as_async_conn(&conn);
let mut query = diesel_models::list::into_boxed_list(
<DieselPaymentIntent as HasTable>::table()
@@ -990,8 +987,10 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
logger::debug!(filter = %diesel::debug_query::<diesel::pg::Pg,_>(&query).to_string());
db_metrics::track_database_call::<<DieselPaymentIntent as HasTable>::Table, _, _>(
- query.get_results_async::<(common_enums::IntentStatus, i64)>(conn),
+ conn.request_id(),
+ conn.event_emitter(),
db_metrics::DatabaseOperation::Filter,
+ query.get_results_async::<(common_enums::IntentStatus, i64)>(conn.raw_connection()),
)
.await
.map_err(|er| {
@@ -1010,7 +1009,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<(PaymentIntent, PaymentAttempt)>, StorageError> {
let conn = connection::pg_connection_read(self).await?;
- let conn = async_bb8_diesel::Connection::as_async_conn(&conn);
+ let conn = conn.raw_connection();
let mut query = diesel_models::list::into_boxed_list(
DieselPaymentIntent::table()
.filter(pi_dsl::processor_merchant_id.eq(processor_merchant_id.to_owned()))
@@ -1018,6 +1017,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
payment_attempt_schema::table
.on(pa_dsl::attempt_id.eq(pi_dsl::active_attempt_id)),
)
+ // Ensure merchant_ids match, as different merchants can share payment/attempt IDs.
.filter(pa_dsl::processor_merchant_id.eq(processor_merchant_id.to_owned())),
);
@@ -1231,7 +1231,8 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
use futures::{future::try_join_all, FutureExt};
let conn = connection::pg_connection_read(self).await?;
- let conn = async_bb8_diesel::Connection::as_async_conn(&conn);
+ let conn = conn.raw_connection();
+ // Filtering on merchant_id for payment_attempt is not required for v2 as payment_attempt_ids are globally unique
let mut query = diesel_models::list::into_boxed_list(
DieselPaymentIntent::table()
.filter(pi_dsl::merchant_id.eq(merchant_id.to_owned()))
@@ -1440,7 +1441,6 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<Option<String>>, StorageError> {
let conn = connection::pg_connection_read(self).await?;
- let conn = async_bb8_diesel::Connection::as_async_conn(&conn);
let mut query = diesel_models::list::into_boxed_list(
DieselPaymentIntent::table()
.select(pi_dsl::active_attempt_id)
@@ -1507,8 +1507,10 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
};
db_metrics::track_database_call::<<DieselPaymentIntent as HasTable>::Table, _, _>(
- query.get_results_async::<Option<String>>(conn),
+ conn.request_id(),
+ conn.event_emitter(),
db_metrics::DatabaseOperation::Filter,
+ query.get_results_async::<Option<String>>(conn.raw_connection()),
)
.await
.map_err(|er| {
@@ -1526,7 +1528,6 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<String>, StorageError> {
let conn = connection::pg_connection_read(self).await?;
- let conn = async_bb8_diesel::Connection::as_async_conn(&conn);
let mut query = diesel_models::list::into_boxed_list(
DieselPaymentIntent::table()
.select(pi_dsl::active_attempt_id)
@@ -1592,8 +1593,10 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
};
db_metrics::track_database_call::<<DieselPaymentIntent as HasTable>::Table, _, _>(
- query.get_results_async::<String>(conn),
+ conn.request_id(),
+ conn.event_emitter(),
db_metrics::DatabaseOperation::Filter,
+ query.get_results_async::<String>(conn.raw_connection()),
)
.await
.map_err(|er| {
diff --git a/crates/storage_impl/src/payouts/payouts.rs b/crates/storage_impl/src/payouts/payouts.rs
index 469b59fdc2..9c4522dc5b 100644
--- a/crates/storage_impl/src/payouts/payouts.rs
+++ b/crates/storage_impl/src/payouts/payouts.rs
@@ -1,7 +1,7 @@
#[cfg(feature = "olap")]
use api_models::enums::PayoutConnectors;
#[cfg(feature = "olap")]
-use async_bb8_diesel::{AsyncConnection, AsyncRunQueryDsl};
+use async_bb8_diesel::AsyncRunQueryDsl;
use common_utils::ext_traits::Encode;
#[cfg(feature = "olap")]
use diesel::{associations::HasTable, ExpressionMethods, QueryDsl};
@@ -48,7 +48,7 @@ use crate::{
errors::{RedisErrorExt, StorageError},
kv_router_store::KVRouterStore,
redis::kv_store::{decide_storage_scheme, kv_wrapper, KvOperation, Op, PartitionKey},
- utils::{self, pg_connection_read, pg_connection_write},
+ utils::{self, pg_connection_read, pg_connection_read_replica, pg_connection_write},
DataModelExt, DatabaseStore,
};
@@ -489,7 +489,6 @@ impl<T: DatabaseStore> PayoutsInterface for crate::RouterStore<T> {
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<Payouts>, StorageError> {
let conn = connection::pg_connection_read(self).await?;
- let conn = async_bb8_diesel::Connection::as_async_conn(&conn);
//[#350]: Replace this with Boxable Expression and pass it into generic filter
// when https://github.com/rust-lang/rust/issues/52662 becomes stable
@@ -560,8 +559,10 @@ impl<T: DatabaseStore> PayoutsInterface for crate::RouterStore<T> {
logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg,_>(&query).to_string());
db_metrics::track_database_call::<<DieselPayouts as HasTable>::Table, _, _>(
- query.get_results_async::<DieselPayouts>(conn),
+ conn.request_id(),
+ conn.event_emitter(),
db_metrics::DatabaseOperation::Filter,
+ query.get_results_async::<DieselPayouts>(conn.raw_connection()),
)
.await
.map(|payouts| {
@@ -593,7 +594,7 @@ impl<T: DatabaseStore> PayoutsInterface for crate::RouterStore<T> {
StorageError,
> {
let conn = connection::pg_connection_read(self).await?;
- let conn = async_bb8_diesel::Connection::as_async_conn(&conn);
+ let conn = conn.raw_connection();
let mut query = diesel_models::list::into_boxed_list(
DieselPayouts::table()
.inner_join(
@@ -780,12 +781,7 @@ impl<T: DatabaseStore> PayoutsInterface for crate::RouterStore<T> {
status: Option<Vec<storage_enums::PayoutStatus>>,
payout_type: Option<Vec<storage_enums::PayoutType>>,
) -> error_stack::Result<i64, StorageError> {
- let conn = self
- .db_store
- .get_replica_pool()
- .get()
- .await
- .change_context(StorageError::DatabaseConnectionError)?;
+ let conn = pg_connection_read_replica(self).await?;
let connector_strings = connector.as_ref().map(|connectors| {
connectors
.iter()
@@ -817,7 +813,6 @@ impl<T: DatabaseStore> PayoutsInterface for crate::RouterStore<T> {
constraints: &PayoutFetchConstraints,
) -> error_stack::Result<Vec<common_utils::id_type::PayoutId>, StorageError> {
let conn = connection::pg_connection_read(self).await?;
- let conn = async_bb8_diesel::Connection::as_async_conn(&conn);
let mut query = diesel_models::list::into_boxed_list(
DieselPayouts::table()
.inner_join(
@@ -875,8 +870,10 @@ impl<T: DatabaseStore> PayoutsInterface for crate::RouterStore<T> {
logger::debug!(filter = %diesel::debug_query::<diesel::pg::Pg,_>(&query).to_string());
db_metrics::track_database_call::<<DieselPayouts as HasTable>::Table, _, _>(
- query.get_results_async::<String>(conn),
+ conn.request_id(),
+ conn.event_emitter(),
db_metrics::DatabaseOperation::Filter,
+ query.get_results_async::<String>(conn.raw_connection()),
)
.await
.map_err(|er| {
@@ -911,7 +908,6 @@ impl<T: DatabaseStore> PayoutsInterface for crate::RouterStore<T> {
time_range: &common_utils::types::TimeRange,
) -> error_stack::Result<Vec<(common_enums::PayoutStatus, i64)>, StorageError> {
let conn = connection::pg_connection_read(self).await?;
- let conn = async_bb8_diesel::Connection::as_async_conn(&conn);
let mut query = diesel_models::list::into_boxed_list(
<DieselPayouts as HasTable>::table()
@@ -934,8 +930,10 @@ impl<T: DatabaseStore> PayoutsInterface for crate::RouterStore<T> {
logger::debug!(filter = %diesel::debug_query::<diesel::pg::Pg,_>(&query).to_string());
db_metrics::track_database_call::<<DieselPayouts as HasTable>::Table, _, _>(
- query.get_results_async::<(common_enums::PayoutStatus, i64)>(conn),
+ conn.request_id(),
+ conn.event_emitter(),
db_metrics::DatabaseOperation::Filter,
+ query.get_results_async::<(common_enums::PayoutStatus, i64)>(conn.raw_connection()),
)
.await
.map_err(|er| {
diff --git a/crates/storage_impl/src/utils.rs b/crates/storage_impl/src/utils.rs
index 5addbde2df..0383b5404f 100644
--- a/crates/storage_impl/src/utils.rs
+++ b/crates/storage_impl/src/utils.rs
@@ -1,10 +1,13 @@
+#[cfg(feature = "deja")]
use bb8::PooledConnection;
+#[cfg(feature = "deja")]
use diesel_models::DejaPgConnection;
use error_stack::ResultExt;
use crate::{
+ database::store::DatabaseConnectionWithContext,
errors::{RedisErrorExt, StorageError},
- metrics, DatabaseStore,
+ metrics, DatabaseStore, RequestContext,
};
// Deja replay (R1): the per-correlation DB routing hook, at the ACTUAL storage
@@ -126,12 +129,9 @@ fn deja_replay_route_warn_no_correlation() {
}
}
-pub async fn pg_connection_read<T: DatabaseStore>(
- store: &T,
-) -> error_stack::Result<
- PooledConnection<'_, async_bb8_diesel::ConnectionManager<DejaPgConnection>>,
- StorageError,
-> {
+pub async fn pg_connection_read<'a, T: DatabaseStore + RequestContext>(
+ store: &'a T,
+) -> error_stack::Result<DatabaseConnectionWithContext<'a>, StorageError> {
// If only OLAP is enabled get replica pool.
#[cfg(all(feature = "olap", not(feature = "oltp")))]
let pool = store.get_replica_pool();
@@ -148,40 +148,77 @@ pub async fn pg_connection_read<T: DatabaseStore>(
let pool = store.get_master_pool();
#[cfg_attr(not(feature = "deja"), allow(unused_mut))]
- let mut conn = pool
+ let mut connection = pool
+ .pg_pool
.get()
.await
.change_context(StorageError::DatabaseConnectionError)?;
+
#[cfg(feature = "deja")]
- deja_route_replay_schema(&mut conn, store).await;
- Ok(conn)
+ deja_route_replay_schema(&mut connection, store).await;
+
+ Ok(DatabaseConnectionWithContext::new(
+ connection,
+ store.request_id().map(str::to_owned),
+ pool.event_emitter.clone(),
+ ))
}
-pub async fn pg_connection_write<T: DatabaseStore>(
- store: &T,
-) -> error_stack::Result<
- PooledConnection<'_, async_bb8_diesel::ConnectionManager<DejaPgConnection>>,
- StorageError,
-> {
+/// Always leases from the replica pool, irrespective of the `olap`/`oltp` features.
+///
+/// `pg_connection_read` falls back to the master pool whenever `oltp` is enabled
+/// (including the default build, where both `olap` and `oltp` are on), so analytics
+/// style queries that must never touch master should use this instead. For stores
+/// without a configured replica (`Store`), `get_replica_pool` returns the master
+/// pool, so this stays correct in single-pool deployments.
+pub async fn pg_connection_read_replica<'a, T: DatabaseStore + RequestContext>(
+ store: &'a T,
+) -> error_stack::Result<DatabaseConnectionWithContext<'a>, StorageError> {
+ let pool = store.get_replica_pool();
+
+ #[cfg_attr(not(feature = "deja"), allow(unused_mut))]
+ let mut connection = pool
+ .pg_pool
+ .get()
+ .await
+ .change_context(StorageError::DatabaseConnectionError)?;
+
+ #[cfg(feature = "deja")]
+ deja_route_replay_schema(&mut connection, store).await;
+
+ Ok(DatabaseConnectionWithContext::new(
+ connection,
+ store.request_id().map(str::to_owned),
+ pool.event_emitter.clone(),
+ ))
+}
+
+pub async fn pg_connection_write<'a, T: DatabaseStore + RequestContext>(
+ store: &'a T,
+) -> error_stack::Result<DatabaseConnectionWithContext<'a>, StorageError> {
// Since all writes should happen to master DB only choose master DB.
let pool = store.get_master_pool();
#[cfg_attr(not(feature = "deja"), allow(unused_mut))]
- let mut conn = pool
+ let mut connection = pool
+ .pg_pool
.get()
.await
.change_context(StorageError::DatabaseConnectionError)?;
+
#[cfg(feature = "deja")]
- deja_route_replay_schema(&mut conn, store).await;
- Ok(conn)
+ deja_route_replay_schema(&mut connection, store).await;
+
+ Ok(DatabaseConnectionWithContext::new(
+ connection,
+ store.request_id().map(str::to_owned),
+ pool.event_emitter.clone(),
+ ))
}
-pub async fn pg_accounts_connection_read<T: DatabaseStore>(
- store: &T,
-) -> error_stack::Result<
- PooledConnection<'_, async_bb8_diesel::ConnectionManager<DejaPgConnection>>,
- StorageError,
-> {
+pub async fn pg_accounts_connection_read<'a, T: DatabaseStore + RequestContext>(
+ store: &'a T,
+) -> error_stack::Result<DatabaseConnectionWithContext<'a>, StorageError> {
// If only OLAP is enabled get replica pool.
#[cfg(all(feature = "olap", not(feature = "oltp")))]
let pool = store.get_accounts_replica_pool();
@@ -198,32 +235,43 @@ pub async fn pg_accounts_connection_read<T: DatabaseStore>(
let pool = store.get_accounts_master_pool();
#[cfg_attr(not(feature = "deja"), allow(unused_mut))]
- let mut conn = pool
+ let mut connection = pool
+ .pg_pool
.get()
.await
.change_context(StorageError::DatabaseConnectionError)?;
+
#[cfg(feature = "deja")]
- deja_route_replay_schema(&mut conn, store).await;
- Ok(conn)
+ deja_route_replay_schema(&mut connection, store).await;
+
+ Ok(DatabaseConnectionWithContext::new(
+ connection,
+ store.request_id().map(str::to_owned),
+ pool.event_emitter.clone(),
+ ))
}
-pub async fn pg_accounts_connection_write<T: DatabaseStore>(
- store: &T,
-) -> error_stack::Result<
- PooledConnection<'_, async_bb8_diesel::ConnectionManager<DejaPgConnection>>,
- StorageError,
-> {
+pub async fn pg_accounts_connection_write<'a, T: DatabaseStore + RequestContext>(
+ store: &'a T,
+) -> error_stack::Result<DatabaseConnectionWithContext<'a>, StorageError> {
// Since all writes should happen to master DB only choose master DB.
let pool = store.get_accounts_master_pool();
#[cfg_attr(not(feature = "deja"), allow(unused_mut))]
- let mut conn = pool
+ let mut connection = pool
+ .pg_pool
.get()
.await
.change_context(StorageError::DatabaseConnectionError)?;
+
#[cfg(feature = "deja")]
- deja_route_replay_schema(&mut conn, store).await;
- Ok(conn)
+ deja_route_replay_schema(&mut connection, store).await;
+
+ Ok(DatabaseConnectionWithContext::new(
+ connection,
+ store.request_id().map(str::to_owned),
+ pool.event_emitter.clone(),
+ ))
}
pub async fn try_redis_get_else_try_database_get<F, RFut, DFut, T>(