bottle_orm/pagination.rs
1//! # Pagination Module
2//!
3//! This module provides a standard `Pagination` struct that is compatible with
4//! web frameworks like `axum`, `actix-web`, and `serde`. It allows for easy
5//! extraction of pagination parameters from HTTP requests and application
6//! to `QueryBuilder` instances.
7//!
8//! ## Features
9//!
10//! - **Serde Compatibility**: derives `Serialize` and `Deserialize`
11//! - **Query Integration**: `apply` method to automatically paginate queries
12//! - **Defaults**: sane defaults (page 0, limit 10)
13//!
14//! ## Example with Axum
15//!
16//! ```rust,ignore
17//! use axum::{extract::Query, Json};
18//! use bottle_orm::{Database, pagination::Pagination};
19//!
20//! async fn list_users(
21//! State(db): State<Database>,
22//! Query(pagination): Query<Pagination>
23//! ) -> Json<Vec<User>> {
24//! let users = pagination.apply(db.model::<User>())
25//! .scan()
26//! .await
27//! .unwrap();
28//!
29//! Json(users)
30//! }
31//! ```
32
33use crate::{AnyImpl, any_struct::FromAnyRow, database::Connection, model::Model, query_builder::QueryBuilder};
34use serde::{Deserialize, Serialize};
35use sqlx::Row;
36
37/// A standard pagination structure.
38///
39/// Can be deserialized from query parameters (e.g., `?page=1&limit=20`).
40#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
41pub struct Pagination {
42 /// The page number (0-indexed). Default: 0.
43 #[serde(default)]
44 pub page: usize,
45
46 /// The number of items per page. Default: 10.
47 #[serde(default = "default_limit")]
48 pub limit: usize,
49
50 /// The maximum allowed limit for pagination to prevent large result sets.
51 /// If the requested `limit` exceeds `max_limit`, it will be capped (default: 100).
52 pub max_limit: usize,
53}
54
55/// A wrapper for paginated results.
56///
57/// Contains the data items and metadata about the pagination state (total, pages, etc.).
58/// This struct is `Serialize`d to JSON for API responses.
59#[derive(Debug, Clone, Serialize, Deserialize)]
60pub struct Paginated<T> {
61 /// The list of items for the current page.
62 pub data: Vec<T>,
63 /// The total number of items matching the query.
64 pub total: i64,
65 /// The current page number (0-indexed).
66 pub page: usize,
67 /// The number of items per page.
68 pub limit: usize,
69 /// The total number of pages.
70 pub total_pages: i64,
71}
72
73fn default_limit() -> usize {
74 10
75}
76
77impl Default for Pagination {
78 fn default() -> Self {
79 Self { page: 0, limit: 10, max_limit: 100 }
80 }
81}
82
83impl Pagination {
84 /// Creates a new Pagination instance with a specified max_limit.
85 ///
86 /// If `limit` is greater than `max_limit`, it defaults to 10.
87 pub fn new(page: usize, mut limit: usize, max_limit: usize) -> Self {
88 if limit > max_limit {
89 limit = 10;
90 }
91 Self { page, limit, max_limit }
92 }
93
94 /// Applies the pagination to a `QueryBuilder`.
95 ///
96 /// This method sets the `limit` and `offset` of the query builder
97 /// based on the pagination parameters. It also enforces the `max_limit`
98 /// check before applying the limit.
99 ///
100 /// # Arguments
101 ///
102 /// * `query` - The `QueryBuilder` to paginate
103 ///
104 /// # Returns
105 ///
106 /// The modified `QueryBuilder`
107 pub fn apply<'a, T, E>(mut self, query: QueryBuilder<'a, T, E>) -> QueryBuilder<'a, T, E>
108 where
109 T: Model + Send + Sync + Unpin,
110 E: Connection + Send,
111 {
112 // Enforce max_limit again during application to ensure safety
113 if self.limit > self.max_limit {
114 self.limit = 10;
115 }
116 query.limit(self.limit).offset(self.page * self.limit)
117 }
118
119 /// Executes the query and returns a `Paginated<T>` result with metadata.
120 ///
121 /// This method performs two database queries:
122 /// 1. A `COUNT(*)` query to get the total number of records matching the filters.
123 /// 2. The actual `SELECT` query with `LIMIT` and `OFFSET` applied.
124 ///
125 /// # Type Parameters
126 ///
127 /// * `T` - The Model type.
128 /// * `E` - The connection type (Database or Transaction).
129 /// * `R` - The result type (usually same as T, but can be a DTO/Projection).
130 ///
131 /// # Returns
132 ///
133 /// * `Ok(Paginated<R>)` - The paginated results.
134 /// * `Err(sqlx::Error)` - Database error.
135 ///
136 /// # Example
137 ///
138 /// ```rust,ignore
139 /// let pagination = Pagination::new(0, 10);
140 /// let result = pagination.paginate(db.model::<User>()).await?;
141 ///
142 /// println!("Total users: {}", result.total);
143 /// for user in result.data {
144 /// println!("User: {}", user.username);
145 /// }
146 /// ```
147 pub async fn paginate<'a, T, E, R>(self, mut query: QueryBuilder<'a, T, E>) -> Result<Paginated<R>, sqlx::Error>
148 where
149 T: Model + Send + Sync + Unpin,
150 E: Connection + Send,
151 R: FromAnyRow + AnyImpl + Send + Unpin,
152 {
153 // 1. Prepare COUNT query
154 // We temporarily replace selected columns with COUNT(*) and remove order/limit/offset
155 let original_select = query.select_columns.clone();
156 let original_order = query.order_clauses.clone();
157 let _original_limit = query.limit;
158 let _original_offset = query.offset;
159
160 query.select_columns = vec!["COUNT(*)".to_string()];
161 query.order_clauses.clear();
162 query.limit = None;
163 query.offset = None;
164
165 // 2. Generate and Execute Count SQL
166 // We cannot use query.scalar() easily because it consumes self.
167 // We use query.to_sql() and construct a manual query execution using the builder's state.
168
169 let count_sql = query.to_sql();
170
171 // We need to re-bind arguments. This logic mirrors QueryBuilder::scan
172 let mut args = sqlx::any::AnyArguments::default();
173 let mut arg_counter = 1;
174
175 // Re-bind arguments for count query
176 // Note: We access internal fields of QueryBuilder. This assumes this module is part of the crate.
177 // If WHERE clauses are complex, this manual reconstruction is necessary.
178 let mut dummy_query = String::new(); // Just to satisfy the closure signature
179 for clause in &query.where_clauses {
180 clause(&mut dummy_query, &mut args, &query.driver, &mut arg_counter);
181 }
182 if !query.having_clauses.is_empty() {
183 for clause in &query.having_clauses {
184 clause(&mut dummy_query, &mut args, &query.driver, &mut arg_counter);
185 }
186 }
187
188 // Execute count query
189 let count_row = sqlx::query_with::<_, _>(&count_sql, args).fetch_one(query.tx.executor()).await?;
190
191 let total: i64 = count_row.try_get(0)?;
192
193 // 3. Restore Query State for Data Fetch
194 query.select_columns = original_select;
195 query.order_clauses = original_order;
196 // Apply Pagination
197 query.limit = Some(self.limit);
198 query.offset = Some(self.page * self.limit);
199
200 // 4. Execute Data Query
201 // Now we can consume the builder with scan()
202 let data = query.scan::<R>().await?;
203
204 // 5. Calculate Metadata
205 let total_pages = (total as f64 / self.limit as f64).ceil() as i64;
206
207 Ok(Paginated { data, total, page: self.page, limit: self.limit, total_pages })
208 }
209}