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::{any_struct::FromAnyRow, database::Connection, model::Model, query_builder::QueryBuilder, AnyImpl};
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
51/// A wrapper for paginated results.
52///
53/// Contains the data items and metadata about the pagination state (total, pages, etc.).
54/// This struct is `Serialize`d to JSON for API responses.
55#[derive(Debug, Clone, Serialize, Deserialize)]
56pub struct Paginated<T> {
57 /// The list of items for the current page.
58 pub data: Vec<T>,
59 /// The total number of items matching the query.
60 pub total: i64,
61 /// The current page number (0-indexed).
62 pub page: usize,
63 /// The number of items per page.
64 pub limit: usize,
65 /// The total number of pages.
66 pub total_pages: i64,
67}
68
69fn default_limit() -> usize {
70 10
71}
72
73impl Default for Pagination {
74 fn default() -> Self {
75 Self { page: 0, limit: 10 }
76 }
77}
78
79impl Pagination {
80 /// Creates a new Pagination instance.
81 pub fn new(page: usize, limit: usize) -> Self {
82 Self { page, limit }
83 }
84
85 /// Applies the pagination to a `QueryBuilder`.
86 ///
87 /// This method sets the `limit` and `offset` of the query builder
88 /// based on the pagination parameters.
89 ///
90 /// # Arguments
91 ///
92 /// * `query` - The `QueryBuilder` to paginate
93 ///
94 /// # Returns
95 ///
96 /// The modified `QueryBuilder`
97 pub fn apply<'a, T, E>(self, query: QueryBuilder<'a, T, E>) -> QueryBuilder<'a, T, E>
98 where
99 T: Model + Send + Sync + Unpin,
100 E: Connection + Send,
101 {
102 query.limit(self.limit).offset(self.page * self.limit)
103 }
104
105 /// Executes the query and returns a `Paginated<T>` result with metadata.
106 ///
107 /// This method performs two database queries:
108 /// 1. A `COUNT(*)` query to get the total number of records matching the filters.
109 /// 2. The actual `SELECT` query with `LIMIT` and `OFFSET` applied.
110 ///
111 /// # Type Parameters
112 ///
113 /// * `T` - The Model type.
114 /// * `E` - The connection type (Database or Transaction).
115 /// * `R` - The result type (usually same as T, but can be a DTO/Projection).
116 ///
117 /// # Returns
118 ///
119 /// * `Ok(Paginated<R>)` - The paginated results.
120 /// * `Err(sqlx::Error)` - Database error.
121 ///
122 /// # Example
123 ///
124 /// ```rust,ignore
125 /// let pagination = Pagination::new(0, 10);
126 /// let result = pagination.paginate(db.model::<User>()).await?;
127 ///
128 /// println!("Total users: {}", result.total);
129 /// for user in result.data {
130 /// println!("User: {}", user.username);
131 /// }
132 /// ```
133 pub async fn paginate<'a, T, E, R>(self, mut query: QueryBuilder<'a, T, E>) -> Result<Paginated<R>, sqlx::Error>
134 where
135 T: Model + Send + Sync + Unpin,
136 E: Connection + Send,
137 R: FromAnyRow + AnyImpl + Send + Unpin,
138 {
139 // 1. Prepare COUNT query
140 // We temporarily replace selected columns with COUNT(*) and remove order/limit/offset
141 let original_select = query.select_columns.clone();
142 let original_order = query.order_clauses.clone();
143 let _original_limit = query.limit;
144 let _original_offset = query.offset;
145
146 query.select_columns = vec!["COUNT(*)".to_string()];
147 query.order_clauses.clear();
148 query.limit = None;
149 query.offset = None;
150
151 // 2. Generate and Execute Count SQL
152 // We cannot use query.scalar() easily because it consumes self.
153 // We use query.to_sql() and construct a manual query execution using the builder's state.
154
155 let count_sql = query.to_sql();
156
157 // We need to re-bind arguments. This logic mirrors QueryBuilder::scan
158 let mut args = sqlx::any::AnyArguments::default();
159 let mut arg_counter = 1;
160
161 // Re-bind arguments for count query
162 // Note: We access internal fields of QueryBuilder. This assumes this module is part of the crate.
163 // If WHERE clauses are complex, this manual reconstruction is necessary.
164 let mut dummy_query = String::new(); // Just to satisfy the closure signature
165 for clause in &query.where_clauses {
166 clause(&mut dummy_query, &mut args, &query.driver, &mut arg_counter);
167 }
168 if !query.having_clauses.is_empty() {
169 for clause in &query.having_clauses {
170 clause(&mut dummy_query, &mut args, &query.driver, &mut arg_counter);
171 }
172 }
173
174 // Execute count query
175 let count_row = sqlx::query_with::<_, _>(&count_sql, args).fetch_one(query.tx.executor()).await?;
176
177 let total: i64 = count_row.try_get(0)?;
178
179 // 3. Restore Query State for Data Fetch
180 query.select_columns = original_select;
181 query.order_clauses = original_order;
182 // Apply Pagination
183 query.limit = Some(self.limit);
184 query.offset = Some(self.page * self.limit);
185
186 // 4. Execute Data Query
187 // Now we can consume the builder with scan()
188 let data = query.scan::<R>().await?;
189
190 // 5. Calculate Metadata
191 let total_pages = (total as f64 / self.limit as f64).ceil() as i64;
192
193 Ok(Paginated { data, total, page: self.page, limit: self.limit, total_pages })
194 }
195}