-
-
Notifications
You must be signed in to change notification settings - Fork 530
/
Copy pathpaginator.rs
385 lines (321 loc) Β· 12.2 KB
/
paginator.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
use crate::{Database, QueryErr, SelectorTrait};
use async_stream::stream;
use futures::Stream;
use sea_query::{Alias, Expr, SelectStatement};
use std::{marker::PhantomData, pin::Pin};
pub type PinBoxStream<'db, Item> = Pin<Box<dyn Stream<Item = Item> + 'db>>;
#[derive(Clone, Debug)]
pub struct Paginator<'db, S>
where
S: SelectorTrait + 'db,
{
pub(crate) query: SelectStatement,
pub(crate) page: usize,
pub(crate) page_size: usize,
pub(crate) db: &'db Database,
pub(crate) selector: PhantomData<S>,
}
impl<'db, S> Paginator<'db, S>
where
S: SelectorTrait + 'db,
{
/// Fetch a specific page
pub async fn fetch_page(&self, page: usize) -> Result<Vec<S::Item>, QueryErr> {
let query = self
.query
.clone()
.limit(self.page_size as u64)
.offset((self.page_size * page) as u64)
.to_owned();
let builder = self.db.get_query_builder_backend();
let stmt = builder.build_select_statement(&query);
let rows = self.db.get_connection().query_all(stmt).await?;
let mut buffer = Vec::with_capacity(rows.len());
for row in rows.into_iter() {
// TODO: Error handling
buffer.push(S::from_raw_query_result(row).map_err(|_e| QueryErr)?);
}
Ok(buffer)
}
/// Fetch the current page
pub async fn fetch(&self) -> Result<Vec<S::Item>, QueryErr> {
self.fetch_page(self.page).await
}
/// Get the total number of pages
pub async fn num_pages(&self) -> Result<usize, QueryErr> {
let builder = self.db.get_query_builder_backend();
let stmt = builder.build_select_statement(
SelectStatement::new()
.expr(Expr::cust("COUNT(*) AS num_rows"))
.from_subquery(
self.query.clone().reset_limit().reset_offset().to_owned(),
Alias::new("sub_query"),
),
);
let result = match self.db.get_connection().query_one(stmt).await? {
Some(res) => res,
None => return Ok(0),
};
let num_rows = result
.try_get::<i32>("", "num_rows")
.map_err(|_e| QueryErr)? as usize;
let num_pages = (num_rows / self.page_size) + (num_rows % self.page_size > 0) as usize;
Ok(num_pages)
}
/// Increment the page counter
pub fn next(&mut self) {
self.page += 1;
}
/// Get current page number
pub fn cur_page(&self) -> usize {
self.page
}
/// Fetch one page and increment the page counter
pub async fn fetch_and_next(&mut self) -> Result<Option<Vec<S::Item>>, QueryErr> {
let vec = self.fetch().await?;
self.next();
let opt = if !vec.is_empty() { Some(vec) } else { None };
Ok(opt)
}
/// Convert self into an async stream
pub fn into_stream(mut self) -> PinBoxStream<'db, Result<Vec<S::Item>, QueryErr>> {
Box::pin(stream! {
loop {
if let Some(vec) = self.fetch_and_next().await? {
yield Ok(vec);
} else {
break
}
}
})
}
}
#[cfg(test)]
#[cfg(feature = "mock")]
mod tests {
use crate::tests_cfg::fruit;
use crate::{
entity::*, Database, DatabaseConnection, MockDatabase, MockRow, QueryErr, Statement,
};
use futures::TryStreamExt;
use sea_query::{Alias, Expr, PostgresQueryBuilder, SelectStatement, Value};
fn setup() -> (Database, Vec<Vec<fruit::Model>>) {
// TODO: auto impl
impl From<fruit::Model> for MockRow {
fn from(model: fruit::Model) -> Self {
let map = maplit::btreemap! {
"id" => Into::<Value>::into(model.id),
"name" => Into::<Value>::into(model.name),
"cake_id" => Into::<Value>::into(model.cake_id),
};
map.into()
}
}
let page1 = vec![
fruit::Model {
id: 1,
name: "Blueberry".into(),
cake_id: Some(1),
},
fruit::Model {
id: 2,
name: "Rasberry".into(),
cake_id: Some(1),
},
];
let page2 = vec![fruit::Model {
id: 3,
name: "Strawberry".into(),
cake_id: Some(2),
}];
let db = MockDatabase::new()
.append_query_results(vec![
// TODO: take any IntoMockRow
page1
.clone()
.into_iter()
.map(|model| Into::<MockRow>::into(model))
.collect(),
page2
.clone()
.into_iter()
.map(|model| Into::<MockRow>::into(model))
.collect(),
Vec::<fruit::Model>::new()
.into_iter()
.map(|model| Into::<MockRow>::into(model))
.collect(),
])
.into_database();
(db, vec![page1, page2, vec![]])
}
fn setup_num_rows() -> (Database, i32) {
let num_rows = 3;
let db = MockDatabase::new()
.append_query_results(vec![vec![maplit::btreemap! {
"num_rows" => Into::<Value>::into(num_rows),
}
.into()]])
.into_database();
(db, num_rows)
}
fn match_transaction_log(db: Database, selects: Vec<SelectStatement>) {
let mock_conn = match db.get_connection() {
DatabaseConnection::MockDatabaseConnection(mock_conn) => mock_conn,
_ => unreachable!(),
};
let mut mocker = mock_conn.mocker.lock().unwrap();
for (i, stmt) in mocker.into_transaction_log().into_iter().enumerate() {
let query_builder = db.get_query_builder_backend();
let statement = query_builder.build_select_statement(&selects[i]);
assert_eq!(stmt.to_string(), statement.to_string());
}
}
#[async_std::test]
async fn fetch_page() -> Result<(), QueryErr> {
let (db, pages) = setup();
let paginator = fruit::Entity::find().paginate(&db, 2);
assert_eq!(paginator.fetch_page(0).await?, pages[0].clone());
assert_eq!(paginator.fetch_page(1).await?, pages[1].clone());
assert_eq!(paginator.fetch_page(2).await?, pages[2].clone());
let select = SelectStatement::new()
.exprs(vec![
Expr::tbl(fruit::Entity, fruit::Column::Id),
Expr::tbl(fruit::Entity, fruit::Column::Name),
Expr::tbl(fruit::Entity, fruit::Column::CakeId),
])
.from(fruit::Entity)
.to_owned();
let transaction_log = vec![
select.clone().offset(0).limit(2).to_owned(),
select.clone().offset(2).limit(2).to_owned(),
select.clone().offset(4).limit(2).to_owned(),
];
match_transaction_log(db, transaction_log);
Ok(())
}
#[async_std::test]
async fn fetch() -> Result<(), QueryErr> {
let (db, pages) = setup();
let mut paginator = fruit::Entity::find().paginate(&db, 2);
assert_eq!(paginator.fetch().await?, pages[0].clone());
paginator.next();
assert_eq!(paginator.fetch().await?, pages[1].clone());
paginator.next();
assert_eq!(paginator.fetch().await?, pages[2].clone());
let select = SelectStatement::new()
.exprs(vec![
Expr::tbl(fruit::Entity, fruit::Column::Id),
Expr::tbl(fruit::Entity, fruit::Column::Name),
Expr::tbl(fruit::Entity, fruit::Column::CakeId),
])
.from(fruit::Entity)
.to_owned();
let transaction_log = vec![
select.clone().offset(0).limit(2).to_owned(),
select.clone().offset(2).limit(2).to_owned(),
select.clone().offset(4).limit(2).to_owned(),
];
match_transaction_log(db, transaction_log);
Ok(())
}
#[async_std::test]
async fn num_pages() -> Result<(), QueryErr> {
let (db, num_rows) = setup_num_rows();
let num_rows = num_rows as usize;
let page_size = 2_usize;
let num_pages = (num_rows / page_size) + (num_rows % page_size > 0) as usize;
let paginator = fruit::Entity::find().paginate(&db, page_size);
assert_eq!(paginator.num_pages().await?, num_pages);
let sub_query = SelectStatement::new()
.exprs(vec![
Expr::tbl(fruit::Entity, fruit::Column::Id),
Expr::tbl(fruit::Entity, fruit::Column::Name),
Expr::tbl(fruit::Entity, fruit::Column::CakeId),
])
.from(fruit::Entity)
.to_owned();
let select = SelectStatement::new()
.expr(Expr::cust("COUNT(*) AS num_rows"))
.from_subquery(sub_query, Alias::new("sub_query"))
.to_owned();
let transaction_log = vec![select];
match_transaction_log(db, transaction_log);
Ok(())
}
#[async_std::test]
async fn next_and_cur_page() -> Result<(), QueryErr> {
let (db, _) = setup();
let mut paginator = fruit::Entity::find().paginate(&db, 2);
assert_eq!(paginator.cur_page(), 0);
paginator.next();
assert_eq!(paginator.cur_page(), 1);
paginator.next();
assert_eq!(paginator.cur_page(), 2);
let select = SelectStatement::new()
.exprs(vec![
Expr::tbl(fruit::Entity, fruit::Column::Id),
Expr::tbl(fruit::Entity, fruit::Column::Name),
Expr::tbl(fruit::Entity, fruit::Column::CakeId),
])
.from(fruit::Entity)
.to_owned();
let transaction_log = vec![
select.clone().offset(0).limit(2).to_owned(),
select.clone().offset(2).limit(2).to_owned(),
select.clone().offset(4).limit(2).to_owned(),
];
match_transaction_log(db, transaction_log);
Ok(())
}
#[async_std::test]
async fn fetch_and_next() -> Result<(), QueryErr> {
let (db, pages) = setup();
let mut paginator = fruit::Entity::find().paginate(&db, 2);
assert_eq!(paginator.cur_page(), 0);
assert_eq!(paginator.fetch_and_next().await?, Some(pages[0].clone()));
assert_eq!(paginator.cur_page(), 1);
assert_eq!(paginator.fetch_and_next().await?, Some(pages[1].clone()));
assert_eq!(paginator.cur_page(), 2);
assert_eq!(paginator.fetch_and_next().await?, None);
let select = SelectStatement::new()
.exprs(vec![
Expr::tbl(fruit::Entity, fruit::Column::Id),
Expr::tbl(fruit::Entity, fruit::Column::Name),
Expr::tbl(fruit::Entity, fruit::Column::CakeId),
])
.from(fruit::Entity)
.to_owned();
let transaction_log = vec![
select.clone().offset(0).limit(2).to_owned(),
select.clone().offset(2).limit(2).to_owned(),
select.clone().offset(4).limit(2).to_owned(),
];
match_transaction_log(db, transaction_log);
Ok(())
}
#[async_std::test]
async fn into_stream() -> Result<(), QueryErr> {
let (db, pages) = setup();
let mut fruit_stream = fruit::Entity::find().paginate(&db, 2).into_stream();
assert_eq!(fruit_stream.try_next().await?, Some(pages[0].clone()));
assert_eq!(fruit_stream.try_next().await?, Some(pages[1].clone()));
assert_eq!(fruit_stream.try_next().await?, None);
drop(fruit_stream);
let select = SelectStatement::new()
.exprs(vec![
Expr::tbl(fruit::Entity, fruit::Column::Id),
Expr::tbl(fruit::Entity, fruit::Column::Name),
Expr::tbl(fruit::Entity, fruit::Column::CakeId),
])
.from(fruit::Entity)
.to_owned();
let transaction_log = vec![
select.clone().offset(0).limit(2).to_owned(),
select.clone().offset(2).limit(2).to_owned(),
select.clone().offset(4).limit(2).to_owned(),
];
match_transaction_log(db, transaction_log);
Ok(())
}
}