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(core): add framework for domains id listing (#13684)

Shivansh Mathurf08a1e9c4ec7
diff --git a/.clippy.toml b/.clippy.toml
index b8043f976f..88530b7fb7 100644
--- a/.clippy.toml
+++ b/.clippy.toml
@@ -3,3 +3,7 @@ allow-expect-in-tests = true
allow-panic-in-tests = true
allow-print-in-tests = true
allow-unwrap-in-tests = true
+
+disallowed-methods = [
+ { path = "diesel::query_dsl::QueryDsl::into_boxed", reason = "dynamic list queries must be built via diesel_models::list::boxed_list_query! or diesel_models::list::into_boxed_list" },
+]
diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.json
index 42c6cbe871..6154ac653e 100644
--- a/api-reference/v1/openapi_spec_v1.json
+++ b/api-reference/v1/openapi_spec_v1.json
@@ -29985,12 +29985,7 @@
"nullable": true
},
"limit": {
- "type": "integer",
- "format": "int32",
- "description": "limit on the number of objects to return",
- "default": 10,
- "maximum": 100,
- "minimum": 0
+ "$ref": "#/components/schemas/common_utils.types.list.PageSize"
},
"created": {
"type": "string",
@@ -37240,12 +37235,7 @@
"nullable": true
},
"limit": {
- "type": "integer",
- "format": "int32",
- "description": "limit on the number of objects to return",
- "default": 10,
- "maximum": 100,
- "minimum": 0
+ "$ref": "#/components/schemas/common_utils.types.list.PageSize"
},
"created": {
"type": "string",
@@ -37302,17 +37292,10 @@
"nullable": true
},
"limit": {
- "type": "integer",
- "format": "int32",
- "description": "The limit on the number of objects. The default limit is 10 and max limit is 20",
- "minimum": 0
+ "$ref": "#/components/schemas/common_utils.types.list.PageSize"
},
"offset": {
- "type": "integer",
- "format": "int32",
- "description": "The starting point within a list of objects",
- "nullable": true,
- "minimum": 0
+ "$ref": "#/components/schemas/common_utils.types.list.PageOffset"
},
"connector": {
"type": "array",
@@ -40744,16 +40727,15 @@
"nullable": true
},
"limit": {
- "type": "integer",
- "format": "int64",
- "description": "Limit on the number of objects to return",
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/common_utils.types.list.PageSize"
+ }
+ ],
"nullable": true
},
"offset": {
- "type": "integer",
- "format": "int64",
- "description": "The starting point within a list of objects",
- "nullable": true
+ "$ref": "#/components/schemas/common_utils.types.list.PageOffset"
},
"amount_filter": {
"allOf": [
@@ -47211,6 +47193,18 @@
}
},
"additionalProperties": false
+ },
+ "common_utils.types.list.PageOffset": {
+ "type": "integer",
+ "format": "int32",
+ "maximum": 20000,
+ "minimum": 0
+ },
+ "common_utils.types.list.PageSize": {
+ "type": "integer",
+ "format": "int32",
+ "maximum": 100,
+ "minimum": 1
}
},
"securitySchemes": {
diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json
index 79eeaf3466..b36afd2259 100644
--- a/api-reference/v2/openapi_spec_v2.json
+++ b/api-reference/v2/openapi_spec_v2.json
@@ -2708,11 +2708,7 @@
"description": "limit on the number of objects to return",
"required": true,
"schema": {
- "type": "integer",
- "format": "int32",
- "default": 10,
- "maximum": 100,
- "minimum": 0
+ "$ref": "#/components/schemas/common_utils.types.list.PageSize"
}
},
{
@@ -2721,10 +2717,7 @@
"description": "The starting point within a list of objects",
"required": true,
"schema": {
- "type": "integer",
- "format": "int32",
- "nullable": true,
- "minimum": 0
+ "$ref": "#/components/schemas/common_utils.types.list.PageOffset"
}
},
{
@@ -26337,12 +26330,7 @@
"nullable": true
},
"limit": {
- "type": "integer",
- "format": "int32",
- "description": "limit on the number of objects to return",
- "default": 10,
- "maximum": 100,
- "minimum": 0
+ "$ref": "#/components/schemas/common_utils.types.list.PageSize"
},
"created": {
"type": "string",
@@ -26399,17 +26387,10 @@
"nullable": true
},
"limit": {
- "type": "integer",
- "format": "int32",
- "description": "The limit on the number of objects. The default limit is 10 and max limit is 20",
- "minimum": 0
+ "$ref": "#/components/schemas/common_utils.types.list.PageSize"
},
"offset": {
- "type": "integer",
- "format": "int32",
- "description": "The starting point within a list of objects",
- "nullable": true,
- "minimum": 0
+ "$ref": "#/components/schemas/common_utils.types.list.PageOffset"
},
"connector": {
"type": "array",
@@ -29083,16 +29064,10 @@
"description": "The identifier for the refund"
},
"limit": {
- "type": "integer",
- "format": "int64",
- "description": "Limit on the number of objects to return",
- "nullable": true
+ "$ref": "#/components/schemas/common_utils.types.list.PageSize"
},
"offset": {
- "type": "integer",
- "format": "int64",
- "description": "The starting point within a list of objects",
- "nullable": true
+ "$ref": "#/components/schemas/common_utils.types.list.PageOffset"
},
"amount_filter": {
"allOf": [
@@ -34331,6 +34306,18 @@
}
},
"additionalProperties": false
+ },
+ "common_utils.types.list.PageOffset": {
+ "type": "integer",
+ "format": "int32",
+ "maximum": 20000,
+ "minimum": 0
+ },
+ "common_utils.types.list.PageSize": {
+ "type": "integer",
+ "format": "int32",
+ "maximum": 100,
+ "minimum": 1
}
},
"securitySchemes": {
diff --git a/crates/api_models/src/disputes.rs b/crates/api_models/src/disputes.rs
index 6ce1f2a713..023b53bd76 100644
--- a/crates/api_models/src/disputes.rs
+++ b/crates/api_models/src/disputes.rs
@@ -137,9 +137,11 @@ pub struct DisputeListGetConstraints {
/// The payment_id against which dispute is raised
pub payment_id: Option<common_utils::id_type::PaymentId>,
/// Limit on the number of objects to return
- pub limit: Option<u32>,
+ #[serde(default)]
+ pub limit: common_utils::types::list::PageSize,
/// The starting point within a list of object
- pub offset: Option<u32>,
+ #[serde(default)]
+ pub offset: common_utils::types::list::PageOffset,
/// The identifier for business profile
#[schema(value_type = Option<String>)]
pub profile_id: Option<common_utils::id_type::ProfileId>,
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 13732bc493..c9f2e9833c 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -18,7 +18,7 @@ use common_types::{
customers::DocumentKind, payments as common_payments_types, primitive_wrappers,
};
use common_utils::{
- consts::{default_payments_list_limit, DISCOUNT_PERCENTAGE_PRECISION_LENGTH},
+ consts::DISCOUNT_PERCENTAGE_PRECISION_LENGTH,
crypto,
errors::ValidationError,
ext_traits::{ConfigExt, Encode, ValueExt},
@@ -8881,9 +8881,8 @@ pub struct PaymentListConstraints {
pub ending_before: Option<id_type::PaymentId>,
/// limit on the number of objects to return
- #[schema(default = 10, maximum = 100)]
- #[serde(default = "default_payments_list_limit")]
- pub limit: u32,
+ #[serde(default)]
+ pub limit: common_utils::types::list::PageSize,
/// The time at which payment is created
#[schema(example = "2022-09-10T10:11:12Z")]
@@ -8954,12 +8953,12 @@ pub struct PaymentListConstraints {
pub ending_before: Option<id_type::GlobalPaymentId>,
/// limit on the number of objects to return
- #[param(default = 10, maximum = 100)]
- #[serde(default = "default_payments_list_limit")]
- pub limit: u32,
+ #[serde(default)]
+ pub limit: common_utils::types::list::PageSize,
/// The starting point within a list of objects
- pub offset: Option<u32>,
+ #[serde(default)]
+ pub offset: common_utils::types::list::PageOffset,
/// The time at which payment is created
#[param(example = "2022-09-10T10:11:12Z")]
@@ -9136,10 +9135,11 @@ pub struct PaymentListFilterConstraints {
/// The identifier for customer
pub customer_id: Option<id_type::CustomerId>,
/// The limit on the number of objects. The default limit is 10 and max limit is 20
- #[serde(default = "default_payments_list_limit")]
- pub limit: u32,
+ #[serde(default)]
+ pub limit: common_utils::types::list::PageSize,
/// The starting point within a list of objects
- pub offset: Option<u32>,
+ #[serde(default)]
+ pub offset: common_utils::types::list::PageOffset,
/// The amount to filter payments list
pub amount_filter: Option<AmountFilter>,
/// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc).
diff --git a/crates/api_models/src/payouts.rs b/crates/api_models/src/payouts.rs
index b2bab60dfd..1edc7a6109 100644
--- a/crates/api_models/src/payouts.rs
+++ b/crates/api_models/src/payouts.rs
@@ -6,7 +6,6 @@ use common_types::payouts::PayoutsBillingDescriptor;
#[cfg(feature = "v2")]
use common_utils::types::BrowserInformation;
use common_utils::{
- consts::default_payouts_list_limit,
crypto,
errors::ValidationError,
id_type, link_utils, payout_method_utils,
@@ -1122,9 +1121,8 @@ pub struct PayoutListConstraints {
pub ending_before: Option<id_type::PayoutId>,
/// limit on the number of objects to return
- #[schema(default = 10, maximum = 100)]
- #[serde(default = "default_payouts_list_limit")]
- pub limit: u32,
+ #[serde(default)]
+ pub limit: common_utils::types::list::PageSize,
/// The time at which payout is created
#[schema(example = "2022-09-10T10:11:12Z")]
@@ -1157,11 +1155,12 @@ pub struct PayoutListFilterConstraints {
/// The identifier for customer
#[schema(value_type = Option<String>,example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")]
pub customer_id: Option<id_type::CustomerId>,
- /// The limit on the number of objects. The default limit is 10 and max limit is 20
- #[serde(default = "default_payouts_list_limit")]
- pub limit: u32,
+ /// The limit on the number of objects to return
+ #[serde(default)]
+ pub limit: common_utils::types::list::PageSize,
/// The starting point within a list of objects
- pub offset: Option<u32>,
+ #[serde(default)]
+ pub offset: common_utils::types::list::PageOffset,
/// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc).
#[serde(flatten)]
#[schema(value_type = Option<TimeRange>)]
diff --git a/crates/api_models/src/refunds.rs b/crates/api_models/src/refunds.rs
index 704ff82058..8697512a47 100644
--- a/crates/api_models/src/refunds.rs
+++ b/crates/api_models/src/refunds.rs
@@ -449,11 +449,13 @@ pub struct RefundListRequest {
#[smithy(value_type = "Option<String>")]
pub profile_id: Option<common_utils::id_type::ProfileId>,
/// Limit on the number of objects to return
- #[smithy(value_type = "Option<i64>")]
- pub limit: Option<i64>,
+ #[serde(default)]
+ #[smithy(value_type = "Option<u32>")]
+ pub limit: Option<common_utils::types::list::PageSize>,
/// The starting point within a list of objects
- #[smithy(value_type = "Option<i64>")]
- pub offset: Option<i64>,
+ #[serde(default)]
+ #[smithy(value_type = "Option<u32>")]
+ pub offset: common_utils::types::list::PageOffset,
/// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc)
#[serde(flatten)]
pub time_range: Option<TimeRange>,
@@ -486,9 +488,11 @@ pub struct RefundListRequest {
#[schema(value_type = String)]
pub refund_id: Option<common_utils::id_type::GlobalRefundId>,
/// Limit on the number of objects to return
- pub limit: Option<i64>,
+ #[serde(default)]
+ pub limit: common_utils::types::list::PageSize,
/// The starting point within a list of objects
- pub offset: Option<i64>,
+ #[serde(default)]
+ pub offset: common_utils::types::list::PageOffset,
/// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc)
#[serde(flatten)]
pub time_range: Option<TimeRange>,
diff --git a/crates/api_models/src/user/dashboard_metadata.rs b/crates/api_models/src/user/dashboard_metadata.rs
index b77d7b8ef1..e425727831 100644
--- a/crates/api_models/src/user/dashboard_metadata.rs
+++ b/crates/api_models/src/user/dashboard_metadata.rs
@@ -223,9 +223,10 @@ pub struct PaymentListFilterConstraintsV1 {
pub payment_id: Option<id_type::PaymentId>,
pub profile_id: Option<id_type::ProfileId>,
pub customer_id: Option<id_type::CustomerId>,
- #[serde(default = "common_utils::consts::default_payments_list_limit")]
- pub limit: u32,
- pub offset: Option<u32>,
+ #[serde(default)]
+ pub limit: common_utils::types::list::PageSize,
+ #[serde(default)]
+ pub offset: Option<common_utils::types::list::PageOffset>,
pub amount_filter: Option<payments::AmountFilter>,
#[serde(flatten)]
pub time_range: Option<common_utils::types::TimeRange>,
@@ -323,9 +324,10 @@ pub struct PaymentAdvancedViewFilterConstraints {
pub payment_id: Option<id_type::PaymentId>,
pub profile_id: Option<id_type::ProfileId>,
pub customer_id: Option<id_type::CustomerId>,
- #[serde(default = "common_utils::consts::default_payments_list_limit")]
- pub limit: u32,
- pub offset: Option<u32>,
+ #[serde(default)]
+ pub limit: common_utils::types::list::PageSize,
+ #[serde(default)]
+ pub offset: Option<common_utils::types::list::PageOffset>,
pub amount_filter: Option<payments::AmountFilter>,
#[serde(flatten)]
pub time_range: Option<common_utils::types::TimeRange>,
diff --git a/crates/common_utils/src/consts.rs b/crates/common_utils/src/consts.rs
index f803a2ed65..df65bfcd9f 100644
--- a/crates/common_utils/src/consts.rs
+++ b/crates/common_utils/src/consts.rs
@@ -22,6 +22,13 @@ pub static FRM_CONFIGS_EG: &str = r#"
[{"gateway":"stripe","payment_methods":[{"payment_method":"card","payment_method_types":[{"payment_method_type":"credit","card_networks":["Visa"],"flow":"pre","action":"cancel_txn"},{"payment_method_type":"debit","card_networks":["Visa"],"flow":"pre"}]}]}]
"#;
+/// Global minimum limit for any list API.
+pub const LIST_MIN_LIMIT: u32 = 1;
+/// Global maximum limit for any list API (single cap across endpoints).
+pub const LIST_MAX_LIMIT: u32 = 100;
+/// Global default limit for any list API when the caller omits it.
+pub const LIST_DEFAULT_LIMIT: u32 = 10;
+
/// Maximum limit for payments list get api
pub const PAYMENTS_LIST_MAX_LIMIT_V1: u32 = 100;
/// Maximum limit for payments list post api with filters
@@ -46,6 +53,16 @@ pub fn default_payouts_list_limit() -> u32 {
10
}
+/// Default limit for refunds list API
+pub const REFUNDS_LIST_DEFAULT_LIMIT: u32 = 10;
+/// Maximum limit for refunds list API
+pub const REFUNDS_LIST_MAX_LIMIT: u32 = 100;
+
+/// Default limit for disputes list API
+pub const DISPUTES_LIST_DEFAULT_LIMIT: u32 = 10;
+/// Maximum limit for disputes list API
+pub const DISPUTES_LIST_MAX_LIMIT: u32 = 100;
+
/// surcharge percentage maximum precision length
pub const SURCHARGE_PERCENTAGE_PRECISION_LENGTH: u8 = 2;
diff --git a/crates/common_utils/src/types.rs b/crates/common_utils/src/types.rs
index e069d10567..f83f86e65d 100644
--- a/crates/common_utils/src/types.rs
+++ b/crates/common_utils/src/types.rs
@@ -9,6 +9,9 @@ pub mod user;
/// types that are wrappers around primitive types
pub mod primitive_wrappers;
+/// List-query pagination and sorting types
+pub mod list;
+
use std::{
borrow::Cow,
fmt::Display,
diff --git a/crates/common_utils/src/types/list.rs b/crates/common_utils/src/types/list.rs
new file mode 100644
index 0000000000..db9fee9118
--- /dev/null
+++ b/crates/common_utils/src/types/list.rs
@@ -0,0 +1,208 @@
+//! List-query pagination and sorting types.
+
+use serde::{Deserialize, Serialize, Serializer};
+
+use crate::consts::{LIST_DEFAULT_LIMIT, LIST_MAX_LIMIT, LIST_MIN_LIMIT};
+
+/// A page size, validated against the global list bounds (`1..=LIST_MAX_LIMIT`).
+/// Deserialization rejects an out-of-range limit, so the caller gets an error rather
+/// than silently receiving fewer (or zero) rows.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)]
+#[serde(try_from = "u64")]
+pub struct PageSize(u32);
+
+/// Error returned by [`PageSize::new`] / [`PageOffset::new`] when an out-of-range
+/// value is supplied.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
+pub enum PaginationError {
+ /// `limit` was zero or greater than the allowed maximum.
+ #[error("list limit {got} is invalid, it must be between 1 and {max}")]
+ InvalidLimit {
+ /// The value the caller passed.
+ got: u32,
+ /// The maximum allowed value.
+ max: u32,
+ },
+ /// `offset` was greater than the allowed maximum.
+ #[error("list offset {got} is invalid, it must be at most {max}")]
+ InvalidOffset {
+ /// The value the caller passed.
+ got: u32,
+ /// The maximum allowed value.
+ max: u32,
+ },
+}
+
+impl PageSize {
+ /// Construct a validated page size, rejecting out-of-range values.
+ pub fn new(value: u32) -> Result<Self, PaginationError> {
+ if !(LIST_MIN_LIMIT..=LIST_MAX_LIMIT).contains(&value) {
+ return Err(PaginationError::InvalidLimit {
+ got: value,
+ max: LIST_MAX_LIMIT,
+ });
+ }
+ Ok(Self(value))
+ }
+
+ /// The resolved limit as `i64`, ready for Diesel's `.limit()`.
+ pub fn as_i64(self) -> i64 {
+ i64::from(self.0)
+ }
+
+ /// The resolved limit as `usize` (for in-memory slicing).
+ pub fn as_usize(self) -> usize {
+ usize::try_from(self.0).unwrap_or(usize::MAX)
+ }
+
+ /// The raw limit as `u32`.
+ pub fn as_u32(self) -> u32 {
+ self.0
+ }
+}
+
+impl Default for PageSize {
+ fn default() -> Self {
+ Self(LIST_DEFAULT_LIMIT)
+ }
+}
+
+impl Serialize for PageSize {
+ fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
+ serializer.serialize_u32(self.0)
+ }
+}
+
+// Internal compat conversion: clamps rather than fails. Used by stripe compatibility
+// and other non-HTTP paths that hold a resolved `u32`.
+impl From<u32> for PageSize {
+ fn from(value: u32) -> Self {
+ Self(value.clamp(LIST_MIN_LIMIT, LIST_MAX_LIMIT))
+ }
+}
+
+// Validation hook for `#[serde(try_from = "u64")]`. Rejects out-of-range values from
+// the request path; the `u64` intermediary avoids a blanket-impl collision between
+// `From<u32>` and `TryFrom<u32>`.
+impl TryFrom<u64> for PageSize {
+ type Error = PaginationError;
+
+ fn try_from(value: u64) -> Result<Self, Self::Error> {
+ let value = u32::try_from(value).map_err(|_| PaginationError::InvalidLimit {
+ got: u32::MAX,
+ max: LIST_MAX_LIMIT,
+ })?;
+ Self::new(value)
+ }
+}
+
+// Manual `ToSchema`: the derive would emit `array` for a newtype tuple struct, and we
+// need a custom component key + integer bounds matching `Deserialize` validation.
+impl<'a> utoipa::ToSchema<'a> for PageSize {
+ fn schema() -> (
+ &'a str,
+ utoipa::openapi::RefOr<utoipa::openapi::schema::Schema>,
+ ) {
+ use utoipa::openapi::{KnownFormat, ObjectBuilder, SchemaFormat, SchemaType};
+ (
+ // Use the full dotted path so the component key matches the `$ref` that
+ // utoipa's derive macro generates for fields of this type.
+ "common_utils.types.list.PageSize",
+ ObjectBuilder::new()
+ .schema_type(SchemaType::Integer)
+ .format(Some(SchemaFormat::KnownFormat(KnownFormat::Int32)))
+ .minimum(Some(f64::from(LIST_MIN_LIMIT)))
+ .maximum(Some(f64::from(LIST_MAX_LIMIT)))
+ .into(),
+ )
+ }
+}
+
+/// A page offset, capped so a caller can't skip a huge number of rows.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize)]
+#[serde(try_from = "u64")]
+pub struct PageOffset(u32);
+
+impl PageOffset {
+ const MAX: u32 = 20_000;
+
+ /// Construct a validated page offset, rejecting values above [`Self::MAX`].
+ pub fn new(value: u32) -> Result<Self, PaginationError> {
+ if value > Self::MAX {
+ return Err(PaginationError::InvalidOffset {
+ got: value,
+ max: Self::MAX,
+ });
+ }
+ Ok(Self(value))
+ }
+
+ /// The capped offset as `i64`, ready for Diesel's `.offset()`.
+ pub fn as_i64(self) -> i64 {
+ i64::from(self.0)
+ }
+
+ /// The capped offset as `usize` (for in-memory skipping).
+ pub fn as_usize(self) -> usize {
+ usize::try_from(self.0).unwrap_or(usize::MAX)
+ }
+}
+
+impl Serialize for PageOffset {
+ fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
+ serializer.serialize_u32(self.0)
+ }
+}
+
+// Internal compat conversion: clamps rather than fails.
+impl From<u32> for PageOffset {
+ fn from(value: u32) -> Self {
+ Self(value.min(Self::MAX))
+ }
+}
+
+// Validation hook for `#[serde(try_from = "u64")]`. Rejects values above MAX from
+// the request path; the `u64` intermediary avoids a blanket-impl collision between
+// `From<u32>` and `TryFrom<u32>`.
+impl TryFrom<u64> for PageOffset {
+ type Error = PaginationError;
+
+ fn try_from(value: u64) -> Result<Self, Self::Error> {
+ let value = u32::try_from(value).map_err(|_| PaginationError::InvalidOffset {
+ got: u32::MAX,
+ max: Self::MAX,
+ })?;
+ Self::new(value)
+ }
+}
+
+// Manual `ToSchema` for the same reasons as `PageSize` above.
+impl<'a> utoipa::ToSchema<'a> for PageOffset {
+ fn schema() -> (
+ &'a str,
+ utoipa::openapi::RefOr<utoipa::openapi::schema::Schema>,
+ ) {
+ use utoipa::openapi::{KnownFormat, ObjectBuilder, SchemaFormat, SchemaType};
+ (
+ // Use the full dotted path so the component key matches the `$ref` that
+ // utoipa's derive macro generates for fields of this type.
+ "common_utils.types.list.PageOffset",
+ ObjectBuilder::new()
+ .schema_type(SchemaType::Integer)
+ .format(Some(SchemaFormat::KnownFormat(KnownFormat::Int32)))
+ .minimum(Some(0.0))
+ .maximum(Some(f64::from(Self::MAX)))
+ .into(),
+ )
+ }
+}
+
+/// Sort direction. The column is chosen by the caller, not hardcoded here.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub enum SortDirection {
+ #[default]
+ /// Newest-first (descending).
+ Desc,
+ /// Oldest-first (ascending).
+ Asc,
+}
diff --git a/crates/diesel_models/src/lib.rs b/crates/diesel_models/src/lib.rs
index fdce2ec142..7fdad48261 100644
--- a/crates/diesel_models/src/lib.rs
+++ b/crates/diesel_models/src/lib.rs
@@ -29,6 +29,7 @@ pub mod hyperswitch_ai_interaction;
pub mod invoice;
#[cfg(feature = "kv_store")]
pub mod kv;
+pub mod list;
pub mod locker_mock_up;
pub mod mandate;
pub mod merchant_account;
diff --git a/crates/diesel_models/src/list.rs b/crates/diesel_models/src/list.rs
new file mode 100644
index 0000000000..238cbb8a83
--- /dev/null
+++ b/crates/diesel_models/src/list.rs
@@ -0,0 +1,38 @@
+//! Shared list-query helpers: pagination, boxing, and the `boxed_list_query!` macro.
+
+pub use common_utils::types::list::{PageOffset, PageSize, SortDirection};
+use diesel::query_dsl::methods::{BoxedDsl, LimitDsl, OffsetDsl};
+
+/// Apply page size and offset to a boxed list query.
+pub fn apply_pagination<Q>(query: Q, page_size: PageSize, offset: PageOffset) -> Q
+where
+ Q: LimitDsl<Output = Q> + OffsetDsl<Output = Q>,
+{
+ query.limit(page_size.as_i64()).offset(offset.as_i64())
+}
+
+/// The only sanctioned `.into_boxed()` call; the `#[allow]` here means
+/// `boxed_list_query!` callers don't need their own.
+#[allow(clippy::disallowed_methods)]
+pub fn into_boxed_list<'a, Q>(query: Q) -> <Q as BoxedDsl<'a, diesel::pg::Pg>>::Output
+where
+ Q: BoxedDsl<'a, diesel::pg::Pg>,
+{
+ query.internal_into_boxed()
+}
+
+/// Base of a list query: merchant `scope` + caller-chosen `order`, boxed.
+#[macro_export]
+macro_rules! boxed_list_query {
+ (
+ $table:path,
+ scope = $scope:expr,
+ order = $order:expr
+ ) => {{
+ $crate::list::into_boxed_list(
+ <$table as diesel::associations::HasTable>::table()
+ .filter($scope)
+ .order($order),
+ )
+ }};
+}
diff --git a/crates/diesel_models/src/query/events.rs b/crates/diesel_models/src/query/events.rs
index 60ef9865c7..91ded0bd29 100644
--- a/crates/diesel_models/src/query/events.rs
+++ b/crates/diesel_models/src/query/events.rs
@@ -90,16 +90,17 @@ impl Event {
primary_object_id: &str,
event_recipient: Option<common_enums::EventRecipient>,
) -> StorageResult<Vec<Self>> {
- let mut query = Self::table()
- .filter(
- dsl::event_id
- .nullable()
- .eq(dsl::initial_attempt_id) // Filter initial attempts only
- .and(dsl::merchant_id.eq(merchant_id.to_owned()))
- .and(dsl::primary_object_id.eq(primary_object_id.to_owned())),
- )
- .order(dsl::created_at.desc())
- .into_boxed();
+ let mut query = crate::list::into_boxed_list(
+ Self::table()
+ .filter(
+ dsl::event_id
+ .nullable()
+ .eq(dsl::initial_attempt_id) // Filter initial attempts only
+ .and(dsl::merchant_id.eq(merchant_id.to_owned()))
+ .and(dsl::primary_object_id.eq(primary_object_id.to_owned())),
+ )
+ .order(dsl::created_at.desc()),
+ );
query = Self::apply_event_recipient(query, event_recipient);
@@ -144,15 +145,16 @@ impl Event {
is_delivered: Option<bool>,
event_recipient: Option<common_enums::EventRecipient>,
) -> StorageResult<Vec<Self>> {
- let mut query = Self::table()
- .filter(
- dsl::event_id
- .nullable()
- .eq(dsl::initial_attempt_id) // Filter initial attempts only
- .and(dsl::merchant_id.eq(merchant_id.to_owned())),
- )
- .order(dsl::created_at.desc())
- .into_boxed();
+ let mut query = crate::list::into_boxed_list(
+ Self::table()
+ .filter(
+ dsl::event_id
+ .nullable()
+ .eq(dsl::initial_attempt_id) // Filter initial attempts only
+ .and(dsl::merchant_id.eq(merchant_id.to_owned())),
+ )
+ .order(dsl::created_at.desc()),
+ );
query = Self::apply_filters(
query,
@@ -179,14 +181,15 @@ impl Event {
initial_attempt_id: &str,
event_recipient: Option<common_enums::EventRecipient>,
) -> StorageResult<Vec<Self>> {
- let mut query = Self::table()
- .filter(
- dsl::merchant_id
- .eq(merchant_id.to_owned())
- .and(dsl::initial_attempt_id.eq(initial_attempt_id.to_owned())),
- )
- .order(dsl::created_at.desc())
- .into_boxed();
+ let mut query = crate::list::into_boxed_list(
+ Self::table()
+ .filter(
+ dsl::merchant_id
+ .eq(merchant_id.to_owned())
+ .and(dsl::initial_attempt_id.eq(initial_attempt_id.to_owned())),
+ )
+ .order(dsl::created_at.desc()),
+ );
query = Self::apply_event_recipient(query, event_recipient);
@@ -209,22 +212,23 @@ impl Event {
// handle events created during staggered rollout by older code. This
// fallback is correct for standard merchants where merchant_id equals
// the webhook recipient.
- let mut query = Self::table()
- .filter(
- dsl::event_id
- .nullable()
- .eq(dsl::initial_attempt_id) // Filter initial attempts only
- .and(
- dsl::initiator_merchant_id
- .eq(initiator_merchant_id.to_owned())
- .or(dsl::initiator_merchant_id
- .is_null()
- .and(dsl::merchant_id.eq(initiator_merchant_id.to_owned()))),
- )
- .and(dsl::primary_object_id.eq(primary_object_id.to_owned())),
- )
- .order(dsl::created_at.desc())
- .into_boxed();
+ let mut query = crate::list::into_boxed_list(
+ Self::table()
+ .filter(
+ dsl::event_id
+ .nullable()
+ .eq(dsl::initial_attempt_id) // Filter initial attempts only
+ .and(
+ dsl::initiator_merchant_id
+ .eq(initiator_merchant_id.to_owned())
+ .or(dsl::initiator_merchant_id
+ .is_null()
+ .and(dsl::merchant_id.eq(initiator_merchant_id.to_owned()))),
+ )
+ .and(dsl::primary_object_id.eq(primary_object_id.to_owned())),
+ )
+ .order(dsl::created_at.desc()),
+ );
query = Self::apply_event_recipient(query, recipient);
@@ -258,21 +262,22 @@ impl Event {
// handle events created during staggered rollout by older code. This
// fallback is correct for standard merchants where merchant_id equals
// the webhook recipient.
- let mut query = Self::table()
- .filter(
- dsl::event_id
- .nullable()
- .eq(dsl::initial_attempt_id) // Filter initial attempts only
- .and(
- dsl::initiator_merchant_id
- .eq(initiator_merchant_id.to_owned())
- .or(dsl::initiator_merchant_id
- .is_null()
- .and(dsl::merchant_id.eq(initiator_merchant_id.to_owned()))),
- ),
- )
- .order(dsl::created_at.desc())
- .into_boxed();
+ let mut query = crate::list::into_boxed_list(
+ Self::table()
+ .filter(
+ dsl::event_id
+ .nullable()
+ .eq(dsl::initial_attempt_id) // Filter initial attempts only
+ .and(
+ dsl::initiator_merchant_id
+ .eq(initiator_merchant_id.to_owned())
+ .or(dsl::initiator_merchant_id
+ .is_null()
+ .and(dsl::merchant_id.eq(initiator_merchant_id.to_owned()))),
+ ),
+ )
+ .order(dsl::created_at.desc()),
+ );
query = Self::apply_filters(
query,
@@ -302,20 +307,21 @@ impl Event {
// Fallback on merchant_id for rows with NULL initiator_merchant_id to
// handle events created during staggered rollout by older code.
- let mut query = Self::table()
- .filter(
- dsl::initial_attempt_id
- .eq(initial_attempt_id.to_owned())
- .and(
- dsl::initiator_merchant_id
- .eq(initiator_merchant_id.to_owned())
- .or(dsl::initiator_merchant_id
- .is_null()
- .and(dsl::merchant_id.eq(initiator_merchant_id.to_owned()))),
- ),
- )
- .order(dsl::created_at.desc())
- .into_boxed();
+ let mut query = crate::list::into_boxed_list(
+ Self::table()
+ .filter(
+ dsl::initial_attempt_id
+ .eq(initial_attempt_id.to_owned())
+ .and(
+ dsl::initiator_merchant_id
+ .eq(initiator_merchant_id.to_owned())
+ .or(dsl::initiator_merchant_id
+ .is_null()
+ .and(dsl::merchant_id.eq(initiator_merchant_id.to_owned()))),
+ ),
+ )
+ .order(dsl::created_at.desc()),
+ );
query = Self::apply_event_recipient(query, event_recipient);
@@ -333,16 +339,17 @@ impl Event {
primary_object_id: &str,
event_recipient: Option<common_enums::EventRecipient>,
) -> StorageResult<Vec<Self>> {
- let mut query = Self::table()
- .filter(
- dsl::event_id
- .nullable()
- .eq(dsl::initial_attempt_id) // Filter initial attempts only
- .and(dsl::business_profile_id.eq(profile_id.to_owned()))
- .and(dsl::primary_object_id.eq(primary_object_id.to_owned())),
- )
- .order(dsl::created_at.desc())
- .into_boxed();
+ let mut query = crate::list::into_boxed_list(
+ Self::table()
+ .filter(
+ dsl::event_id
+ .nullable()
+ .eq(dsl::initial_attempt_id) // Filter initial attempts only
+ .and(dsl::business_profile_id.eq(profile_id.to_owned()))
+ .and(dsl::primary_object_id.eq(primary_object_id.to_owned())),
+ )
+ .order(dsl::created_at.desc()),
+ );
query = Self::apply_event_recipient(query, event_recipient);
@@ -387,15 +394,16 @@ impl Event {
is_delivered: Option<bool>,
event_recipient: Option<common_enums::EventRecipient>,
) -> StorageResult<Vec<Self>> {
- let mut query = Self::table()
- .filter(
- dsl::event_id
- .nullable()
- .eq(dsl::initial_attempt_id) // Filter initial attempts only
- .and(dsl::business_profile_id.eq(profile_id.to_owned())),
- )
- .order(dsl::created_at.desc())
- .into_boxed();
+ let mut query = crate::list::into_boxed_list(
+ Self::table()
+ .filter(
+ dsl::event_id
+ .nullable()
+ .eq(dsl::initial_attempt_id) // Filter initial attempts only
+ .and(dsl::business_profile_id.eq(profile_id.to_owned())),
+ )
+ .order(dsl::created_at.desc()),
+ );
query = Self::apply_filters(
query,
@@ -595,15 +603,14 @@ impl Event {
is_delivered: Option<bool>,
event_recipient: Option<common_enums::EventRecipient>,
) -> StorageResult<i64> {
- let mut query = Self::table()
- .count()
- .filter(
+ let mut query = crate::list::into_boxed_list(
+ Self::table().count().filter(
dsl::event_id
.nullable()
.eq(dsl::initial_attempt_id) // Filter initial attempts only
.and(dsl::merchant_id.eq(merchant_id.to_owned())),
- )
- .into_boxed();
+ ),
+ );
query = Self::apply_filters(
query,
@@ -636,15 +643,14 @@ impl Event {
is_delivered: Option<bool>,
event_recipient: Option<common_enums::EventRecipient>,
) -> StorageResult<i64> {
- let mut query = Self::table()
- .count()
- .filter(
+ let mut query = crate::list::into_boxed_list(
+ Self::table().count().filter(
dsl::event_id
.nullable()
.eq(dsl::initial_attempt_id) // Filter initial attempts only
.and(dsl::business_profile_id.eq(profile_id.to_owned())),
- )
- .into_boxed();
+ ),
+ );
query = Self::apply_filters(
query,
@@ -683,9 +689,8 @@ impl Event {
// handle events created during staggered rollout by older code. This
// fallback is correct for standard merchants where merchant_id equals
// the webhook recipient.
- let mut query = Self::table()
- .count()
- .filter(
+ let mut query = crate::list::into_boxed_list(
+ Self::table().count().filter(
dsl::event_id
.nullable()
.eq(dsl::initial_attempt_id) // Filter initial attempts only
@@ -696,8 +701,8 @@ impl Event {
.is_null()
.and(dsl::merchant_id.eq(initiator_merchant_id.to_owned()))),
),
- )
- .into_boxed();
+ ),
+ );
query = Self::apply_filters(
query,
diff --git a/crates/diesel_models/src/query/generics.rs b/crates/diesel_models/src/query/generics.rs
index aba801f3ad..a1a2394f13 100644
--- a/crates/diesel_models/src/query/generics.rs
+++ b/crates/diesel_models/src/query/generics.rs
@@ -17,7 +17,7 @@ use diesel::{
LoadQuery, RunQueryDsl,
},
result::Error as DieselError,
- Expression, ExpressionMethods, Insertable, QueryDsl, QuerySource, Table,
+ Expression, ExpressionMethods, Insertable, QuerySource, Table,
};
use error_stack::{report, ResultExt};
#[cfg(feature = "deja")]
@@ -854,7 +854,7 @@ where
O: Expression,
R: Send + 'static + DejaQueryResult,
{
- let mut query = T::table().into_boxed();
+ let mut query = crate::list::into_boxed_list(T::table());
query = query
.filter(predicate)
.filter(T::table().get_primary_key().is_not_null());
diff --git a/crates/diesel_models/src/query/payment_attempt.rs b/crates/diesel_models/src/query/payment_attempt.rs
index 62f02a3a7c..31a866c994 100644
--- a/crates/diesel_models/src/query/payment_attempt.rs
+++ b/crates/diesel_models/src/query/payment_attempt.rs
@@ -454,11 +454,12 @@ impl PaymentAttempt {
merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>,
card_network: Option<Vec<enums::CardNetwork>>,
) -> StorageResult<i64> {
- let mut filter = <Self as HasTable>::table()
- .count()
- .filter(dsl::merchant_id.eq(merchant_id.to_owned()))
- .filter(dsl::id.eq_any(active_attempt_ids.to_owned()))
- .into_boxed();
+ let mut filter = crate::list::into_boxed_list(
+ <Self as HasTable>::table()
+ .count()
+ .filter(dsl::merchant_id.eq(merchant_id.to_owned()))
+ .filter(dsl::id.eq_any(active_attempt_ids.to_owned())),
+ );
if let Some(connectors) = connector {
filter = filter.filter(dsl::connector.eq_any(connectors));
@@ -513,11 +514,12 @@ impl PaymentAttempt {
card_network: Option<Vec<enums::CardNetwork>>,
card_discovery: Option<Vec<enums::CardDiscovery>>,
) -> StorageResult<i64> {
- let mut filter = <Self as HasTable>::table()
- .count()
- .filter(dsl::processor_merchant_id.eq(processor_merchant_id.to_owned()))
- .filter(dsl::attempt_id.eq_any(active_attempt_ids.to_owned()))
- .into_boxed();
+ let mut filter = crate::list::into_boxed_list(
+ <Self as HasTable>::table()
+ .count()
+ .filter(dsl::processor_merchant_id.eq(processor_merchant_id.to_owned()))
+ .filter(dsl::attempt_id.eq_any(active_attempt_ids.to_owned())),
+ );
if let Some(connector) = connector {
filter = filter.filter(dsl::connector.eq_any(connector));
diff --git a/crates/diesel_models/src/query/payment_method.rs b/crates/diesel_models/src/query/payment_method.rs
index ea91bb228a..9df83469b8 100644
--- a/crates/diesel_models/src/query/payment_method.rs
+++ b/crates/diesel_models/src/query/payment_method.rs
@@ -142,15 +142,14 @@ impl PaymentMethod {
merchant_id: &common_utils::id_type::MerchantId,
status: common_enums::PaymentMethodStatus,
) -> StorageResult<i64> {
- let filter = <Self as HasTable>::table()
- .count()
- .filter(
+ let filter = crate::list::into_boxed_list(
+ <Self as HasTable>::table().count().filter(
dsl::customer_id
.eq(customer_id.to_owned())
.and(dsl::merchant_id.eq(merchant_id.to_owned()))
.and(dsl::status.eq(status.to_owned())),
- )
- .into_boxed();
+ ),
+ );
router_env::logger::debug!(query = %debug_query::<Pg, _>(&filter).to_string());
diff --git a/crates/diesel_models/src/query/payouts.rs b/crates/diesel_models/src/query/payouts.rs
index 1aa45bea83..5324222a1c 100644
--- a/crates/diesel_models/src/query/payouts.rs
+++ b/crates/diesel_models/src/query/payouts.rs
@@ -113,12 +113,15 @@ impl Payouts {
status: Option<Vec<enums::PayoutStatus>>,
payout_type: Option<Vec<enums::PayoutType>>,
) -> StorageResult<i64> {
- let mut filter = <Self as HasTable>::table()
- .inner_join(payout_attempt::table.on(payout_attempt::dsl::payout_id.eq(dsl::payout_id)))
- .count()
- .filter(dsl::merchant_id.eq(merchant_id.to_owned()))
- .filter(dsl::payout_id.eq_any(active_payout_ids.to_vec()))
- .into_boxed();
+ let mut filter = crate::list::into_boxed_list(
+ <Self as HasTable>::table()
+ .inner_join(
+ payout_attempt::table.on(payout_attempt::dsl::payout_id.eq(dsl::payout_id)),
+ )
+ .count()
+ .filter(dsl::merchant_id.eq(merchant_id.to_owned()))
+ .filter(dsl::payout_id.eq_any(active_payout_ids.to_vec())),
+ );
if let Some(connector) = connector {
filter = filter.filter(payout_attempt::dsl::connector.eq_any(connector));
diff --git a/crates/diesel_models/src/query/role.rs b/crates/diesel_models/src/query/role.rs
index 6fae9cda78..09542dc7f9 100644
--- a/crates/diesel_models/src/query/role.rs
+++ b/crates/diesel_models/src/query/role.rs
@@ -120,9 +120,10 @@ impl Role {
entity_type: Option<EntityType>,
limit: Option<u32>,
) -> StorageResult<Vec<Self>> {
- let mut query = <Self as HasTable>::table()
- .filter(dsl::tenant_id.eq(tenant_id).and(dsl::org_id.eq(org_id)))
- .into_boxed();
+ let mut query = crate::list::into_boxed_list(
+ <Self as HasTable>::table()
+ .filter(dsl::tenant_id.eq(tenant_id).and(dsl::org_id.eq(org_id))),
+ );
if let Some(merchant_id) = merchant_id {
query = query.filter(
@@ -166,8 +167,7 @@ impl Role {
tenant_id: id_type::TenantId,
org_id: id_type::OrganizationId,
) -> StorageResult<Vec<Self>> {
- let mut query = <Self as HasTable>::table()
- .into_boxed()
+ let mut query = crate::list::into_boxed_list(<Self as HasTable>::table())
.filter(dsl::tenant_id.eq(tenant_id))
.filter(dsl::org_id.eq(org_id));
diff --git a/crates/diesel_models/src/query/user/theme.rs b/crates/diesel_models/src/query/user/theme.rs
index 9a29acd8ba..68b225eaf6 100644
--- a/crates/diesel_models/src/query/user/theme.rs
+++ b/crates/diesel_models/src/query/user/theme.rs
@@ -131,7 +131,7 @@ impl Theme {
conn: &PgPooledConn,
lineage: ThemeLineage,
) -> StorageResult<Self> {
- let query = <Self as HasTable>::table().into_boxed();
+ let query = crate::list::into_boxed_list(<Self as HasTable>::table());
let query =
lineage
@@ -217,7 +217,7 @@ impl Theme {
) -> StorageResult<Vec<Self>> {
let filter = Self::lineage_hierarchy_filter(lineage);
- let query = <Self as HasTable>::table().filter(filter).into_boxed();
+ let query = crate::list::into_boxed_list(<Self as HasTable>::table().filter(filter));
logger::debug!(query = %debug_query::<Pg,_>(&query).to_string());
diff --git a/crates/diesel_models/src/query/user_role.rs b/crates/diesel_models/src/query/user_role.rs
index 62b2267ccb..38774f6650 100644
--- a/crates/diesel_models/src/query/user_role.rs
+++ b/crates/diesel_models/src/query/user_role.rs
@@ -264,9 +264,10 @@ impl UserRole {
version: Option<UserRoleVersion>,
limit: Option<u32>,
) -> StorageResult<Vec<Self>> {
- let mut query = <Self as HasTable>::table()
- .filter(dsl::user_id.eq(user_id).and(dsl::tenant_id.eq(tenant_id)))
- .into_boxed();
+ let mut query = crate::list::into_boxed_list(
+ <Self as HasTable>::table()
+ .filter(dsl::user_id.eq(user_id).and(dsl::tenant_id.eq(tenant_id))),
+ );
if let Some(org_id) = org_id {
query = query.filter(dsl::org_id.eq(org_id));
@@ -326,9 +327,10 @@ impl UserRole {
version: Option<UserRoleVersion>,
limit: Option<u32>,
) -> StorageResult<Vec<Self>> {
- let mut query = <Self as HasTable>::table()
- .filter(dsl::org_id.eq(org_id).and(dsl::tenant_id.eq(tenant_id)))
- .into_boxed();
+ let mut query = crate::list::into_boxed_list(
+ <Self as HasTable>::table()
+ .filter(dsl::org_id.eq(org_id).and(dsl::tenant_id.eq(tenant_id))),
+ );
if let Some(user_id) = user_id {
query = query.filter(dsl::user_id.eq(user_id));
@@ -377,9 +379,9 @@ impl UserRole {
user_id: String,
limit: Option<u32>,
) -> StorageResult<Vec<Self>> {
- let mut query = <Self as HasTable>::table()
- .filter(dsl::user_id.eq(user_id))
- .into_boxed();
+ let mut query = crate::list::into_boxed_list(
+ <Self as HasTable>::table().filter(dsl::user_id.eq(user_id)),
+ );
if let Some(limit) = limit {
query = query.limit(limit.into());
}
diff --git a/crates/hyperswitch_domain_models/src/disputes.rs b/crates/hyperswitch_domain_models/src/disputes.rs
index 33db166bda..fac5bf12e6 100644
--- a/crates/hyperswitch_domain_models/src/disputes.rs
+++ b/crates/hyperswitch_domain_models/src/disputes.rs
@@ -3,8 +3,8 @@ use crate::errors;
pub struct DisputeListConstraints {
pub dispute_id: Option<String>,
pub payment_id: Option<common_utils::id_type::PaymentId>,
- pub limit: Option<u32>,
- pub offset: Option<u32>,
+ pub limit: common_utils::types::list::PageSize,
+ pub offset: common_utils::types::list::PageOffset,
pub profile_id: Option<Vec<common_utils::id_type::ProfileId>>,
pub dispute_status: Option<Vec<common_enums::DisputeStatus>>,
pub dispute_stage: Option<Vec<common_enums::DisputeStage>>,
diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
index 136db9d7bc..c8060457e2 100644
--- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
+++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
@@ -1,13 +1,10 @@
use api_models::customers::CustomerDocumentDetails;
use common_types::primitive_wrappers;
-#[cfg(feature = "v1")]
-use common_utils::consts::PAYMENTS_LIST_MAX_LIMIT_V2;
#[cfg(feature = "v2")]
use common_utils::errors::ParsingError;
#[cfg(feature = "v2")]
use common_utils::ext_traits::{Encode, ValueExt};
use common_utils::{
- consts::PAYMENTS_LIST_MAX_LIMIT_V1,
crypto::Encryptable,
encryption::Encryption,
errors::{CustomResult, ValidationError},
@@ -1799,7 +1796,7 @@ impl PaymentIntentFetchConstraints {
#[cfg(feature = "v1")]
pub struct PaymentIntentListParams {
- pub offset: u32,
+ pub offset: common_utils::types::list::PageOffset,
pub starting_at: Option<PrimitiveDateTime>,
pub ending_at: Option<PrimitiveDateTime>,
pub amount_filter: Option<api_models::payments::AmountFilter>,
@@ -1814,7 +1811,7 @@ pub struct PaymentIntentListParams {
pub customer_id: Option<id_type::CustomerId>,
pub starting_after_id: Option<id_type::PaymentId>,
pub ending_before_id: Option<id_type::PaymentId>,
- pub limit: Option<u32>,
+ pub limit: common_utils::types::list::PageSize,
pub order: api_models::payments::Order,
pub card_network: Option<Vec<common_enums::CardNetwork>>,
pub card_discovery: Option<Vec<common_enums::CardDiscovery>>,
@@ -1824,7 +1821,7 @@ pub struct PaymentIntentListParams {
#[cfg(feature = "v2")]
pub struct PaymentIntentListParams {
- pub offset: u32,
+ pub offset: common_utils::types::list::PageOffset,
pub starting_at: Option<PrimitiveDateTime>,
pub ending_at: Option<PrimitiveDateTime>,
pub amount_filter: Option<api_models::payments::AmountFilter>,
@@ -1839,7 +1836,7 @@ pub struct PaymentIntentListParams {
pub customer_id: Option<id_type::GlobalCustomerId>,
pub starting_after_id: Option<id_type::GlobalPaymentId>,
pub ending_before_id: Option<id_type::GlobalPaymentId>,
- pub limit: Option<u32>,
+ pub limit: common_utils::types::list::PageSize,
pub order: api_models::payments::Order,
pub card_network: Option<Vec<common_enums::CardNetwork>>,
pub merchant_order_reference_id: Option<String>,
@@ -1861,7 +1858,7 @@ impl From<api_models::payments::PaymentListConstraints> for PaymentIntentFetchCo
created_gte,
} = value;
Self::List(Box::new(PaymentIntentListParams {
- offset: 0,
+ offset: common_utils::types::list::PageOffset::default(),
starting_at: created_gte.or(created_gt).or(created),
ending_at: created_lte.or(created_lt).or(created),
amount_filter: None,
@@ -1876,7 +1873,7 @@ impl From<api_models::payments::PaymentListConstraints> for PaymentIntentFetchCo
customer_id,
starting_after_id: starting_after,
ending_before_id: ending_before,
- limit: Some(std::cmp::min(limit, PAYMENTS_LIST_MAX_LIMIT_V1)),
+ limit,
order: Default::default(),
card_network: None,
card_discovery: None,
@@ -1917,7 +1914,7 @@ impl From<api_models::payments::PaymentListConstraints> for PaymentIntentFetchCo
offset,
} = value;
Self::List(Box::new(PaymentIntentListParams {
- offset: offset.unwrap_or_default(),
+ offset,
starting_at: created_gte.or(created_gt).or(created),
ending_at: created_lte.or(created_lt).or(created),
amount_filter: (start_amount.is_some() || end_amount.is_some()).then_some({
@@ -1937,7 +1934,7 @@ impl From<api_models::payments::PaymentListConstraints> for PaymentIntentFetchCo
customer_id,
starting_after_id: starting_after,
ending_before_id: ending_before,
- limit: Some(std::cmp::min(limit, PAYMENTS_LIST_MAX_LIMIT_V1)),
+ limit,
order: api_models::payments::Order {
on: order_on,
by: order_by,
@@ -1953,7 +1950,7 @@ impl From<api_models::payments::PaymentListConstraints> for PaymentIntentFetchCo
impl From<common_utils::types::TimeRange> for PaymentIntentFetchConstraints {
fn from(value: common_utils::types::TimeRange) -> Self {
Self::List(Box::new(PaymentIntentListParams {
- offset: 0,
+ offset: common_utils::types::list::PageOffset::default(),
starting_at: Some(value.start_time),
ending_at: value.end_time,
amount_filter: None,
@@ -1968,7 +1965,7 @@ impl From<common_utils::types::TimeRange> for PaymentIntentFetchConstraints {
customer_id: None,
starting_after_id: None,
ending_before_id: None,
- limit: None,
+ limit: common_utils::types::list::PageSize::default(),
order: Default::default(),
card_network: None,
card_discovery: None,
@@ -2016,7 +2013,7 @@ impl From<api_models::payments::PaymentListFilterConstraints> for PaymentIntentF
Self::Single { payment_intent_id }
} else {
Self::List(Box::new(PaymentIntentListParams {
- offset: offset.unwrap_or_default(),
+ offset,
starting_at: time_range.map(|t| t.start_time),
ending_at: time_range.and_then(|t| t.end_time),
amount_filter,
@@ -2031,7 +2028,7 @@ impl From<api_models::payments::PaymentListFilterConstraints> for PaymentIntentF
customer_id,
starting_after_id: None,
ending_before_id: None,
- limit: Some(std::cmp::min(limit, PAYMENTS_LIST_MAX_LIMIT_V2)),
+ limit,
order,
card_network,
card_discovery,
diff --git a/crates/hyperswitch_domain_models/src/payouts.rs b/crates/hyperswitch_domain_models/src/payouts.rs
index 9a40dc119c..adf463f9d8 100644
--- a/crates/hyperswitch_domain_models/src/payouts.rs
+++ b/crates/hyperswitch_domain_models/src/payouts.rs
@@ -3,7 +3,10 @@ pub mod payout_attempt;
pub mod payouts;
use common_enums as storage_enums;
-use common_utils::{consts, id_type};
+use common_utils::{
+ id_type,
+ types::list::{PageOffset, PageSize},
+};
use time::PrimitiveDateTime;
pub enum PayoutFetchConstraints {
@@ -12,7 +15,7 @@ pub enum PayoutFetchConstraints {
}
pub struct PayoutListParams {
- pub offset: u32,
+ pub offset: PageOffset,
pub starting_at: Option<PrimitiveDateTime>,
pub ending_at: Option<PrimitiveDateTime>,
pub connector: Option<Vec<api_models::enums::PayoutConnectors>>,
@@ -24,14 +27,14 @@ pub struct PayoutListParams {
pub starting_after_id: Option<id_type::PayoutId>,
pub ending_before_id: Option<id_type::PayoutId>,
pub entity_type: Option<common_enums::PayoutEntityType>,
- pub limit: Option<u32>,
+ pub limit: PageSize,
pub merchant_order_reference_id: Option<String>,
}
impl From<api_models::payouts::PayoutListConstraints> for PayoutFetchConstraints {
fn from(value: api_models::payouts::PayoutListConstraints) -> Self {
Self::List(Box::new(PayoutListParams {
- offset: 0,
+ offset: PageOffset::default(),
starting_at: value
.time_range
.map_or(value.created, |t| Some(t.start_time)),
@@ -46,10 +49,7 @@ impl From<api_models::payouts::PayoutListConstraints> for PayoutFetchConstraints
ending_before_id: value.ending_before,
entity_type: None,
merchant_order_reference_id: None,
- limit: Some(std::cmp::min(
- value.limit,
- consts::PAYOUTS_LIST_MAX_LIMIT_GET,
- )),
+ limit: value.limit,
}))
}
}
@@ -57,7 +57,7 @@ impl From<api_models::payouts::PayoutListConstraints> for PayoutFetchConstraints
impl From<common_utils::types::TimeRange> for PayoutFetchConstraints {
fn from(value: common_utils::types::TimeRange) -> Self {
Self::List(Box::new(PayoutListParams {
- offset: 0,
+ offset: PageOffset::default(),
starting_at: Some(value.start_time),
ending_at: value.end_time,
connector: None,
@@ -70,7 +70,7 @@ impl From<common_utils::types::TimeRange> for PayoutFetchConstraints {
ending_before_id: None,
entity_type: None,
merchant_order_reference_id: None,
- limit: None,
+ limit: PageSize::default(),
}))
}
}
@@ -81,7 +81,7 @@ impl From<api_models::payouts::PayoutListFilterConstraints> for PayoutFetchConst
Self::Single { payout_id }
} else {
Self::List(Box::new(PayoutListParams {
- offset: value.offset.unwrap_or_default(),
+ offset: value.offset,
starting_at: value.time_range.map(|t| t.start_time),
ending_at: value.time_range.and_then(|t| t.end_time),
connector: value.connector,
@@ -94,10 +94,7 @@ impl From<api_models::payouts::PayoutListFilterConstraints> for PayoutFetchConst
ending_before_id: None,
entity_type: value.entity_type,
merchant_order_reference_id: value.merchant_order_reference_id,
- limit: Some(std::cmp::min(
- value.limit,
- consts::PAYOUTS_LIST_MAX_LIMIT_POST,
- )),
+ limit: value.limit,
}))
}
}
diff --git a/crates/hyperswitch_domain_models/src/refunds.rs b/crates/hyperswitch_domain_models/src/refunds.rs
index 151937799f..57fc93ab0b 100644
--- a/crates/hyperswitch_domain_models/src/refunds.rs
+++ b/crates/hyperswitch_domain_models/src/refunds.rs
@@ -8,8 +8,8 @@ pub struct RefundListConstraints {
pub payment_id: Option<common_utils::id_type::PaymentId>,
pub refund_id: Option<String>,
pub profile_id: Option<Vec<common_utils::id_type::ProfileId>>,
- pub limit: Option<i64>,
- pub offset: Option<i64>,
+ pub limit: common_utils::types::list::PageSize,
+ pub offset: common_utils::types::list::PageOffset,
pub time_range: Option<common_utils::types::TimeRange>,
pub amount_filter: Option<api_models::payments::AmountFilter>,
pub connector: Option<Vec<String>>,
@@ -23,8 +23,8 @@ pub struct RefundListConstraints {
pub payment_id: Option<common_utils::id_type::GlobalPaymentId>,
pub refund_id: Option<common_utils::id_type::GlobalRefundId>,
pub profile_id: common_utils::id_type::ProfileId,
- pub limit: Option<i64>,
- pub offset: Option<i64>,
+ pub limit: common_utils::types::list::PageSize,
+ pub offset: common_utils::types::list::PageOffset,
pub time_range: Option<common_utils::types::TimeRange>,
pub amount_filter: Option<api_models::payments::AmountFilter>,
pub connector: Option<Vec<String>>,
@@ -89,7 +89,10 @@ impl
payment_id,
refund_id,
profile_id: profile_id_list,
- limit,
+ // API keeps `Option<PageSize>` for wire compat; the domain holds a resolved
+ // value. `PageSize::default()` is the semantically-correct "no preference"
+ // — same behavior as the previous `Option<i64>` validator's `None → 10`.
+ limit: limit.unwrap_or_default(),
offset,
time_range,
amount_filter,
diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs
index 8a91791ce7..68ca1fab7d 100644
--- a/crates/openapi/src/openapi.rs
+++ b/crates/openapi/src/openapi.rs
@@ -842,6 +842,8 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payment_methods::TokenizePaymentMethodRequest,
api_models::refunds::RefundListRequest,
api_models::refunds::RefundListResponse,
+ common_utils::types::list::PageSize,
+ common_utils::types::list::PageOffset,
api_models::relay::RelayRequest,
api_models::relay::RelayResponse,
api_models::enums::RelayType,
diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs
index 2b0c00fd05..2303653240 100644
--- a/crates/openapi/src/openapi_v2.rs
+++ b/crates/openapi/src/openapi_v2.rs
@@ -256,6 +256,8 @@ Never share your secret api keys. Keep them guarded and secure.
common_types::payments::ExternalSurchargeDetails,
common_types::three_ds_decision_rule_engine::ThreeDSDecisionRule,
common_types::three_ds_decision_rule_engine::ThreeDSDecision,
+ common_utils::types::list::PageSize,
+ common_utils::types::list::PageOffset,
api_models::payments::CartesBancairesParams,
api_models::payments::NetworkParams,
api_models::payments::Cryptogram,
diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs
index 530ee44039..493b5fc225 100644
--- a/crates/router/src/analytics.rs
+++ b/crates/router/src/analytics.rs
@@ -3824,8 +3824,8 @@ pub mod routes {
query: constraints.query.unwrap_or_default(),
filters: Some(filters),
time_range: constraints.time_range,
- offset: constraints.offset.map(i64::from).unwrap_or(0),
- count: i64::from(constraints.limit),
+ offset: constraints.offset.as_i64(),
+ count: constraints.limit.as_i64(),
order: Some(constraints.order),
},
};
@@ -3897,8 +3897,8 @@ pub mod routes {
query: constraints.query.unwrap_or_default(),
filters: Some(filters),
time_range: constraints.time_range,
- offset: constraints.offset.map(i64::from).unwrap_or(0),
- count: i64::from(constraints.limit),
+ offset: constraints.offset.as_i64(),
+ count: constraints.limit.as_i64(),
order: Some(constraints.order),
},
};
diff --git a/crates/router/src/compatibility/stripe/payment_intents/types.rs b/crates/router/src/compatibility/stripe/payment_intents/types.rs
index d20770e3dd..3f8a0cdac9 100644
--- a/crates/router/src/compatibility/stripe/payment_intents/types.rs
+++ b/crates/router/src/compatibility/stripe/payment_intents/types.rs
@@ -650,7 +650,7 @@ impl TryFrom<StripePaymentListConstraints> for payments::PaymentListConstraints
customer_id: item.customer,
starting_after: item.starting_after,
ending_before: item.ending_before,
- limit: item.limit,
+ limit: item.limit.into(),
created: from_timestamp_to_datetime(item.created)?,
created_lt: from_timestamp_to_datetime(item.created_lt)?,
created_gt: from_timestamp_to_datetime(item.created_gt)?,
diff --git a/crates/router/src/compatibility/stripe/setup_intents/types.rs b/crates/router/src/compatibility/stripe/setup_intents/types.rs
index 5e72d41c2b..1ea20795f6 100644
--- a/crates/router/src/compatibility/stripe/setup_intents/types.rs
+++ b/crates/router/src/compatibility/stripe/setup_intents/types.rs
@@ -618,7 +618,7 @@ impl TryFrom<StripePaymentListConstraints> for payments::PaymentListConstraints
customer_id: item.customer,
starting_after: item.starting_after,
ending_before: item.ending_before,
- limit: item.limit,
+ limit: item.limit.into(),
created: from_timestamp_to_datetime(item.created)?,
created_lt: from_timestamp_to_datetime(item.created_lt)?,
created_gt: from_timestamp_to_datetime(item.created_gt)?,
diff --git a/crates/router/src/connection.rs b/crates/router/src/connection.rs
index 8b4c7890ae..582ca09bf6 100644
--- a/crates/router/src/connection.rs
+++ b/crates/router/src/connection.rs
@@ -63,6 +63,7 @@ pub async fn pg_connection_read<T: storage_impl::DatabaseStore>(
.change_context(storage_errors::StorageError::DatabaseConnectionError)?;
#[cfg(feature = "deja")]
deja_route_replay_schema(&mut conn, store).await;
+
Ok(conn)
}
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index eecbb3e97b..e5b7055530 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -10577,7 +10577,6 @@ pub async fn list_payments(
profile_id_list: Option<Vec<id_type::ProfileId>>,
constraints: api::PaymentListConstraints,
) -> RouterResponse<api::PaymentListResponse> {
- helpers::validate_payment_list_request(&constraints)?;
let processor_merchant_id = platform.get_processor().get_account().get_id();
let db = state.store.as_ref();
let payment_intents = helpers::filter_by_constraints(
@@ -10654,8 +10653,6 @@ pub async fn list_payments(
) -> RouterResponse<payments_api::PaymentListResponse> {
common_utils::metrics::utils::record_operation_time(
async {
- let limit = &constraints.limit;
- helpers::validate_payment_list_request_for_joins(*limit)?;
let db: &dyn StorageInterface = state.store.as_ref();
let fetch_constraints = constraints.clone().into();
let list: Vec<(storage::PaymentIntent, Option<storage::PaymentAttempt>)> = db
@@ -10731,8 +10728,7 @@ pub async fn revenue_recovery_list_payments(
) -> RouterResponse<payments_api::RecoveryPaymentListResponse> {
common_utils::metrics::utils::record_operation_time(
async {
- let limit = &constraints.limit;
- helpers::validate_payment_list_request_for_joins(*limit)?;
+ // `limit` is a `PageSize`, already validated at deserialize; no extra check needed.
let db: &dyn StorageInterface = state.store.as_ref();
let fetch_constraints = constraints.clone().into();
let list: Vec<(storage::PaymentIntent, Option<storage::PaymentAttempt>)> = db
@@ -10868,19 +10864,17 @@ pub async fn revenue_recovery_list_payments(
pub async fn apply_filters_on_payments(
state: SessionState,
platform: domain::Platform,
- profile_id_list: Option<Vec<id_type::ProfileId>>,
+ _profile_id_list: Option<Vec<id_type::ProfileId>>,
constraints: api::PaymentListFilterConstraints,
) -> RouterResponse<api::PaymentListResponseV2> {
common_utils::metrics::utils::record_operation_time(
async {
- let limit = &constraints.limit;
- helpers::validate_payment_list_request_for_joins(*limit)?;
let db: &dyn StorageInterface = state.store.as_ref();
- let pi_fetch_constraints = (constraints.clone(), profile_id_list.clone()).try_into()?;
+ let fetch_constraints = constraints.clone().into();
let list: Vec<(storage::PaymentIntent, storage::PaymentAttempt)> = db
.get_filtered_payment_intents_attempt(
platform.get_processor().get_account().get_id(),
- &pi_fetch_constraints,
+ &fetch_constraints,
platform.get_processor().get_key_store(),
platform.get_processor().get_account().storage_scheme,
)
@@ -10892,7 +10886,7 @@ pub async fn apply_filters_on_payments(
let active_attempt_ids = db
.get_filtered_active_attempt_ids_for_total_count(
platform.get_processor().get_account().get_id(),
- &pi_fetch_constraints,
+ &fetch_constraints,
platform.get_processor().get_account().storage_scheme,
)
.await
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 4d6df05fb7..c53507e35a 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -4169,36 +4169,6 @@ pub(super) async fn filter_by_constraints(
Ok(result)
}
-#[cfg(feature = "olap")]
-pub(super) fn validate_payment_list_request(
- req: &api::PaymentListConstraints,
-) -> CustomResult<(), errors::ApiErrorResponse> {
- use common_utils::consts::PAYMENTS_LIST_MAX_LIMIT_V1;
-
- utils::when(
- req.limit > PAYMENTS_LIST_MAX_LIMIT_V1 || req.limit < 1,
- || {
- Err(errors::ApiErrorResponse::InvalidRequestData {
- message: format!("limit should be in between 1 and {PAYMENTS_LIST_MAX_LIMIT_V1}"),
- })
- },
- )?;
- Ok(())
-}
-#[cfg(feature = "olap")]
-pub(super) fn validate_payment_list_request_for_joins(
- limit: u32,
-) -> CustomResult<(), errors::ApiErrorResponse> {
- use common_utils::consts::PAYMENTS_LIST_MAX_LIMIT_V2;
-
- utils::when(!(1..=PAYMENTS_LIST_MAX_LIMIT_V2).contains(&limit), || {
- Err(errors::ApiErrorResponse::InvalidRequestData {
- message: format!("limit should be in between 1 and {PAYMENTS_LIST_MAX_LIMIT_V2}"),
- })
- })?;
- Ok(())
-}
-
#[cfg(feature = "v1")]
pub fn get_handle_response_url(
payment_id: id_type::PaymentId,
diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rs
index 03f723f1bb..6dc75b8813 100644
--- a/crates/router/src/core/payouts.rs
+++ b/crates/router/src/core/payouts.rs
@@ -832,7 +832,6 @@ pub async fn payouts_list_core(
profile_id_list: Option<Vec<id_type::ProfileId>>,
constraints: payouts::PayoutListConstraints,
) -> RouterResponse<payouts::PayoutListResponse> {
- validator::validate_payout_list_request(&constraints)?;
let merchant_id = platform.get_processor().get_account().get_id();
let db = state.store.as_ref();
let payouts = helpers::filter_by_constraints(
@@ -975,8 +974,8 @@ pub async fn payouts_filtered_list_core(
profile_id_list: Option<Vec<id_type::ProfileId>>,
filters: payouts::PayoutListFilterConstraints,
) -> RouterResponse<payouts::PayoutListResponse> {
- let limit = &filters.limit;
- validator::validate_payout_list_request_for_joins(*limit)?;
+ let limit = filters.limit;
+ validator::validate_payout_list_request_for_joins(limit)?;
let db = state.store.as_ref();
let constraints = filters.clone().into();
let list: Vec<(
diff --git a/crates/router/src/core/payouts/validator.rs b/crates/router/src/core/payouts/validator.rs
index 4d380815c1..ea5276eeae 100644
--- a/crates/router/src/core/payouts/validator.rs
+++ b/crates/router/src/core/payouts/validator.rs
@@ -351,30 +351,13 @@ pub fn validate_payout_link_request(
Ok(())
}
-#[cfg(feature = "olap")]
-pub(super) fn validate_payout_list_request(
- req: &payouts::PayoutListConstraints,
-) -> CustomResult<(), errors::ApiErrorResponse> {
- use common_utils::consts::PAYOUTS_LIST_MAX_LIMIT_GET;
-
- utils::when(
- req.limit > PAYOUTS_LIST_MAX_LIMIT_GET || req.limit < 1,
- || {
- Err(errors::ApiErrorResponse::InvalidRequestData {
- message: format!("limit should be in between 1 and {PAYOUTS_LIST_MAX_LIMIT_GET}"),
- })
- },
- )?;
- Ok(())
-}
-
#[cfg(feature = "olap")]
pub(super) fn validate_payout_list_request_for_joins(
- limit: u32,
+ limit: common_utils::types::list::PageSize,
) -> CustomResult<(), errors::ApiErrorResponse> {
use common_utils::consts::PAYOUTS_LIST_MAX_LIMIT_POST;
- utils::when(!(1..=PAYOUTS_LIST_MAX_LIMIT_POST).contains(&limit), || {
+ utils::when(limit.as_u32() > PAYOUTS_LIST_MAX_LIMIT_POST, || {
Err(errors::ApiErrorResponse::InvalidRequestData {
message: format!("limit should be in between 1 and {PAYOUTS_LIST_MAX_LIMIT_POST}"),
})
diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs
index 6b4ed515ee..3db3200246 100644
--- a/crates/router/src/core/refunds.rs
+++ b/crates/router/src/core/refunds.rs
@@ -1510,8 +1510,8 @@ pub async fn refund_list(
req: api_models::refunds::RefundListRequest,
) -> RouterResponse<api_models::refunds::RefundListResponse> {
let db = state.store;
- let limit = validator::validate_refund_list(req.limit)?;
- let offset = req.offset.unwrap_or_default();
+ let limit = req.limit.unwrap_or_default();
+ let offset = req.offset;
let refund_list = db
.filter_refund_by_constraints(
diff --git a/crates/router/src/core/refunds_v2.rs b/crates/router/src/core/refunds_v2.rs
index af0a8b9c7d..dad7165cb9 100644
--- a/crates/router/src/core/refunds_v2.rs
+++ b/crates/router/src/core/refunds_v2.rs
@@ -1102,8 +1102,8 @@ pub async fn refund_list(
req: refunds::RefundListRequest,
) -> errors::RouterResponse<refunds::RefundListResponse> {
let db = state.store;
- let limit = refunds_validator::validate_refund_list(req.limit)?;
- let offset = req.offset.unwrap_or_default();
+ let limit = req.limit;
+ let offset = req.offset;
let refund_list = db
.filter_refund_by_constraints(
diff --git a/crates/router/src/db/dispute.rs b/crates/router/src/db/dispute.rs
index ba1eb60df0..ccd179f5b4 100644
--- a/crates/router/src/db/dispute.rs
+++ b/crates/router/src/db/dispute.rs
@@ -806,16 +806,8 @@ impl DisputeInterface for MockDb {
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<Vec<storage::Dispute>, errors::StorageError> {
let locked_disputes = self.disputes.lock().await;
- let limit_usize = dispute_constraints
- .limit
- .unwrap_or(u32::MAX)
- .try_into()
- .unwrap_or(usize::MAX);
- let offset_usize = dispute_constraints
- .offset
- .unwrap_or(0)
- .try_into()
- .unwrap_or(usize::MIN);
+ let limit_usize = dispute_constraints.limit.as_usize();
+ let offset_usize = dispute_constraints.offset.as_usize();
let filtered_disputes: Vec<storage::Dispute> = locked_disputes
.iter()
.filter(|dispute| {
@@ -1267,8 +1259,8 @@ mod tests {
connector: None,
merchant_connector_id: None,
currency: None,
- limit: None,
- offset: None,
+ limit: Default::default(),
+ offset: Default::default(),
dispute_status: None,
dispute_stage: None,
reason: None,
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 0f28180dbc..8e97154186 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -3161,8 +3161,8 @@ impl RefundInterface for KafkaStore {
processor_merchant_id: &id_type::MerchantId,
refund_details: &refunds::RefundListConstraints,
storage_scheme: MerchantStorageScheme,
- limit: i64,
- offset: i64,
+ limit: diesel_models::list::PageSize,
+ offset: diesel_models::list::PageOffset,
) -> CustomResult<Vec<diesel_refund::Refund>, errors::StorageError> {
self.diesel_store
.filter_refund_by_constraints(
@@ -3181,8 +3181,8 @@ impl RefundInterface for KafkaStore {
merchant_id: &id_type::MerchantId,
refund_details: refunds::RefundListConstraints,
storage_scheme: MerchantStorageScheme,
- limit: i64,
- offset: i64,
+ limit: diesel_models::list::PageSize,
+ offset: diesel_models::list::PageOffset,
) -> CustomResult<Vec<diesel_refund::Refund>, errors::StorageError> {
self.diesel_store
.filter_refund_by_constraints(
diff --git a/crates/router/src/db/refund.rs b/crates/router/src/db/refund.rs
index 9bdbf42ad8..474350b7ed 100644
--- a/crates/router/src/db/refund.rs
+++ b/crates/router/src/db/refund.rs
@@ -83,8 +83,8 @@ pub trait RefundInterface {
processor_merchant_id: &common_utils::id_type::MerchantId,
refund_details: &refunds::RefundListConstraints,
storage_scheme: enums::MerchantStorageScheme,
- limit: i64,
- offset: i64,
+ limit: diesel_models::list::PageSize,
+ offset: diesel_models::list::PageOffset,
) -> CustomResult<Vec<diesel_models::refund::Refund>, errors::StorageError>;
#[cfg(all(feature = "v2", feature = "olap"))]
@@ -93,8 +93,8 @@ pub trait RefundInterface {
merchant_id: &common_utils::id_type::MerchantId,
refund_details: refunds::RefundListConstraints,
storage_scheme: enums::MerchantStorageScheme,
- limit: i64,
- offset: i64,
+ limit: diesel_models::list::PageSize,
+ offset: diesel_models::list::PageOffset,
) -> CustomResult<Vec<diesel_models::refund::Refund>, errors::StorageError>;
#[cfg(all(feature = "v1", feature = "olap"))]
@@ -379,8 +379,8 @@ mod storage {
processor_merchant_id: &common_utils::id_type::MerchantId,
refund_details: &refunds::RefundListConstraints,
_storage_scheme: enums::MerchantStorageScheme,
- limit: i64,
- offset: i64,
+ limit: diesel_models::list::PageSize,
+ offset: diesel_models::list::PageOffset,
) -> CustomResult<Vec<diesel_models::refund::Refund>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
<diesel_models::refund::Refund as storage_types::RefundDbExt>::filter_by_constraints(
@@ -401,8 +401,8 @@ mod storage {
merchant_id: &common_utils::id_type::MerchantId,
refund_details: refunds::RefundListConstraints,
_storage_scheme: enums::MerchantStorageScheme,
- limit: i64,
- offset: i64,
+ limit: diesel_models::list::PageSize,
+ offset: diesel_models::list::PageOffset,
) -> CustomResult<Vec<diesel_models::refund::Refund>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
<diesel_models::refund::Refund as storage_types::RefundDbExt>::filter_by_constraints(
@@ -1203,8 +1203,8 @@ mod storage {
processor_merchant_id: &common_utils::id_type::MerchantId,
refund_details: &refunds::RefundListConstraints,
_storage_scheme: enums::MerchantStorageScheme,
- limit: i64,
- offset: i64,
+ limit: diesel_models::list::PageSize,
+ offset: diesel_models::list::PageOffset,
) -> CustomResult<Vec<diesel_models::refund::Refund>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
<diesel_models::refund::Refund as storage_types::RefundDbExt>::filter_by_constraints(
@@ -1225,8 +1225,8 @@ mod storage {
merchant_id: &common_utils::id_type::MerchantId,
refund_details: refunds::RefundListConstraints,
_storage_scheme: enums::MerchantStorageScheme,
- limit: i64,
- offset: i64,
+ limit: diesel_models::list::PageSize,
+ offset: diesel_models::list::PageOffset,
) -> CustomResult<Vec<diesel_models::refund::Refund>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
<diesel_models::refund::Refund as storage_types::RefundDbExt>::filter_by_constraints(
@@ -1635,8 +1635,8 @@ impl RefundInterface for MockDb {
processor_merchant_id: &common_utils::id_type::MerchantId,
refund_details: &refunds::RefundListConstraints,
_storage_scheme: enums::MerchantStorageScheme,
- limit: i64,
- offset: i64,
+ limit: diesel_models::list::PageSize,
+ offset: diesel_models::list::PageOffset,
) -> CustomResult<Vec<diesel_models::refund::Refund>, errors::StorageError> {
let mut unique_connectors = HashSet::new();
let mut unique_merchant_connector_ids = HashSet::new();
@@ -1736,8 +1736,8 @@ impl RefundInterface for MockDb {
.filter(|refund| {
unique_statuses.is_empty() || unique_statuses.contains(&refund.refund_status)
})
- .skip(usize::try_from(offset).unwrap_or_default())
- .take(usize::try_from(limit).unwrap_or(MAX_LIMIT))
+ .skip(usize::try_from(offset.as_i64()).unwrap_or_default())
+ .take(usize::try_from(limit.as_i64()).unwrap_or(MAX_LIMIT))
.cloned()
.collect::<Vec<_>>();
@@ -1750,8 +1750,8 @@ impl RefundInterface for MockDb {
merchant_id: &common_utils::id_type::MerchantId,
refund_details: refunds::RefundListConstraints,
_storage_scheme: enums::MerchantStorageScheme,
- limit: i64,
- offset: i64,
+ limit: diesel_models::list::PageSize,
+ offset: diesel_models::list::PageOffset,
) -> CustomResult<Vec<diesel_models::refund::Refund>, errors::StorageError> {
let mut unique_connectors = HashSet::new();
let mut unique_connector_ids = HashSet::new();
@@ -1841,8 +1841,8 @@ impl RefundInterface for MockDb {
.filter(|refund| {
unique_statuses.is_empty() || unique_statuses.contains(&refund.refund_status)
})
- .skip(usize::try_from(offset).unwrap_or_default())
- .take(usize::try_from(limit).unwrap_or(MAX_LIMIT))
+ .skip(usize::try_from(offset.as_i64()).unwrap_or_default())
+ .take(usize::try_from(limit.as_i64()).unwrap_or(MAX_LIMIT))
.cloned()
.collect::<Vec<_>>();
diff --git a/crates/router/src/types/storage/dispute.rs b/crates/router/src/types/storage/dispute.rs
index d581c037a5..d65c03837b 100644
--- a/crates/router/src/types/storage/dispute.rs
+++ b/crates/router/src/types/storage/dispute.rs
@@ -31,16 +31,15 @@ impl DisputeDbExt for Dispute {
processor_merchant_id: &common_utils::id_type::MerchantId,
dispute_list_constraints: &disputes::DisputeListConstraints,
) -> CustomResult<Vec<Self>, errors::DatabaseError> {
- let mut filter = <Self as HasTable>::table()
- .filter(
- dsl::processor_merchant_id
- .eq(processor_merchant_id.to_owned())
- .or(dsl::processor_merchant_id
- .is_null()
- .and(dsl::merchant_id.eq(processor_merchant_id.to_owned()))),
- )
- .order(dsl::modified_at.desc())
- .into_boxed();
+ let mut filter = diesel_models::boxed_list_query!(
+ Dispute,
+ scope = dsl::processor_merchant_id
+ .eq(processor_merchant_id.to_owned())
+ .or(dsl::processor_merchant_id
+ .is_null()
+ .and(dsl::merchant_id.eq(processor_merchant_id.to_owned()))),
+ order = dsl::created_at.desc()
+ );
let mut search_by_payment_or_dispute_id = false;
@@ -97,12 +96,11 @@ impl DisputeDbExt for Dispute {
if let Some(merchant_connector_id) = &dispute_list_constraints.merchant_connector_id {
filter = filter.filter(dsl::merchant_connector_id.eq(merchant_connector_id.clone()))
}
- if let Some(limit) = dispute_list_constraints.limit {
- filter = filter.limit(limit.into());
- }
- if let Some(offset) = dispute_list_constraints.offset {
- filter = filter.offset(offset.into());
- }
+ let filter = diesel_models::list::apply_pagination(
+ filter,
+ dispute_list_constraints.limit,
+ dispute_list_constraints.offset,
+ );
logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg, _>(&filter).to_string());
@@ -121,17 +119,18 @@ impl DisputeDbExt for Dispute {
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
time_range: &common_utils::types::TimeRange,
) -> CustomResult<Vec<(common_enums::DisputeStatus, i64)>, errors::DatabaseError> {
- let mut query = <Self as HasTable>::table()
- .group_by(dsl::dispute_status)
- .select((dsl::dispute_status, diesel::dsl::count_star()))
- .filter(
- dsl::processor_merchant_id
- .eq(processor_merchant_id.to_owned())
- .or(dsl::processor_merchant_id
- .is_null()
- .and(dsl::merchant_id.eq(processor_merchant_id.to_owned()))),
- )
- .into_boxed();
+ let mut query = diesel_models::list::into_boxed_list(
+ <Self as HasTable>::table()
+ .group_by(dsl::dispute_status)
+ .select((dsl::dispute_status, diesel::dsl::count_star()))
+ .filter(
+ dsl::processor_merchant_id
+ .eq(processor_merchant_id.to_owned())
+ .or(dsl::processor_merchant_id
+ .is_null()
+ .and(dsl::merchant_id.eq(processor_merchant_id.to_owned()))),
+ ),
+ );
if let Some(profile_id) = profile_id_list {
query = query.filter(dsl::profile_id.eq_any(profile_id));
diff --git a/crates/router/src/types/storage/mandate.rs b/crates/router/src/types/storage/mandate.rs
index c575e433e5..ca874e7e92 100644
--- a/crates/router/src/types/storage/mandate.rs
+++ b/crates/router/src/types/storage/mandate.rs
@@ -25,10 +25,11 @@ impl MandateDbExt for Mandate {
merchant_id: &common_utils::id_type::MerchantId,
mandate_list_constraints: api_models::mandates::MandateListConstraints,
) -> CustomResult<Vec<Self>, errors::DatabaseError> {
- let mut filter = <Self as HasTable>::table()
- .filter(dsl::merchant_id.eq(merchant_id.to_owned()))
- .order(dsl::created_at.desc())
- .into_boxed();
+ let mut filter = diesel_models::list::into_boxed_list(
+ <Self as HasTable>::table()
+ .filter(dsl::merchant_id.eq(merchant_id.to_owned()))
+ .order(dsl::created_at.desc()),
+ );
if let Some(created_time) = mandate_list_constraints.created_time {
filter = filter.filter(dsl::created_at.eq(created_time));
diff --git a/crates/router/src/types/storage/payment_link.rs b/crates/router/src/types/storage/payment_link.rs
index 71e20ddc6c..dfd6dfefc7 100644
--- a/crates/router/src/types/storage/payment_link.rs
+++ b/crates/router/src/types/storage/payment_link.rs
@@ -28,16 +28,17 @@ impl PaymentLinkDbExt for PaymentLink {
processor_merchant_id: &common_utils::id_type::MerchantId,
payment_link_list_constraints: api_models::payments::PaymentLinkListConstraints,
) -> CustomResult<Vec<Self>, errors::DatabaseError> {
- let mut filter = <Self as HasTable>::table()
- .filter(
- dsl::processor_merchant_id
- .eq(processor_merchant_id.to_owned())
- .or(dsl::processor_merchant_id
- .is_null()
- .and(dsl::merchant_id.eq(processor_merchant_id.to_owned()))),
- )
- .order(dsl::created_at.desc())
- .into_boxed();
+ let mut filter = diesel_models::list::into_boxed_list(
+ <Self as HasTable>::table()
+ .filter(
+ dsl::processor_merchant_id
+ .eq(processor_merchant_id.to_owned())
+ .or(dsl::processor_merchant_id
+ .is_null()
+ .and(dsl::merchant_id.eq(processor_merchant_id.to_owned()))),
+ )
+ .order(dsl::created_at.desc()),
+ );
if let Some(created_time) = payment_link_list_constraints.created {
filter = filter.filter(dsl::created_at.eq(created_time));
diff --git a/crates/router/src/types/storage/refund.rs b/crates/router/src/types/storage/refund.rs
index 9f82b5517c..ad5afc0f37 100644
--- a/crates/router/src/types/storage/refund.rs
+++ b/crates/router/src/types/storage/refund.rs
@@ -9,6 +9,7 @@ use diesel_models::schema_v2::refund::dsl;
use diesel_models::{
enums::{Currency, RefundStatus},
errors,
+ list::{PageOffset, PageSize},
query::generics::db_metrics,
refund::Refund,
};
@@ -24,8 +25,8 @@ pub trait RefundDbExt: Sized {
conn: &PgPooledConn,
processor_merchant_id: &common_utils::id_type::MerchantId,
refund_list_details: &refunds::RefundListConstraints,
- limit: i64,
- offset: i64,
+ limit: PageSize,
+ offset: PageOffset,
) -> CustomResult<Vec<Self>, errors::DatabaseError>;
#[cfg(feature = "v2")]
@@ -33,8 +34,8 @@ pub trait RefundDbExt: Sized {
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
refund_list_details: refunds::RefundListConstraints,
- limit: i64,
- offset: i64,
+ limit: PageSize,
+ offset: PageOffset,
) -> CustomResult<Vec<Self>, errors::DatabaseError>;
#[cfg(feature = "v1")]
@@ -74,19 +75,18 @@ impl RefundDbExt for Refund {
conn: &PgPooledConn,
processor_merchant_id: &common_utils::id_type::MerchantId,
refund_list_details: &refunds::RefundListConstraints,
- limit: i64,
- offset: i64,
+ limit: PageSize,
+ offset: PageOffset,
) -> CustomResult<Vec<Self>, errors::DatabaseError> {
- let mut filter = <Self as HasTable>::table()
- .filter(
- dsl::processor_merchant_id
- .eq(processor_merchant_id.to_owned())
- .or(dsl::processor_merchant_id
- .is_null()
- .and(dsl::merchant_id.eq(processor_merchant_id.to_owned()))),
- )
- .order(dsl::modified_at.desc())
- .into_boxed();
+ let mut filter = diesel_models::boxed_list_query!(
+ Refund,
+ scope = dsl::processor_merchant_id
+ .eq(processor_merchant_id.to_owned())
+ .or(dsl::processor_merchant_id
+ .is_null()
+ .and(dsl::merchant_id.eq(processor_merchant_id.to_owned()))),
+ order = dsl::created_at.desc()
+ );
let mut search_by_pay_or_ref_id = false;
if let (Some(pid), Some(ref_id)) = (
@@ -94,47 +94,26 @@ impl RefundDbExt for Refund {
&refund_list_details.refund_id,
) {
search_by_pay_or_ref_id = true;
- filter = filter
- .filter(
- dsl::payment_id
- .eq(pid.to_owned())
- .or(dsl::refund_id.eq(ref_id.to_owned())),
- )
- .limit(limit)
- .offset(offset);
+ filter = filter.filter(
+ dsl::payment_id
+ .eq(pid.to_owned())
+ .or(dsl::refund_id.eq(ref_id.to_owned())),
+ );
};
if !search_by_pay_or_ref_id {
- match &refund_list_details.payment_id {
- Some(pid) => {
- filter = filter.filter(dsl::payment_id.eq(pid.to_owned()));
- }
- None => {
- filter = filter.limit(limit).offset(offset);
- }
- };
+ if let Some(pid) = &refund_list_details.payment_id {
+ filter = filter.filter(dsl::payment_id.eq(pid.to_owned()));
+ }
}
if !search_by_pay_or_ref_id {
- match &refund_list_details.refund_id {
- Some(ref_id) => {
- filter = filter.filter(dsl::refund_id.eq(ref_id.to_owned()));
- }
- None => {
- filter = filter.limit(limit).offset(offset);
- }
- };
- }
- match &refund_list_details.profile_id {
- Some(profile_id) => {
- filter = filter
- .filter(dsl::profile_id.eq_any(profile_id.to_owned()))
- .limit(limit)
- .offset(offset);
- }
- None => {
- filter = filter.limit(limit).offset(offset);
+ if let Some(ref_id) = &refund_list_details.refund_id {
+ filter = filter.filter(dsl::refund_id.eq(ref_id.to_owned()));
}
- };
+ }
+ if let Some(profile_id) = &refund_list_details.profile_id {
+ filter = filter.filter(dsl::profile_id.eq_any(profile_id.to_owned()));
+ }
if let Some(time_range) = refund_list_details.time_range {
filter = filter.filter(dsl::created_at.ge(time_range.start_time));
@@ -176,6 +155,8 @@ impl RefundDbExt for Refund {
filter = filter.filter(dsl::refund_status.eq_any(filter_refund_status.clone()));
}
+ let filter = diesel_models::list::apply_pagination(filter, limit, offset);
+
logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg, _>(&filter).to_string());
db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>(
@@ -192,13 +173,14 @@ impl RefundDbExt for Refund {
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
refund_list_details: refunds::RefundListConstraints,
- limit: i64,
- offset: i64,
+ limit: PageSize,
+ offset: PageOffset,
) -> CustomResult<Vec<Self>, errors::DatabaseError> {
- let mut filter = <Self as HasTable>::table()
- .filter(dsl::merchant_id.eq(merchant_id.to_owned()))
- .order(dsl::modified_at.desc())
- .into_boxed();
+ let mut filter = diesel_models::boxed_list_query!(
+ Refund,
+ scope = dsl::merchant_id.eq(merchant_id.to_owned()),
+ order = dsl::created_at.desc()
+ );
if let Some(payment_id) = &refund_list_details.payment_id {
filter = filter.filter(dsl::payment_id.eq(payment_id.to_owned()));
@@ -248,7 +230,7 @@ impl RefundDbExt for Refund {
filter = filter.filter(dsl::refund_status.eq_any(filter_refund_status));
}
- filter = filter.limit(limit).offset(offset);
+ let filter = diesel_models::list::apply_pagination(filter, limit, offset);
logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg, _>(&filter).to_string());
@@ -283,7 +265,7 @@ impl RefundDbExt for Refund {
.is_null()
.and(dsl::merchant_id.eq(processor_merchant_id.to_owned()))),
)
- .order(dsl::modified_at.desc())
+ .order(dsl::created_at.desc())
.filter(dsl::created_at.ge(start_time))
.filter(dsl::created_at.le(end_time));
@@ -331,16 +313,15 @@ impl RefundDbExt for Refund {
processor_merchant_id: &common_utils::id_type::MerchantId,
refund_list_details: &refunds::RefundListConstraints,
) -> CustomResult<i64, errors::DatabaseError> {
- let mut filter = <Self as HasTable>::table()
- .count()
- .filter(
+ let mut filter = diesel_models::list::into_boxed_list(
+ <Self as HasTable>::table().count().filter(
dsl::processor_merchant_id
.eq(processor_merchant_id.to_owned())
.or(dsl::processor_merchant_id
.is_null()
.and(dsl::merchant_id.eq(processor_merchant_id.to_owned()))),
- )
- .into_boxed();
+ ),
+ );
let mut search_by_pay_or_ref_id = false;
@@ -426,10 +407,11 @@ impl RefundDbExt for Refund {
merchant_id: &common_utils::id_type::MerchantId,
refund_list_details: refunds::RefundListConstraints,
) -> CustomResult<i64, errors::DatabaseError> {
- let mut filter = <Self as HasTable>::table()
- .count()
- .filter(dsl::merchant_id.eq(merchant_id.to_owned()))
- .into_boxed();
+ let mut filter = diesel_models::list::into_boxed_list(
+ <Self as HasTable>::table()
+ .count()
+ .filter(dsl::merchant_id.eq(merchant_id.to_owned())),
+ );
if let Some(payment_id) = &refund_list_details.payment_id {
filter = filter.filter(dsl::payment_id.eq(payment_id.to_owned()));
@@ -495,17 +477,18 @@ impl RefundDbExt for Refund {
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
time_range: &common_utils::types::TimeRange,
) -> CustomResult<Vec<(RefundStatus, i64)>, errors::DatabaseError> {
- let mut query = <Self as HasTable>::table()
- .group_by(dsl::refund_status)
- .select((dsl::refund_status, diesel::dsl::count_star()))
- .filter(
- dsl::processor_merchant_id
- .eq(processor_merchant_id.to_owned())
- .or(dsl::processor_merchant_id
- .is_null()
- .and(dsl::merchant_id.eq(processor_merchant_id.to_owned()))),
- )
- .into_boxed();
+ let mut query = diesel_models::list::into_boxed_list(
+ <Self as HasTable>::table()
+ .group_by(dsl::refund_status)
+ .select((dsl::refund_status, diesel::dsl::count_star()))
+ .filter(
+ dsl::processor_merchant_id
+ .eq(processor_merchant_id.to_owned())
+ .or(dsl::processor_merchant_id
+ .is_null()
+ .and(dsl::merchant_id.eq(processor_merchant_id.to_owned()))),
+ ),
+ );
if let Some(profile_id) = profile_id_list {
query = query.filter(dsl::profile_id.eq_any(profile_id));
diff --git a/crates/router/src/utils/user/dashboard_metadata.rs b/crates/router/src/utils/user/dashboard_metadata.rs
index 5b69eccb63..9a3d22b7e6 100644
--- a/crates/router/src/utils/user/dashboard_metadata.rs
+++ b/crates/router/src/utils/user/dashboard_metadata.rs
@@ -505,7 +505,7 @@ impl ForeignFrom<payments::PaymentListFilterConstraints> for PaymentListFilterCo
profile_id,
customer_id,
limit,
- offset,
+ offset: Some(offset),
amount_filter,
time_range,
connector,
@@ -573,7 +573,7 @@ impl ForeignFrom<PaymentListFilterConstraintsV1> for payments::PaymentListFilter
profile_id,
customer_id,
limit,
- offset,
+ offset: offset.unwrap_or_default(),
amount_filter,
time_range,
connector,
diff --git a/crates/storage_impl/src/payments/payment_intent.rs b/crates/storage_impl/src/payments/payment_intent.rs
index 205f307fe4..e09ce797e6 100644
--- a/crates/storage_impl/src/payments/payment_intent.rs
+++ b/crates/storage_impl/src/payments/payment_intent.rs
@@ -836,20 +836,17 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
//[#350]: Replace this with Boxable Expression and pass it into generic filter
// when https://github.com/rust-lang/rust/issues/52662 becomes stable
- let mut query = <DieselPaymentIntent as HasTable>::table()
- .filter(pi_dsl::processor_merchant_id.eq(processor_merchant_id.to_owned()))
- .order(pi_dsl::created_at.desc())
- .into_boxed();
+ let mut query = diesel_models::boxed_list_query!(
+ DieselPaymentIntent,
+ scope = pi_dsl::processor_merchant_id.eq(processor_merchant_id.to_owned()),
+ order = pi_dsl::created_at.desc()
+ );
match filters {
PaymentIntentFetchConstraints::Single { payment_intent_id } => {
query = query.filter(pi_dsl::payment_id.eq(payment_intent_id.to_owned()));
}
PaymentIntentFetchConstraints::List(params) => {
- if let Some(limit) = params.limit {
- query = query.limit(limit.into());
- }
-
if let Some(customer_id) = &params.customer_id {
query = query.filter(pi_dsl::customer_id.eq(customer_id.clone()));
}
@@ -893,8 +890,6 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
(None, None) => query,
};
- query = query.offset(params.offset.into());
-
query = match &params.currency {
Some(currency) => query.filter(pi_dsl::currency.eq_any(currency.clone())),
None => query,
@@ -912,6 +907,8 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
if let Some(status) = &params.status {
query = query.filter(pi_dsl::status.eq_any(status.clone()));
}
+
+ query = diesel_models::list::apply_pagination(query, params.limit, params.offset);
}
}
let keymanager_state = self
@@ -972,11 +969,12 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
let conn = connection::pg_connection_read(self).await?;
let conn = async_bb8_diesel::Connection::as_async_conn(&conn);
- let mut query = <DieselPaymentIntent as HasTable>::table()
- .group_by(pi_dsl::status)
- .select((pi_dsl::status, diesel::dsl::count_star()))
- .filter(pi_dsl::processor_merchant_id.eq(processor_merchant_id.to_owned()))
- .into_boxed();
+ let mut query = diesel_models::list::into_boxed_list(
+ <DieselPaymentIntent as HasTable>::table()
+ .group_by(pi_dsl::status)
+ .select((pi_dsl::status, diesel::dsl::count_star()))
+ .filter(pi_dsl::processor_merchant_id.eq(processor_merchant_id.to_owned())),
+ );
if let Some(profile_id) = profile_id_list {
query = query.filter(pi_dsl::profile_id.eq_any(profile_id));
@@ -1013,13 +1011,15 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
) -> 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 mut query = DieselPaymentIntent::table()
- .filter(pi_dsl::processor_merchant_id.eq(processor_merchant_id.to_owned()))
- .inner_join(
- payment_attempt_schema::table.on(pa_dsl::attempt_id.eq(pi_dsl::active_attempt_id)),
- )
- .filter(pa_dsl::processor_merchant_id.eq(processor_merchant_id.to_owned())) // Ensure merchant_ids match, as different merchants can share payment/attempt IDs.
- .into_boxed();
+ let mut query = diesel_models::list::into_boxed_list(
+ DieselPaymentIntent::table()
+ .filter(pi_dsl::processor_merchant_id.eq(processor_merchant_id.to_owned()))
+ .inner_join(
+ payment_attempt_schema::table
+ .on(pa_dsl::attempt_id.eq(pi_dsl::active_attempt_id)),
+ )
+ .filter(pa_dsl::processor_merchant_id.eq(processor_merchant_id.to_owned())),
+ );
query = match constraints {
PaymentIntentFetchConstraints::Single { payment_intent_id } => {
@@ -1036,21 +1036,13 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
by: SortBy::Desc,
} => query.order(pi_dsl::amount.desc()),
Order {
- on: SortOn::Created,
+ on: SortOn::Created | SortOn::Modified,
by: SortBy::Asc,
} => query.order(pi_dsl::created_at.asc()),
Order {
- on: SortOn::Created,
+ on: SortOn::Created | SortOn::Modified,
by: SortBy::Desc,
} => query.order(pi_dsl::created_at.desc()),
- Order {
- on: SortOn::Modified,
- by: SortBy::Asc,
- } => query.order(pi_dsl::modified_at.asc()),
- Order {
- on: SortOn::Modified,
- by: SortBy::Desc,
- } => query.order(pi_dsl::modified_at.desc()),
Order {
on: SortOn::AttemptCount,
by: SortBy::Asc,
@@ -1061,10 +1053,6 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
} => query.order(pi_dsl::attempt_count.desc()),
};
- if let Some(limit) = params.limit {
- query = query.limit(limit.into());
- }
-
if let Some(customer_id) = &params.customer_id {
query = query.filter(pi_dsl::customer_id.eq(customer_id.clone()));
}
@@ -1115,8 +1103,6 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
(None, None) => query,
};
- query = query.offset(params.offset.into());
-
query = match params.amount_filter {
Some(AmountFilter {
start_amount: Some(start),
@@ -1187,7 +1173,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
query = query.filter(pa_dsl::card_discovery.eq_any(card_discovery.clone()));
}
- query
+ diesel_models::list::apply_pagination(query, params.limit, params.offset)
}
};
@@ -1246,14 +1232,14 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
let conn = connection::pg_connection_read(self).await?;
let conn = async_bb8_diesel::Connection::as_async_conn(&conn);
- let mut query = DieselPaymentIntent::table()
- .filter(pi_dsl::merchant_id.eq(merchant_id.to_owned()))
- .left_join(
- payment_attempt_schema::table
- .on(pi_dsl::active_attempt_id.eq(pa_dsl::id.nullable())),
- )
- // Filtering on merchant_id for payment_attempt is not required for v2 as payment_attempt_ids are globally unique
- .into_boxed();
+ let mut query = diesel_models::list::into_boxed_list(
+ DieselPaymentIntent::table()
+ .filter(pi_dsl::merchant_id.eq(merchant_id.to_owned()))
+ .left_join(
+ payment_attempt_schema::table
+ .on(pi_dsl::active_attempt_id.eq(pa_dsl::id.nullable())),
+ ),
+ );
query = match constraints {
PaymentIntentFetchConstraints::List(params) => {
@@ -1267,21 +1253,13 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
by: SortBy::Desc,
} => query.order(pi_dsl::amount.desc()),
Order {
- on: SortOn::Created,
+ on: SortOn::Created | SortOn::Modified,
by: SortBy::Asc,
} => query.order(pi_dsl::created_at.asc()),
Order {
- on: SortOn::Created,
+ on: SortOn::Created | SortOn::Modified,
by: SortBy::Desc,
} => query.order(pi_dsl::created_at.desc()),
- Order {
- on: SortOn::Modified,
- by: SortBy::Asc,
- } => query.order(pi_dsl::modified_at.asc()),
- Order {
- on: SortOn::Modified,
- by: SortBy::Desc,
- } => query.order(pi_dsl::modified_at.desc()),
Order {
on: SortOn::AttemptCount,
by: SortBy::Asc,
@@ -1292,10 +1270,6 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
} => query.order(pi_dsl::attempt_count.desc()),
};
- if let Some(limit) = params.limit {
- query = query.limit(limit.into());
- }
-
if let Some(customer_id) = &params.customer_id {
query = query.filter(pi_dsl::customer_id.eq(customer_id.clone()));
}
@@ -1344,8 +1318,6 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
(None, None) => query,
};
- query = query.offset(params.offset.into());
-
query = match params.amount_filter {
Some(AmountFilter {
start_amount: Some(start),
@@ -1411,7 +1383,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
query = query.filter(pi_dsl::id.eq(payment_id.clone()));
}
- query
+ diesel_models::list::apply_pagination(query, params.limit, params.offset)
}
};
@@ -1468,11 +1440,12 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
) -> 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 = DieselPaymentIntent::table()
- .select(pi_dsl::active_attempt_id)
- .filter(pi_dsl::merchant_id.eq(merchant_id.to_owned()))
- .order(pi_dsl::created_at.desc())
- .into_boxed();
+ let mut query = diesel_models::list::into_boxed_list(
+ DieselPaymentIntent::table()
+ .select(pi_dsl::active_attempt_id)
+ .filter(pi_dsl::merchant_id.eq(merchant_id.to_owned()))
+ .order(pi_dsl::created_at.desc()),
+ );
query = match constraints {
PaymentIntentFetchConstraints::List(params) => {
@@ -1553,11 +1526,12 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
) -> 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 = DieselPaymentIntent::table()
- .select(pi_dsl::active_attempt_id)
- .filter(pi_dsl::processor_merchant_id.eq(processor_merchant_id.to_owned()))
- .order(pi_dsl::created_at.desc())
- .into_boxed();
+ let mut query = diesel_models::list::into_boxed_list(
+ DieselPaymentIntent::table()
+ .select(pi_dsl::active_attempt_id)
+ .filter(pi_dsl::processor_merchant_id.eq(processor_merchant_id.to_owned()))
+ .order(pi_dsl::created_at.desc()),
+ );
query = match constraints {
PaymentIntentFetchConstraints::Single { payment_intent_id } => {
diff --git a/crates/storage_impl/src/payouts/payouts.rs b/crates/storage_impl/src/payouts/payouts.rs
index cbff36e679..7ca109b127 100644
--- a/crates/storage_impl/src/payouts/payouts.rs
+++ b/crates/storage_impl/src/payouts/payouts.rs
@@ -493,20 +493,17 @@ impl<T: DatabaseStore> PayoutsInterface for crate::RouterStore<T> {
//[#350]: Replace this with Boxable Expression and pass it into generic filter
// when https://github.com/rust-lang/rust/issues/52662 becomes stable
- let mut query = <DieselPayouts as HasTable>::table()
- .filter(po_dsl::merchant_id.eq(merchant_id.to_owned()))
- .order(po_dsl::created_at.desc())
- .into_boxed();
+ let mut query = diesel_models::boxed_list_query!(
+ DieselPayouts,
+ scope = po_dsl::merchant_id.eq(merchant_id.to_owned()),
+ order = po_dsl::created_at.desc()
+ );
match filters {
PayoutFetchConstraints::Single { payout_id } => {
query = query.filter(po_dsl::payout_id.eq(payout_id.to_owned()));
}
PayoutFetchConstraints::List(params) => {
- if let Some(limit) = params.limit {
- query = query.limit(limit.into());
- }
-
if let Some(customer_id) = &params.customer_id {
query = query.filter(po_dsl::customer_id.eq(customer_id.clone()));
}
@@ -548,8 +545,6 @@ impl<T: DatabaseStore> PayoutsInterface for crate::RouterStore<T> {
(None, None) => query,
};
- query = query.offset(params.offset.into());
-
if let Some(currency) = &params.currency {
query = query.filter(po_dsl::destination_currency.eq_any(currency.clone()));
}
@@ -557,6 +552,8 @@ impl<T: DatabaseStore> PayoutsInterface for crate::RouterStore<T> {
if let Some(status) = &params.status {
query = query.filter(po_dsl::status.eq_any(status.clone()));
}
+
+ query = diesel_models::list::apply_pagination(query, params.limit, params.offset);
}
}
@@ -597,33 +594,30 @@ impl<T: DatabaseStore> PayoutsInterface for crate::RouterStore<T> {
> {
let conn = connection::pg_connection_read(self).await?;
let conn = async_bb8_diesel::Connection::as_async_conn(&conn);
- let mut query = DieselPayouts::table()
- .inner_join(
- diesel_models::schema::payout_attempt::table
- .on(poa_dsl::payout_id.eq(po_dsl::payout_id)),
- )
- .left_join(
- diesel_models::schema::customers::table
- .on(cust_dsl::customer_id.nullable().eq(po_dsl::customer_id)),
- )
- .filter(cust_dsl::merchant_id.eq(merchant_id.to_owned()))
- .left_outer_join(
- diesel_models::schema::address::table
- .on(add_dsl::address_id.nullable().eq(po_dsl::address_id)),
- )
- .filter(po_dsl::merchant_id.eq(merchant_id.to_owned()))
- .order(po_dsl::created_at.desc())
- .into_boxed();
+ let mut query = diesel_models::list::into_boxed_list(
+ DieselPayouts::table()
+ .inner_join(
+ diesel_models::schema::payout_attempt::table
+ .on(poa_dsl::payout_id.eq(po_dsl::payout_id)),
+ )
+ .left_join(
+ diesel_models::schema::customers::table
+ .on(cust_dsl::customer_id.nullable().eq(po_dsl::customer_id)),
+ )
+ .filter(cust_dsl::merchant_id.eq(merchant_id.to_owned()))
+ .left_outer_join(
+ diesel_models::schema::address::table
+ .on(add_dsl::address_id.nullable().eq(po_dsl::address_id)),
+ )
+ .filter(po_dsl::merchant_id.eq(merchant_id.to_owned()))
+ .order(po_dsl::created_at.desc()),
+ );
query = match filters {
PayoutFetchConstraints::Single { payout_id } => {
query.filter(po_dsl::payout_id.eq(payout_id.to_owned()))
}
PayoutFetchConstraints::List(params) => {
- if let Some(limit) = params.limit {
- query = query.limit(limit.into());
- }
-
if let Some(customer_id) = &params.customer_id {
query = query.filter(po_dsl::customer_id.eq(customer_id.clone()));
}
@@ -673,8 +667,6 @@ impl<T: DatabaseStore> PayoutsInterface for crate::RouterStore<T> {
(None, None) => query,
};
- query = query.offset(params.offset.into());
-
if let Some(currency) = &params.currency {
query = query.filter(po_dsl::destination_currency.eq_any(currency.clone()));
}
@@ -705,7 +697,7 @@ impl<T: DatabaseStore> PayoutsInterface for crate::RouterStore<T> {
_ => query,
};
- query
+ diesel_models::list::apply_pagination(query, params.limit, params.offset)
}
};
@@ -826,20 +818,21 @@ impl<T: DatabaseStore> PayoutsInterface for crate::RouterStore<T> {
) -> 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 = DieselPayouts::table()
- .inner_join(
- diesel_models::schema::payout_attempt::table
- .on(poa_dsl::payout_id.eq(po_dsl::payout_id)),
- )
- .left_join(
- diesel_models::schema::customers::table
- .on(cust_dsl::customer_id.nullable().eq(po_dsl::customer_id)),
- )
- .select(po_dsl::payout_id)
- .filter(cust_dsl::merchant_id.eq(merchant_id.to_owned()))
- .filter(po_dsl::merchant_id.eq(merchant_id.to_owned()))
- .order(po_dsl::created_at.desc())
- .into_boxed();
+ let mut query = diesel_models::list::into_boxed_list(
+ DieselPayouts::table()
+ .inner_join(
+ diesel_models::schema::payout_attempt::table
+ .on(poa_dsl::payout_id.eq(po_dsl::payout_id)),
+ )
+ .left_join(
+ diesel_models::schema::customers::table
+ .on(cust_dsl::customer_id.nullable().eq(po_dsl::customer_id)),
+ )
+ .select(po_dsl::payout_id)
+ .filter(cust_dsl::merchant_id.eq(merchant_id.to_owned()))
+ .filter(po_dsl::merchant_id.eq(merchant_id.to_owned()))
+ .order(po_dsl::created_at.desc()),
+ );
query = match constraints {
PayoutFetchConstraints::Single { payout_id } => {
@@ -920,11 +913,12 @@ impl<T: DatabaseStore> PayoutsInterface for crate::RouterStore<T> {
let conn = connection::pg_connection_read(self).await?;
let conn = async_bb8_diesel::Connection::as_async_conn(&conn);
- let mut query = <DieselPayouts as HasTable>::table()
- .group_by(po_dsl::status)
- .select((po_dsl::status, diesel::dsl::count_star()))
- .filter(po_dsl::merchant_id.eq(merchant_id.to_owned()))
- .into_boxed();
+ let mut query = diesel_models::list::into_boxed_list(
+ <DieselPayouts as HasTable>::table()
+ .group_by(po_dsl::status)
+ .select((po_dsl::status, diesel::dsl::count_star()))
+ .filter(po_dsl::merchant_id.eq(merchant_id.to_owned())),
+ );
if let Some(profile_id) = profile_id_list {
query = query.filter(po_dsl::profile_id.eq_any(profile_id));