Dataset Viewer
Auto-converted to Parquet Duplicate
file_name
stringlengths
26
96
text
stringlengths
6.17k
164k
crates__analytics__src__clickhouse.rs
use std::sync::Arc; use actix_web::http::StatusCode; use common_utils::errors::ParsingError; use error_stack::{report, Report, ResultExt}; use router_env::logger; use time::PrimitiveDateTime; use super::{ active_payments::metrics::ActivePaymentsMetricRow, auth_events::metrics::AuthEventMetricRow, frm::{filters::FrmFilterRow, metrics::FrmMetricRow}, health_check::HealthCheck, payment_intents::{filters::PaymentIntentFilterRow, metrics::PaymentIntentMetricRow}, payments::{ distribution::PaymentDistributionRow, filters::PaymentFilterRow, metrics::PaymentMetricRow, }, query::{Aggregate, ToSql, Window}, refunds::{ distribution::RefundDistributionRow, filters::RefundFilterRow, metrics::RefundMetricRow, }, sdk_events::{filters::SdkEventFilter, metrics::SdkEventMetricRow}, types::{AnalyticsCollection, AnalyticsDataSource, LoadRow, QueryExecutionError}, }; use crate::{ api_event::{ events::ApiLogsResult, filters::ApiEventFilter, metrics::{latency::LatencyAvg, ApiEventMetricRow}, }, auth_events::filters::AuthEventFilterRow, connector_events::events::ConnectorEventsResult, disputes::{filters::DisputeFilterRow, metrics::DisputeMetricRow}, outgoing_webhook_event::events::OutgoingWebhookLogsResult, routing_events::events::RoutingEventsResult, sdk_events::events::SdkEventsResult, types::TableEngine, }; pub type ClickhouseResult<T> = error_stack::Result<T, ClickhouseError>; #[derive(Clone, Debug)] pub struct ClickhouseClient { pub config: Arc<ClickhouseConfig>, pub database: String, } #[derive(Clone, Debug, serde::Deserialize)] pub struct ClickhouseConfig { username: String, password: Option<String>, host: String, } impl Default for ClickhouseConfig { fn default() -> Self { Self { username: "default".to_string(), password: None, host: "http://localhost:8123".to_string(), } } } impl ClickhouseClient { async fn execute_query(&self, query: &str) -> ClickhouseResult<Vec<serde_json::Value>> { logger::debug!("Executing query: {query}"); let client = reqwest::Client::new(); let params = CkhQuery { date_time_output_format: String::from("iso"), output_format_json_quote_64bit_integers: 0, database: self.database.clone(), }; let response = client .post(&self.config.host) .query(&params) .basic_auth(self.config.username.clone(), self.config.password.clone()) .body(format!("{query}\nFORMAT JSON")) .send() .await .change_context(ClickhouseError::ConnectionError)?; logger::debug!(clickhouse_response=?response, query=?query, "Clickhouse response"); if response.status() != StatusCode::OK { response.text().await.map_or_else( |er| { Err(ClickhouseError::ResponseError) .attach_printable_lazy(|| format!("Error: {er:?}")) }, |t| Err(report!(ClickhouseError::ResponseNotOK(t))), ) } else { Ok(response .json::<CkhOutput<serde_json::Value>>() .await .change_context(ClickhouseError::ResponseError)? .data) } } } #[async_trait::async_trait] impl HealthCheck for ClickhouseClient { async fn deep_health_check( &self, ) -> common_utils::errors::CustomResult<(), QueryExecutionError> { self.execute_query("SELECT 1") .await .map(|_| ()) .change_context(QueryExecutionError::DatabaseError) } } #[async_trait::async_trait] impl AnalyticsDataSource for ClickhouseClient { type Row = serde_json::Value; async fn load_results<T>( &self, query: &str, ) -> common_utils::errors::CustomResult<Vec<T>, QueryExecutionError> where Self: LoadRow<T>, { self.execute_query(query) .await .change_context(QueryExecutionError::DatabaseError)? .into_iter() .map(Self::load_row) .collect::<Result<Vec<_>, _>>() .change_context(QueryExecutionError::RowExtractionFailure) } fn get_table_engine(table: AnalyticsCollection) -> TableEngine { match table { AnalyticsCollection::Payment | AnalyticsCollection::PaymentSessionized | AnalyticsCollection::Refund | AnalyticsCollection::RefundSessionized | AnalyticsCollection::FraudCheck | AnalyticsCollection::PaymentIntent | AnalyticsCollection::PaymentIntentSessionized | AnalyticsCollection::Authentications | AnalyticsCollection::Dispute => { TableEngine::CollapsingMergeTree { sign: "sign_flag" } } AnalyticsCollection::DisputeSessionized => { TableEngine::CollapsingMergeTree { sign: "sign_flag" } } AnalyticsCollection::SdkEvents | AnalyticsCollection::SdkEventsAnalytics | AnalyticsCollection::ApiEvents | AnalyticsCollection::ApiPayoutEvents | AnalyticsCollection::ConnectorEvents | AnalyticsCollection::ConnectorPayoutEvents | AnalyticsCollection::RoutingEvents | AnalyticsCollection::ApiEventsAnalytics | AnalyticsCollection::OutgoingWebhookEvent | AnalyticsCollection::OutgoingWebhookPayoutEvent | AnalyticsCollection::ActivePaymentsAnalytics => TableEngine::BasicTree, } } } impl<T, E> LoadRow<T> for ClickhouseClient where Self::Row: TryInto<T, Error = Report<E>>, { fn load_row(row: Self::Row) -> common_utils::errors::CustomResult<T, QueryExecutionError> { row.try_into() .map_err(|error| error.change_context(QueryExecutionError::RowExtractionFailure)) } } impl super::payments::filters::PaymentFilterAnalytics for ClickhouseClient {} impl super::payments::metrics::PaymentMetricAnalytics for ClickhouseClient {} impl super::payments::distribution::PaymentDistributionAnalytics for ClickhouseClient {} impl super::payment_intents::filters::PaymentIntentFilterAnalytics for ClickhouseClient {} impl super::payment_intents::metrics::PaymentIntentMetricAnalytics for ClickhouseClient {} impl super::refunds::metrics::RefundMetricAnalytics for ClickhouseClient {} impl super::refunds::filters::RefundFilterAnalytics for ClickhouseClient {} impl super::refunds::distribution::RefundDistributionAnalytics for ClickhouseClient {} impl super::frm::metrics::FrmMetricAnalytics for ClickhouseClient {} impl super::frm::filters::FrmFilterAnalytics for ClickhouseClient {} impl super::sdk_events::filters::SdkEventFilterAnalytics for ClickhouseClient {} impl super::sdk_events::metrics::SdkEventMetricAnalytics for ClickhouseClient {} impl super::sdk_events::events::SdkEventsFilterAnalytics for ClickhouseClient {} impl super::active_payments::metrics::ActivePaymentsMetricAnalytics for ClickhouseClient {} impl super::auth_events::metrics::AuthEventMetricAnalytics for ClickhouseClient {} impl super::auth_events::filters::AuthEventFilterAnalytics for ClickhouseClient {} impl super::api_event::events::ApiLogsFilterAnalytics for ClickhouseClient {} impl super::api_event::filters::ApiEventFilterAnalytics for ClickhouseClient {} impl super::api_event::metrics::ApiEventMetricAnalytics for ClickhouseClient {} impl super::connector_events::events::ConnectorEventLogAnalytics for ClickhouseClient {} impl super::routing_events::events::RoutingEventLogAnalytics for ClickhouseClient {} impl super::outgoing_webhook_event::events::OutgoingWebhookLogsFilterAnalytics for ClickhouseClient { } impl super::disputes::filters::DisputeFilterAnalytics for ClickhouseClient {} impl super::disputes::metrics::DisputeMetricAnalytics for ClickhouseClient {} #[derive(Debug, serde::Serialize)] struct CkhQuery { date_time_output_format: String, output_format_json_quote_64bit_integers: u8, database: String, } #[derive(Debug, serde::Deserialize)] struct CkhOutput<T> { data: Vec<T>, } impl TryInto<ApiLogsResult> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<ApiLogsResult, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse ApiLogsResult in clickhouse results", )) } } impl TryInto<SdkEventsResult> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<SdkEventsResult, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse SdkEventsResult in clickhouse results", )) } } impl TryInto<ConnectorEventsResult> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<ConnectorEventsResult, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse ConnectorEventsResult in clickhouse results", )) } } impl TryInto<RoutingEventsResult> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<RoutingEventsResult, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse RoutingEventsResult in clickhouse results", )) } } impl TryInto<PaymentMetricRow> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<PaymentMetricRow, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse PaymentMetricRow in clickhouse results", )) } } impl TryInto<PaymentDistributionRow> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<PaymentDistributionRow, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse PaymentDistributionRow in clickhouse results", )) } } impl TryInto<PaymentFilterRow> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<PaymentFilterRow, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse FilterRow in clickhouse results", )) } } impl TryInto<PaymentIntentMetricRow> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<PaymentIntentMetricRow, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse PaymentIntentMetricRow in clickhouse results", )) } } impl TryInto<PaymentIntentFilterRow> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<PaymentIntentFilterRow, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse PaymentIntentFilterRow in clickhouse results", )) } } impl TryInto<RefundMetricRow> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<RefundMetricRow, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse RefundMetricRow in clickhouse results", )) } } impl TryInto<RefundFilterRow> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<RefundFilterRow, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse RefundFilterRow in clickhouse results", )) } } impl TryInto<RefundDistributionRow> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<RefundDistributionRow, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse RefundDistributionRow in clickhouse results", )) } } impl TryInto<FrmMetricRow> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<FrmMetricRow, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse FrmMetricRow in clickhouse results", )) } } impl TryInto<FrmFilterRow> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<FrmFilterRow, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse FrmFilterRow in clickhouse results", )) } } impl TryInto<DisputeMetricRow> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<DisputeMetricRow, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse DisputeMetricRow in clickhouse results", )) } } impl TryInto<DisputeFilterRow> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<DisputeFilterRow, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse DisputeFilterRow in clickhouse results", )) } } impl TryInto<ApiEventMetricRow> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<ApiEventMetricRow, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse ApiEventMetricRow in clickhouse results", )) } } impl TryInto<LatencyAvg> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<LatencyAvg, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse LatencyAvg in clickhouse results", )) } } impl TryInto<SdkEventMetricRow> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<SdkEventMetricRow, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse SdkEventMetricRow in clickhouse results", )) } } impl TryInto<SdkEventFilter> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<SdkEventFilter, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse SdkEventFilter in clickhouse results", )) } } impl TryInto<AuthEventMetricRow> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<AuthEventMetricRow, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse AuthEventMetricRow in clickhouse results", )) } } impl TryInto<AuthEventFilterRow> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<AuthEventFilterRow, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse AuthEventFilterRow in clickhouse results", )) } } impl TryInto<ApiEventFilter> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<ApiEventFilter, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse ApiEventFilter in clickhouse results", )) } } impl TryInto<OutgoingWebhookLogsResult> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<OutgoingWebhookLogsResult, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse OutgoingWebhookLogsResult in clickhouse results", )) } } impl TryInto<ActivePaymentsMetricRow> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<ActivePaymentsMetricRow, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse ActivePaymentsMetricRow in clickhouse results", )) } } impl ToSql<ClickhouseClient> for PrimitiveDateTime { fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { Ok(self.assume_utc().unix_timestamp().to_string()) } } impl ToSql<ClickhouseClient> for AnalyticsCollection { fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { match self { Self::Payment => Ok("payment_attempts".to_string()), Self::PaymentSessionized => Ok("sessionizer_payment_attempts".to_string()), Self::Refund => Ok("refunds".to_string()), Self::RefundSessionized => Ok("sessionizer_refunds".to_string()), Self::FraudCheck => Ok("fraud_check".to_string()), Self::SdkEvents => Ok("sdk_events_audit".to_string()), Self::SdkEventsAnalytics => Ok("sdk_events".to_string()), Self::ApiEvents => Ok("api_events_audit".to_string()), Self::ApiPayoutEvents => Ok("api_events_payout_audit".to_string()), Self::ApiEventsAnalytics => Ok("api_events".to_string()), Self::PaymentIntent => Ok("payment_intents".to_string()), Self::PaymentIntentSessionized => Ok("sessionizer_payment_intents".to_string()), Self::ConnectorEvents => Ok("connector_events_audit".to_string()), Self::ConnectorPayoutEvents => Ok("connector_events_payout_audit".to_string()), Self::OutgoingWebhookEvent => Ok("outgoing_webhook_events_audit".to_string()), Self::OutgoingWebhookPayoutEvent => { Ok("outgoing_webhook_events_payout_audit".to_string()) } Self::Dispute => Ok("dispute".to_string()), Self::DisputeSessionized => Ok("sessionizer_dispute".to_string()), Self::ActivePaymentsAnalytics => Ok("active_payments".to_string()), Self::Authentications => Ok("authentications".to_string()), Self::RoutingEvents => Ok("routing_events_audit".to_string()), } } } impl<T> ToSql<ClickhouseClient> for Aggregate<T> where T: ToSql<ClickhouseClient>, { fn to_sql(&self, table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { Ok(match self { Self::Count { field: _, alias } => { let query = match table_engine { TableEngine::CollapsingMergeTree { sign } => format!("sum({sign})"), TableEngine::BasicTree => "count(*)".to_string(), }; format!( "{query}{}", alias.map_or_else(|| "".to_owned(), |alias| format!(" as {alias}")) ) } Self::Sum { field, alias } => { let query = match table_engine { TableEngine::CollapsingMergeTree { sign } => format!( "sum({sign} * {})", field .to_sql(table_engine) .attach_printable("Failed to sum aggregate")? ), TableEngine::BasicTree => format!( "sum({})", field .to_sql(table_engine) .attach_printable("Failed to sum aggregate")? ), }; format!( "{query}{}", alias.map_or_else(|| "".to_owned(), |alias| format!(" as {alias}")) ) } Self::Min { field, alias } => { format!( "min({}){}", field .to_sql(table_engine) .attach_printable("Failed to min aggregate")?, alias.map_or_else(|| "".to_owned(), |alias| format!(" as {alias}")) ) } Self::Max { field, alias } => { format!( "max({}){}", field .to_sql(table_engine) .attach_printable("Failed to max aggregate")?, alias.map_or_else(|| "".to_owned(), |alias| format!(" as {alias}")) ) } Self::Percentile { field, alias, percentile, } => { format!( "quantilesExact(0.{})({})[1]{}", percentile.map_or_else(|| "50".to_owned(), |percentile| percentile.to_string()), field .to_sql(table_engine) .attach_printable("Failed to percentile aggregate")?, alias.map_or_else(|| "".to_owned(), |alias| format!(" as {alias}")) ) } Self::DistinctCount { field, alias } => { format!( "count(distinct {}){}", field .to_sql(table_engine) .attach_printable("Failed to percentile aggregate")?, alias.map_or_else(|| "".to_owned(), |alias| format!(" as {alias}")) ) } }) } } impl<T> ToSql<ClickhouseClient> for Window<T> where T: ToSql<ClickhouseClient>, { fn to_sql(&self, table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { Ok(match self { Self::Sum { field, partition_by, order_by, alias, } => { format!( "sum({}) over ({}{}){}", field .to_sql(table_engine) .attach_printable("Failed to sum window")?, partition_by.as_ref().map_or_else( || "".to_owned(), |partition_by| format!("partition by {}", partition_by.to_owned()) ), order_by.as_ref().map_or_else( || "".to_owned(), |(order_column, order)| format!( " order by {} {}", order_column.to_owned(), order ) ), alias.map_or_else(|| "".to_owned(), |alias| format!(" as {alias}")) ) } Self::RowNumber { field: _, partition_by, order_by, alias, } => { format!( "row_number() over ({}{}){}", partition_by.as_ref().map_or_else( || "".to_owned(), |partition_by| format!("partition by {}", partition_by.to_owned()) ), order_by.as_ref().map_or_else( || "".to_owned(), |(order_column, order)| format!( " order by {} {}", order_column.to_owned(), order ) ), alias.map_or_else(|| "".to_owned(), |alias| format!(" as {alias}")) ) } }) } } #[derive(Debug, thiserror::Error)] pub enum ClickhouseError { #[error("Clickhouse connection error")] ConnectionError, #[error("Clickhouse NON-200 response content: '{0}'")] ResponseNotOK(String), #[error("Clickhouse response error")] ResponseError, }
crates__analytics__src__sqlx.rs
use std::{fmt::Display, str::FromStr}; use api_models::{ analytics::{frm::FrmTransactionType, refunds::RefundType}, enums::{DisputeStage, DisputeStatus}, }; use common_enums::{ AuthenticationConnectors, AuthenticationStatus, DecoupledAuthenticationType, TransactionStatus, }; use common_utils::{ errors::{CustomResult, ParsingError}, DbConnectionParams, }; use diesel_models::enums::{ AttemptStatus, AuthenticationType, Currency, FraudCheckStatus, IntentStatus, PaymentMethod, RefundStatus, RoutingApproach, }; use error_stack::ResultExt; use sqlx::{ postgres::{PgArgumentBuffer, PgPoolOptions, PgRow, PgTypeInfo, PgValueRef}, Decode, Encode, Error::ColumnNotFound, FromRow, Pool, Postgres, Row, }; use storage_impl::config::Database; use time::PrimitiveDateTime; use super::{ health_check::HealthCheck, query::{Aggregate, ToSql, Window}, types::{ AnalyticsCollection, AnalyticsDataSource, DBEnumWrapper, LoadRow, QueryExecutionError, TableEngine, }, }; #[derive(Debug, Clone)] pub struct SqlxClient { pool: Pool<Postgres>, } impl Default for SqlxClient { fn default() -> Self { let database_url = format!( "postgres://{}:{}@{}:{}/{}", "db_user", "db_pass", "localhost", 5432, "hyperswitch_db" ); Self { #[allow(clippy::expect_used)] pool: PgPoolOptions::new() .connect_lazy(&database_url) .expect("SQLX Pool Creation failed"), } } } impl SqlxClient { pub async fn from_conf(conf: &Database, schema: &str) -> Self { let database_url = conf.get_database_url(schema); #[allow(clippy::expect_used)] let pool = PgPoolOptions::new() .max_connections(conf.pool_size) .acquire_timeout(std::time::Duration::from_secs(conf.connection_timeout)) .connect_lazy(&database_url) .expect("SQLX Pool Creation failed"); Self { pool } } } pub trait DbType { fn name() -> &'static str; } macro_rules! db_type { ($a: ident, $str: tt) => { impl DbType for $a { fn name() -> &'static str { stringify!($str) } } }; ($a:ident) => { impl DbType for $a { fn name() -> &'static str { stringify!($a) } } }; } db_type!(Currency); db_type!(AuthenticationType); db_type!(AttemptStatus); db_type!(IntentStatus); db_type!(PaymentMethod, TEXT); db_type!(RefundStatus); db_type!(RefundType); db_type!(FraudCheckStatus); db_type!(FrmTransactionType); db_type!(DisputeStage); db_type!(DisputeStatus); db_type!(AuthenticationStatus); db_type!(TransactionStatus); db_type!(AuthenticationConnectors); db_type!(DecoupledAuthenticationType); db_type!(RoutingApproach); impl<'q, Type> Encode<'q, Postgres> for DBEnumWrapper<Type> where Type: DbType + FromStr + Display, { fn encode_by_ref( &self, buf: &mut PgArgumentBuffer, ) -> Result<sqlx::encode::IsNull, Box<dyn std::error::Error + Send + Sync + 'static>> { <String as Encode<'q, Postgres>>::encode(self.0.to_string(), buf) } fn size_hint(&self) -> usize { <String as Encode<'q, Postgres>>::size_hint(&self.0.to_string()) } } impl<'r, Type> Decode<'r, Postgres> for DBEnumWrapper<Type> where Type: DbType + FromStr + Display, { fn decode( value: PgValueRef<'r>, ) -> Result<Self, Box<dyn std::error::Error + 'static + Send + Sync>> { let str_value = <&'r str as Decode<'r, Postgres>>::decode(value)?; Type::from_str(str_value).map(DBEnumWrapper).or(Err(format!( "invalid value {:?} for enum {}", str_value, Type::name() ) .into())) } } impl<Type> sqlx::Type<Postgres> for DBEnumWrapper<Type> where Type: DbType + FromStr + Display, { fn type_info() -> PgTypeInfo { PgTypeInfo::with_name(Type::name()) } } impl<T> LoadRow<T> for SqlxClient where for<'a> T: FromRow<'a, PgRow>, { fn load_row(row: PgRow) -> CustomResult<T, QueryExecutionError> { T::from_row(&row).change_context(QueryExecutionError::RowExtractionFailure) } } impl super::payments::filters::PaymentFilterAnalytics for SqlxClient {} impl super::payments::metrics::PaymentMetricAnalytics for SqlxClient {} impl super::payments::distribution::PaymentDistributionAnalytics for SqlxClient {} impl super::payment_intents::filters::PaymentIntentFilterAnalytics for SqlxClient {} impl super::payment_intents::metrics::PaymentIntentMetricAnalytics for SqlxClient {} impl super::refunds::metrics::RefundMetricAnalytics for SqlxClient {} impl super::refunds::filters::RefundFilterAnalytics for SqlxClient {} impl super::refunds::distribution::RefundDistributionAnalytics for SqlxClient {} impl super::disputes::filters::DisputeFilterAnalytics for SqlxClient {} impl super::disputes::metrics::DisputeMetricAnalytics for SqlxClient {} impl super::frm::metrics::FrmMetricAnalytics for SqlxClient {} impl super::frm::filters::FrmFilterAnalytics for SqlxClient {} impl super::auth_events::metrics::AuthEventMetricAnalytics for SqlxClient {} impl super::auth_events::filters::AuthEventFilterAnalytics for SqlxClient {} #[async_trait::async_trait] impl AnalyticsDataSource for SqlxClient { type Row = PgRow; async fn load_results<T>(&self, query: &str) -> CustomResult<Vec<T>, QueryExecutionError> where Self: LoadRow<T>, { sqlx::query(&format!("{query};")) .fetch_all(&self.pool) .await .change_context(QueryExecutionError::DatabaseError) .attach_printable_lazy(|| format!("Failed to run query {query}"))? .into_iter() .map(Self::load_row) .collect::<Result<Vec<_>, _>>() .change_context(QueryExecutionError::RowExtractionFailure) } } #[async_trait::async_trait] impl HealthCheck for SqlxClient { async fn deep_health_check(&self) -> CustomResult<(), QueryExecutionError> { sqlx::query("SELECT 1") .fetch_all(&self.pool) .await .map(|_| ()) .change_context(QueryExecutionError::DatabaseError) } } impl<'a> FromRow<'a, PgRow> for super::auth_events::metrics::AuthEventMetricRow { fn from_row(row: &'a PgRow) -> sqlx::Result<Self> { let authentication_status: Option<DBEnumWrapper<AuthenticationStatus>> = row.try_get("authentication_status").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let trans_status: Option<DBEnumWrapper<TransactionStatus>> = row.try_get("trans_status").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let authentication_type: Option<DBEnumWrapper<DecoupledAuthenticationType>> = row.try_get("authentication_type").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let error_message: Option<String> = row.try_get("error_message").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let authentication_connector: Option<DBEnumWrapper<AuthenticationConnectors>> = row .try_get("authentication_connector") .or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let message_version: Option<String> = row.try_get("message_version").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let platform: Option<String> = row.try_get("platform").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let acs_reference_number: Option<String> = row.try_get("acs_reference_number").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let count: Option<i64> = row.try_get("count").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; // Removing millisecond precision to get accurate diffs against clickhouse let start_bucket: Option<PrimitiveDateTime> = row .try_get::<Option<PrimitiveDateTime>, _>("start_bucket")? .and_then(|dt| dt.replace_millisecond(0).ok()); let end_bucket: Option<PrimitiveDateTime> = row .try_get::<Option<PrimitiveDateTime>, _>("end_bucket")? .and_then(|dt| dt.replace_millisecond(0).ok()); let mcc: Option<String> = row.try_get("mcc").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let currency: Option<DBEnumWrapper<Currency>> = row.try_get("currency").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let merchant_country: Option<String> = row.try_get("merchant_country").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let billing_country: Option<String> = row.try_get("billing_country").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let shipping_country: Option<String> = row.try_get("shipping_country").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let issuer_country: Option<String> = row.try_get("issuer_country").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let earliest_supported_version: Option<String> = row .try_get("earliest_supported_version") .or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let latest_supported_version: Option<String> = row .try_get("latest_supported_version") .or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let whitelist_decision: Option<bool> = row.try_get("whitelist_decision").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let device_manufacturer: Option<String> = row.try_get("device_manufacturer").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let device_type: Option<String> = row.try_get("device_type").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let device_brand: Option<String> = row.try_get("device_brand").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let device_os: Option<String> = row.try_get("device_os").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let device_display: Option<String> = row.try_get("device_display").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let browser_name: Option<String> = row.try_get("browser_name").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let browser_version: Option<String> = row.try_get("browser_version").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let issuer_id: Option<String> = row.try_get("issuer_id").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let scheme_name: Option<String> = row.try_get("scheme_name").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let exemption_requested: Option<bool> = row.try_get("exemption_requested").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let exemption_accepted: Option<bool> = row.try_get("exemption_accepted").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; Ok(Self { authentication_status, trans_status, authentication_type, error_message, authentication_connector, message_version, acs_reference_number, platform, count, start_bucket, end_bucket, mcc, currency, merchant_country, billing_country, shipping_country, issuer_country, earliest_supported_version, latest_supported_version, whitelist_decision, device_manufacturer, device_type, device_brand, device_os, device_display, browser_name, browser_version, issuer_id, scheme_name, exemption_requested, exemption_accepted, }) } } impl<'a> FromRow<'a, PgRow> for super::auth_events::filters::AuthEventFilterRow { fn from_row(row: &'a PgRow) -> sqlx::Result<Self> { let authentication_status: Option<DBEnumWrapper<AuthenticationStatus>> = row.try_get("authentication_status").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let trans_status: Option<DBEnumWrapper<TransactionStatus>> = row.try_get("trans_status").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let authentication_type: Option<DBEnumWrapper<DecoupledAuthenticationType>> = row.try_get("authentication_type").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let error_message: Option<String> = row.try_get("error_message").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let authentication_connector: Option<DBEnumWrapper<AuthenticationConnectors>> = row .try_get("authentication_connector") .or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let message_version: Option<String> = row.try_get("message_version").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let acs_reference_number: Option<String> = row.try_get("acs_reference_number").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let platform: Option<String> = row.try_get("platform").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let mcc: Option<String> = row.try_get("mcc").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let currency: Option<DBEnumWrapper<Currency>> = row.try_get("currency").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let merchant_country: Option<String> = row.try_get("merchant_country").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let billing_country: Option<String> = row.try_get("billing_country").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let shipping_country: Option<String> = row.try_get("shipping_country").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let issuer_country: Option<String> = row.try_get("issuer_country").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let earliest_supported_version: Option<String> = row .try_get("earliest_supported_version") .or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let latest_supported_version: Option<String> = row .try_get("latest_supported_version") .or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let whitelist_decision: Option<bool> = row.try_get("whitelist_decision").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let device_manufacturer: Option<String> = row.try_get("device_manufacturer").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let device_type: Option<String> = row.try_get("device_type").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let device_brand: Option<String> = row.try_get("device_brand").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let device_os: Option<String> = row.try_get("device_os").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let device_display: Option<String> = row.try_get("device_display").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let browser_name: Option<String> = row.try_get("browser_name").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let browser_version: Option<String> = row.try_get("browser_version").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let issuer_id: Option<String> = row.try_get("issuer_id").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let scheme_name: Option<String> = row.try_get("scheme_name").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let exemption_requested: Option<bool> = row.try_get("exemption_requested").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let exemption_accepted: Option<bool> = row.try_get("exemption_accepted").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; Ok(Self { authentication_status, trans_status, authentication_type, error_message, authentication_connector, message_version, platform, acs_reference_number, mcc, currency, merchant_country, billing_country, shipping_country, issuer_country, earliest_supported_version, latest_supported_version, whitelist_decision, device_manufacturer, device_type, device_brand, device_os, device_display, browser_name, browser_version, issuer_id, scheme_name, exemption_requested, exemption_accepted, }) } } impl<'a> FromRow<'a, PgRow> for super::refunds::metrics::RefundMetricRow { fn from_row(row: &'a PgRow) -> sqlx::Result<Self> { let currency: Option<DBEnumWrapper<Currency>> = row.try_get("currency").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let refund_status: Option<DBEnumWrapper<RefundStatus>> = row.try_get("refund_status").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let connector: Option<String> = row.try_get("connector").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let refund_type: Option<DBEnumWrapper<RefundType>> = row.try_get("refund_type").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let profile_id: Option<String> = row.try_get("profile_id").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let refund_reason: Option<String> = row.try_get("refund_reason").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let refund_error_message: Option<String> = row.try_get("refund_error_message").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let total: Option<bigdecimal::BigDecimal> = row.try_get("total").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let count: Option<i64> = row.try_get("count").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; // Removing millisecond precision to get accurate diffs against clickhouse let start_bucket: Option<PrimitiveDateTime> = row .try_get::<Option<PrimitiveDateTime>, _>("start_bucket")? .and_then(|dt| dt.replace_millisecond(0).ok()); let end_bucket: Option<PrimitiveDateTime> = row .try_get::<Option<PrimitiveDateTime>, _>("end_bucket")? .and_then(|dt| dt.replace_millisecond(0).ok()); Ok(Self { currency, refund_status, connector, refund_type, profile_id, refund_reason, refund_error_message, total, count, start_bucket, end_bucket, }) } } impl<'a> FromRow<'a, PgRow> for super::frm::metrics::FrmMetricRow { fn from_row(row: &'a PgRow) -> sqlx::Result<Self> { let frm_name: Option<String> = row.try_get("frm_name").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let frm_status: Option<DBEnumWrapper<FraudCheckStatus>> = row.try_get("frm_status").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let frm_transaction_type: Option<DBEnumWrapper<FrmTransactionType>> = row.try_get("frm_transaction_type").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let total: Option<bigdecimal::BigDecimal> = row.try_get("total").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let count: Option<i64> = row.try_get("count").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; // Removing millisecond precision to get accurate diffs against clickhouse let start_bucket: Option<PrimitiveDateTime> = row .try_get::<Option<PrimitiveDateTime>, _>("start_bucket")? .and_then(|dt| dt.replace_millisecond(0).ok()); let end_bucket: Option<PrimitiveDateTime> = row .try_get::<Option<PrimitiveDateTime>, _>("end_bucket")? .and_then(|dt| dt.replace_millisecond(0).ok()); Ok(Self { frm_name, frm_status, frm_transaction_type, total, count, start_bucket, end_bucket, }) } } impl<'a> FromRow<'a, PgRow> for super::payments::metrics::PaymentMetricRow { fn from_row(row: &'a PgRow) -> sqlx::Result<Self> { let currency: Option<DBEnumWrapper<Currency>> = row.try_get("currency").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let status: Option<DBEnumWrapper<AttemptStatus>> = row.try_get("status").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let connector: Option<String> = row.try_get("connector").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let authentication_type: Option<DBEnumWrapper<AuthenticationType>> = row.try_get("authentication_type").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let payment_method: Option<String> = row.try_get("payment_method").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let payment_method_type: Option<String> = row.try_get("payment_method_type").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let client_source: Option<String> = row.try_get("client_source").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let client_version: Option<String> = row.try_get("client_version").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let profile_id: Option<String> = row.try_get("profile_id").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let card_network: Option<String> = row.try_get("card_network").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let merchant_id: Option<String> = row.try_get("merchant_id").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let card_last_4: Option<String> = row.try_get("card_last_4").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let card_issuer: Option<String> = row.try_get("card_issuer").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let error_reason: Option<String> = row.try_get("error_reason").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let first_attempt: Option<bool> = row.try_get("first_attempt").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let routing_approach: Option<DBEnumWrapper<RoutingApproach>> = row.try_get("routing_approach").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let signature_network: Option<String> = row.try_get("signature_network").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let is_issuer_regulated: Option<bool> = row.try_get("is_issuer_regulated").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let is_debit_routed: Option<bool> = row.try_get("is_debit_routed").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let total: Option<bigdecimal::BigDecimal> = row.try_get("total").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let count: Option<i64> = row.try_get("count").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; // Removing millisecond precision to get accurate diffs against clickhouse let start_bucket: Option<PrimitiveDateTime> = row .try_get::<Option<PrimitiveDateTime>, _>("start_bucket")? .and_then(|dt| dt.replace_millisecond(0).ok()); let end_bucket: Option<PrimitiveDateTime> = row .try_get::<Option<PrimitiveDateTime>, _>("end_bucket")? .and_then(|dt| dt.replace_millisecond(0).ok()); Ok(Self { currency, status, connector, authentication_type, payment_method, payment_method_type, client_source, client_version, profile_id, card_network, merchant_id, card_last_4, card_issuer, error_reason, first_attempt, routing_approach, signature_network, is_issuer_regulated, is_debit_routed, total, count, start_bucket, end_bucket, }) } } impl<'a> FromRow<'a, PgRow> for super::payments::distribution::PaymentDistributionRow { fn from_row(row: &'a PgRow) -> sqlx::Result<Self> { let currency: Option<DBEnumWrapper<Currency>> = row.try_get("currency").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let status: Option<DBEnumWrapper<AttemptStatus>> = row.try_get("status").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let connector: Option<String> = row.try_get("connector").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let authentication_type: Option<DBEnumWrapper<AuthenticationType>> = row.try_get("authentication_type").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let payment_method: Option<String> = row.try_get("payment_method").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let payment_method_type: Option<String> = row.try_get("payment_method_type").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let client_source: Option<String> = row.try_get("client_source").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let client_version: Option<String> = row.try_get("client_version").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let profile_id: Option<String> = row.try_get("profile_id").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let card_network: Option<String> = row.try_get("card_network").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let merchant_id: Option<String> = row.try_get("merchant_id").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let card_last_4: Option<String> = row.try_get("card_last_4").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let card_issuer: Option<String> = row.try_get("card_issuer").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let error_reason: Option<String> = row.try_get("error_reason").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let routing_approach: Option<DBEnumWrapper<RoutingApproach>> = row.try_get("routing_approach").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let signature_network: Option<String> = row.try_get("signature_network").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let is_issuer_regulated: Option<bool> = row.try_get("is_issuer_regulated").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let is_debit_routed: Option<bool> = row.try_get("is_debit_routed").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let total: Option<bigdecimal::BigDecimal> = row.try_get("total").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let count: Option<i64> = row.try_get("count").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let error_message: Option<String> = row.try_get("error_message").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let first_attempt: Option<bool> = row.try_get("first_attempt").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; // Removing millisecond precision to get accurate diffs against clickhouse let start_bucket: Option<PrimitiveDateTime> = row .try_get::<Option<PrimitiveDateTime>, _>("start_bucket")? .and_then(|dt| dt.replace_millisecond(0).ok()); let end_bucket: Option<PrimitiveDateTime> = row .try_get::<Option<PrimitiveDateTime>, _>("end_bucket")? .and_then(|dt| dt.replace_millisecond(0).ok()); Ok(Self { currency, status, connector, authentication_type, payment_method, payment_method_type, client_source, client_version, profile_id, card_network, merchant_id, card_last_4, card_issuer, error_reason, first_attempt, total, count, error_message, routing_approach, signature_network, is_issuer_regulated, is_debit_routed, start_bucket, end_bucket, }) } } impl<'a> FromRow<'a, PgRow> for super::payments::filters::PaymentFilterRow { fn from_row(row: &'a PgRow) -> sqlx::Result<Self> { let currency: Option<DBEnumWrapper<Currency>> = row.try_get("currency").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let status: Option<DBEnumWrapper<AttemptStatus>> = row.try_get("status").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let connector: Option<String> = row.try_get("connector").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let authentication_type: Option<DBEnumWrapper<AuthenticationType>> = row.try_get("authentication_type").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let payment_method: Option<String> = row.try_get("payment_method").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let payment_method_type: Option<String> = row.try_get("payment_method_type").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let client_source: Option<String> = row.try_get("client_source").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let client_version: Option<String> = row.try_get("client_version").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let profile_id: Option<String> = row.try_get("profile_id").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let card_network: Option<String> = row.try_get("card_network").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let merchant_id: Option<String> = row.try_get("merchant_id").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let card_last_4: Option<String> = row.try_get("card_last_4").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let card_issuer: Option<String> = row.try_get("card_issuer").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let error_reason: Option<String> = row.try_get("error_reason").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let first_attempt: Option<bool> = row.try_get("first_attempt").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let routing_approach: Option<DBEnumWrapper<RoutingApproach>> = row.try_get("routing_approach").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let signature_network: Option<String> = row.try_get("signature_network").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let is_issuer_regulated: Option<bool> = row.try_get("is_issuer_regulated").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let is_debit_routed: Option<bool> = row.try_get("is_debit_routed").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; Ok(Self { currency, status, connector, authentication_type, payment_method, payment_method_type, client_source, client_version, profile_id, card_network, merchant_id, card_last_4, card_issuer, error_reason, first_attempt, routing_approach, signature_network, is_issuer_regulated, is_debit_routed, }) } } impl<'a> FromRow<'a, PgRow> for super::payment_intents::metrics::PaymentIntentMetricRow { fn from_row(row: &'a PgRow) -> sqlx::Result<Self> { let status: Option<DBEnumWrapper<IntentStatus>> = row.try_get("status").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let currency: Option<DBEnumWrapper<Currency>> = row.try_get("currency").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let profile_id: Option<String> = row.try_get("profile_id").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let connector: Option<String> = row.try_get("connector").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let authentication_type: Option<DBEnumWrapper<AuthenticationType>> = row.try_get("authentication_type").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let payment_method: Option<String> = row.try_get("payment_method").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let payment_method_type: Option<String> = row.try_get("payment_method_type").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let card_network: Option<String> = row.try_get("card_network").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let merchant_id: Option<String> = row.try_get("merchant_id").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let card_last_4: Option<String> = row.try_get("card_last_4").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let card_issuer: Option<String> = row.try_get("card_issuer").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let error_reason: Option<String> = row.try_get("error_reason").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let total: Option<bigdecimal::BigDecimal> = row.try_get("total").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let count: Option<i64> = row.try_get("count").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let first_attempt: Option<i64> = row.try_get("first_attempt").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; // Removing millisecond precision to get accurate diffs against clickhouse let start_bucket: Option<PrimitiveDateTime> = row .try_get::<Option<PrimitiveDateTime>, _>("start_bucket")? .and_then(|dt| dt.replace_millisecond(0).ok()); let end_bucket: Option<PrimitiveDateTime> = row .try_get::<Option<PrimitiveDateTime>, _>("end_bucket")? .and_then(|dt| dt.replace_millisecond(0).ok()); Ok(Self { status, currency, profile_id, connector, authentication_type, payment_method, payment_method_type, card_network, merchant_id, card_last_4, card_issuer, error_reason, first_attempt, total, count, start_bucket, end_bucket, }) } } impl<'a> FromRow<'a, PgRow> for super::payment_intents::filters::PaymentIntentFilterRow { fn from_row(row: &'a PgRow) -> sqlx::Result<Self> { let status: Option<DBEnumWrapper<IntentStatus>> = row.try_get("status").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let currency: Option<DBEnumWrapper<Currency>> = row.try_get("currency").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let profile_id: Option<String> = row.try_get("profile_id").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let connector: Option<String> = row.try_get("connector").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let authentication_type: Option<DBEnumWrapper<AuthenticationType>> = row.try_get("authentication_type").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let payment_method: Option<String> = row.try_get("payment_method").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let payment_method_type: Option<String> = row.try_get("payment_method_type").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let card_network: Option<String> = row.try_get("card_network").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let merchant_id: Option<String> = row.try_get("merchant_id").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let card_last_4: Option<String> = row.try_get("card_last_4").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let card_issuer: Option<String> = row.try_get("card_issuer").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let error_reason: Option<String> = row.try_get("error_reason").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let customer_id: Option<String> = row.try_get("customer_id").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; Ok(Self { status, currency, profile_id, connector, authentication_type, payment_method, payment_method_type, card_network, merchant_id, card_last_4, card_issuer, error_reason, customer_id, }) } } impl<'a> FromRow<'a, PgRow> for super::refunds::filters::RefundFilterRow { fn from_row(row: &'a PgRow) -> sqlx::Result<Self> { let currency: Option<DBEnumWrapper<Currency>> = row.try_get("currency").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let refund_status: Option<DBEnumWrapper<RefundStatus>> = row.try_get("refund_status").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let connector: Option<String> = row.try_get("connector").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let refund_type: Option<DBEnumWrapper<RefundType>> = row.try_get("refund_type").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let profile_id: Option<String> = row.try_get("profile_id").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let refund_reason: Option<String> = row.try_get("refund_reason").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let refund_error_message: Option<String> = row.try_get("refund_error_message").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; Ok(Self { currency, refund_status, connector, refund_type, profile_id, refund_reason, refund_error_message, }) } } impl<'a> FromRow<'a, PgRow> for super::refunds::distribution::RefundDistributionRow { fn from_row(row: &'a PgRow) -> sqlx::Result<Self> { let currency: Option<DBEnumWrapper<Currency>> = row.try_get("currency").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let refund_status: Option<DBEnumWrapper<RefundStatus>> = row.try_get("refund_status").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let connector: Option<String> = row.try_get("connector").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let refund_type: Option<DBEnumWrapper<RefundType>> = row.try_get("refund_type").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let profile_id: Option<String> = row.try_get("profile_id").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let total: Option<bigdecimal::BigDecimal> = row.try_get("total").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let count: Option<i64> = row.try_get("count").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let refund_reason: Option<String> = row.try_get("refund_reason").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let refund_error_message: Option<String> = row.try_get("refund_error_message").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; // Removing millisecond precision to get accurate diffs against clickhouse let start_bucket: Option<PrimitiveDateTime> = row .try_get::<Option<PrimitiveDateTime>, _>("start_bucket")? .and_then(|dt| dt.replace_millisecond(0).ok()); let end_bucket: Option<PrimitiveDateTime> = row .try_get::<Option<PrimitiveDateTime>, _>("end_bucket")? .and_then(|dt| dt.replace_millisecond(0).ok()); Ok(Self { currency, refund_status, connector, refund_type, profile_id, total, count, refund_reason, refund_error_message, start_bucket, end_bucket, }) } } impl<'a> FromRow<'a, PgRow> for super::frm::filters::FrmFilterRow { fn from_row(row: &'a PgRow) -> sqlx::Result<Self> { let frm_name: Option<String> = row.try_get("frm_name").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let frm_status: Option<DBEnumWrapper<FraudCheckStatus>> = row.try_get("frm_status").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let frm_transaction_type: Option<DBEnumWrapper<FrmTransactionType>> = row.try_get("frm_transaction_type").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; Ok(Self { frm_name, frm_status, frm_transaction_type, }) } } impl<'a> FromRow<'a, PgRow> for super::disputes::filters::DisputeFilterRow { fn from_row(row: &'a PgRow) -> sqlx::Result<Self> { let dispute_stage: Option<String> = row.try_get("dispute_stage").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let dispute_status: Option<String> = row.try_get("dispute_status").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let connector: Option<String> = row.try_get("connector").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let connector_status: Option<String> = row.try_get("connector_status").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let currency: Option<DBEnumWrapper<Currency>> = row.try_get("currency").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; Ok(Self { dispute_stage, dispute_status, connector, connector_status, currency, }) } } impl<'a> FromRow<'a, PgRow> for super::disputes::metrics::DisputeMetricRow { fn from_row(row: &'a PgRow) -> sqlx::Result<Self> { let dispute_stage: Option<DBEnumWrapper<DisputeStage>> = row.try_get("dispute_stage").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let dispute_status: Option<DBEnumWrapper<DisputeStatus>> = row.try_get("dispute_status").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let connector: Option<String> = row.try_get("connector").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let currency: Option<DBEnumWrapper<Currency>> = row.try_get("currency").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let total: Option<bigdecimal::BigDecimal> = row.try_get("total").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let count: Option<i64> = row.try_get("count").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; // Removing millisecond precision to get accurate diffs against clickhouse let start_bucket: Option<PrimitiveDateTime> = row .try_get::<Option<PrimitiveDateTime>, _>("start_bucket")? .and_then(|dt| dt.replace_millisecond(0).ok()); let end_bucket: Option<PrimitiveDateTime> = row .try_get::<Option<PrimitiveDateTime>, _>("end_bucket")? .and_then(|dt| dt.replace_millisecond(0).ok()); Ok(Self { dispute_stage, dispute_status, connector, currency, total, count, start_bucket, end_bucket, }) } } impl ToSql<SqlxClient> for PrimitiveDateTime { fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { Ok(self.to_string()) } } impl ToSql<SqlxClient> for AnalyticsCollection { fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { match self { Self::Payment => Ok("payment_attempt".to_string()), Self::PaymentSessionized => Err(error_stack::report!(ParsingError::UnknownError) .attach_printable("PaymentSessionized table is not implemented for Sqlx"))?, Self::Refund => Ok("refund".to_string()), Self::RefundSessionized => Err(error_stack::report!(ParsingError::UnknownError) .attach_printable("RefundSessionized table is not implemented for Sqlx"))?, Self::SdkEvents => Err(error_stack::report!(ParsingError::UnknownError) .attach_printable("SdkEventsAudit table is not implemented for Sqlx"))?, Self::SdkEventsAnalytics => Err(error_stack::report!(ParsingError::UnknownError) .attach_printable("SdkEvents table is not implemented for Sqlx"))?, Self::ApiEvents => Err(error_stack::report!(ParsingError::UnknownError) .attach_printable("ApiEvents table is not implemented for Sqlx"))?, Self::ApiPayoutEvents => Err(error_stack::report!(ParsingError::UnknownError) .attach_printable("ApiPayoutEvents table is not implemented for Sqlx"))?, Self::FraudCheck => Ok("fraud_check".to_string()), Self::PaymentIntent => Ok("payment_intent".to_string()), Self::PaymentIntentSessionized => Err(error_stack::report!( ParsingError::UnknownError ) .attach_printable("PaymentIntentSessionized table is not implemented for Sqlx"))?, Self::ConnectorEvents => Err(error_stack::report!(ParsingError::UnknownError) .attach_printable("ConnectorEvents table is not implemented for Sqlx"))?, Self::ConnectorPayoutEvents => Err(error_stack::report!(ParsingError::UnknownError) .attach_printable("ConnectorPayoutEvents table is not implemented for Sqlx"))?, Self::ApiEventsAnalytics => Err(error_stack::report!(ParsingError::UnknownError) .attach_printable("ApiEvents table is not implemented for Sqlx"))?, Self::ActivePaymentsAnalytics => Err(error_stack::report!(ParsingError::UnknownError) .attach_printable("ActivePaymentsAnalytics table is not implemented for Sqlx"))?, Self::OutgoingWebhookEvent => Err(error_stack::report!(ParsingError::UnknownError) .attach_printable("OutgoingWebhookEvents table is not implemented for Sqlx"))?, Self::OutgoingWebhookPayoutEvent => Err(error_stack::report!( ParsingError::UnknownError ) .attach_printable("OutgoingWebhookPayoutEvents table is not implemented for Sqlx"))?, Self::Dispute => Ok("dispute".to_string()), Self::DisputeSessionized => Err(error_stack::report!(ParsingError::UnknownError) .attach_printable("DisputeSessionized table is not implemented for Sqlx"))?, Self::Authentications => Err(error_stack::report!(ParsingError::UnknownError) .attach_printable("Authentications table is not implemented for Sqlx"))?, Self::RoutingEvents => Err(error_stack::report!(ParsingError::UnknownError) .attach_printable("RoutingEvents table is not implemented for Sqlx"))?, } } } impl<T> ToSql<SqlxClient> for Aggregate<T> where T: ToSql<SqlxClient>, { fn to_sql(&self, table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { Ok(match self { Self::Count { field: _, alias } => { format!( "count(*){}", alias.map_or_else(|| "".to_owned(), |alias| format!(" as {alias}")) ) } Self::Sum { field, alias } => { format!( "sum({}){}", field .to_sql(table_engine) .attach_printable("Failed to sum aggregate")?, alias.map_or_else(|| "".to_owned(), |alias| format!(" as {alias}")) ) } Self::Min { field, alias } => { format!( "min({}){}", field .to_sql(table_engine) .attach_printable("Failed to min aggregate")?, alias.map_or_else(|| "".to_owned(), |alias| format!(" as {alias}")) ) } Self::Max { field, alias } => { format!( "max({}){}", field .to_sql(table_engine) .attach_printable("Failed to max aggregate")?, alias.map_or_else(|| "".to_owned(), |alias| format!(" as {alias}")) ) } Self::Percentile { field, alias, percentile, } => { format!( "percentile_cont(0.{}) within group (order by {} asc){}", percentile.map_or_else(|| "50".to_owned(), |percentile| percentile.to_string()), field .to_sql(table_engine) .attach_printable("Failed to percentile aggregate")?, alias.map_or_else(|| "".to_owned(), |alias| format!(" as {alias}")) ) } Self::DistinctCount { field, alias } => { format!( "count(distinct {}){}", field .to_sql(table_engine) .attach_printable("Failed to distinct count aggregate")?, alias.map_or_else(|| "".to_owned(), |alias| format!(" as {alias}")) ) } }) } } impl<T> ToSql<SqlxClient> for Window<T> where T: ToSql<SqlxClient>, { fn to_sql(&self, table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { Ok(match self { Self::Sum { field, partition_by, order_by, alias, } => { format!( "sum({}) over ({}{}){}", field .to_sql(table_engine) .attach_printable("Failed to sum window")?, partition_by.as_ref().map_or_else( || "".to_owned(), |partition_by| format!("partition by {}", partition_by.to_owned()) ), order_by.as_ref().map_or_else( || "".to_owned(), |(order_column, order)| format!( " order by {} {}", order_column.to_owned(), order ) ), alias.map_or_else(|| "".to_owned(), |alias| format!(" as {alias}")) ) } Self::RowNumber { field: _, partition_by, order_by, alias, } => { format!( "row_number() over ({}{}){}", partition_by.as_ref().map_or_else( || "".to_owned(), |partition_by| format!("partition by {}", partition_by.to_owned()) ), order_by.as_ref().map_or_else( || "".to_owned(), |(order_column, order)| format!( " order by {} {}", order_column.to_owned(), order ) ), alias.map_or_else(|| "".to_owned(), |alias| format!(" as {alias}")) ) } }) } }
crates__api_models__src__admin.rs
"use std::collections::{HashMap, HashSet};\n\nuse common_types::primitive_wrappers;\nuse common_util(...TRUNCATED)
crates__api_models__src__analytics.rs
"use std::collections::HashSet;\n\npub use common_utils::types::TimeRange;\nuse common_utils::{event(...TRUNCATED)
crates__api_models__src__events__payment.rs
"use common_utils::events::{ApiEventMetric, ApiEventsType};\n\n#[cfg(feature = \"v2\")]\nuse super::(...TRUNCATED)
crates__api_models__src__events__routing.rs
"use common_utils::events::{ApiEventMetric, ApiEventsType};\n\nuse crate::routing::{\n ContractBa(...TRUNCATED)
crates__api_models__src__payment_methods.rs
"use std::collections::{HashMap, HashSet};\n#[cfg(feature = \"v2\")]\nuse std::str::FromStr;\n\nuse (...TRUNCATED)
crates__api_models__src__payouts.rs
"use std::collections::HashMap;\n\nuse cards::CardNumber;\nuse common_enums::CardNetwork;\n#[cfg(fea(...TRUNCATED)
crates__api_models__src__routing.rs
"use std::{fmt::Debug, ops::Deref};\n\nuse common_types::three_ds_decision_rule_engine::{ThreeDSDeci(...TRUNCATED)
crates__api_models__src__subscription.rs
"use common_enums::{InvoiceStatus, SubscriptionStatus};\nuse common_types::payments::CustomerAccepta(...TRUNCATED)
End of preview. Expand in Data Studio

archit11/hyperswitch-code-corpus-track-a

Repository-specific code corpus extracted from hyperswitch and split by file for training/evaluation.

What is in this dataset

  • Source corpus: data/code_corpus_hyperswitch
  • Total files: 300
  • Train files: 270
  • Validation files: 30
  • Test files: 0
  • File type filter: .rs
  • Split mode: file (file-level holdout)

Each row has:

  • file_name: flattened source file name
  • text: full file contents

Training context

This dataset was used for extended pretraining of:

  • Model repo: https://huggingface.co/archit11/qwen2.5-coder-3b-hyperswitch-track-a-lora
  • Base model: /root/.cache/huggingface/hub/models--Qwen--Qwen2.5-Coder-3B/snapshots/09d9bc5d376b0cfa0100a0694ea7de7232525803
  • Sequence curriculum: [768, 1024, 1536]
  • Learning rate: 0.001
  • Batch size: 1

Evaluation from this run: ( from held out dataset )

  • Baseline perplexity: 2.2832

  • Post-training perplexity: 1.5429

    Filtering

    • Source repo restricted to crates/ Rust files only (.rs) in data_preparation.py:48 and data_preparation.py:44.
    • Hard path exclusions for noisy dirs like tests, docs, examples, migrations, scripts, etc. in data_preparation.py:49.
    • Dropped empty/generated files (generated by, auto-generated, do not edit, etc.) in data_preparation.py:97 and data_preparation.py:149.
    • Kept files only if line count in [25, 4000] (data_preparation.py:45, data_preparation.py:46, data_preparation.py:195).
    • Kept only structurally rich files (functions + types >= 2) in data_preparation.py:205.
    • Ranked by a quality score and kept top 300 files (data_preparation.py:47, data_preparation.py:209, data_preparation.py:229).
    • Actual corpus stats: 300 files, 370,212 lines in data/ corpus_metadata_hyperswitch.json.

    Split

    • For this run (results/track_a_hyperswitch_metrics_lr1e3_curr.json): 270 train files, 30 validation files, effectively no test set recorded.
    • Current script does file split after random.shuffle(all_files) (track_a_pretraining.py:361, track_a_pretraining.py:377).

    Chunking

    • no ast based chuking yet since the compute constrains and would be hard to make it work since sequence len is limited
    • Files are concatenated per split with a // FILE: header (track_a_pretraining.py:157).
    • Tokenization uses add_special_tokens=False; chunks are fixed-size, non- overlapping windows (stride = block size) in track_a_pretraining.py:176.
    • Curriculum for this run: 768 -> 1024 -> 1536 (results/ track_a_hyperswitch_metrics_lr1e3_curr.json).
    • Validation chunks were capped to 160 (seen in run metrics), via random subset trimming logic in track_a_pretraining.py:196.

    Perplexity eval

    • PPL is computed from average token-level CE loss over eval chunks (track_a_pretraining.py:267).
    • This run reported 2.2832 -> 1.5429 (baseline -> post).

Load with datasets

from datasets import load_dataset

ds = load_dataset("archit11/hyperswitch-code-corpus-track-a")
print(ds)
print(ds["train"][0]["file_name"])
Downloads last month
23