Skip to content

Commit ecb9d79

Browse files
committed
feat: allow an easier use of limit/offset
1 parent a321f0a commit ecb9d79

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed

src/executor/limiter.rs

+64
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
use migration::SelectStatement;
2+
use sea_orm::{
3+
ConnectionTrait, DbErr, EntityTrait, FromQueryResult, Paginator, PaginatorTrait, QuerySelect,
4+
Select, SelectModel, Selector, SelectorTrait,
5+
};
6+
use std::future::Future;
7+
use std::marker::PhantomData;
8+
use std::num::NonZeroU64;
9+
10+
pub struct Limiter<'db, C, S>
11+
where
12+
C: ConnectionTrait,
13+
S: SelectorTrait + 'db,
14+
{
15+
db: &'db C,
16+
selector: Selector<S>,
17+
paginator: Paginator<'db, C, S>,
18+
}
19+
20+
impl<'db, C, S> Limiter<'db, C, S>
21+
where
22+
C: ConnectionTrait,
23+
S: SelectorTrait + 'db,
24+
{
25+
pub async fn fetch(self) -> Result<Vec<S::Item>, DbErr> {
26+
self.selector.all(self.db).await
27+
}
28+
29+
pub async fn total(&self) -> Result<u64, DbErr> {
30+
self.paginator.num_items().await
31+
}
32+
}
33+
34+
pub trait LimiterTrait<'db, C>
35+
where
36+
C: ConnectionTrait,
37+
{
38+
type Selector: SelectorTrait + 'db;
39+
40+
fn limiting(self, db: &'db C, offset: u64, limit: u64) -> Limiter<'db, C, Self::Selector>;
41+
}
42+
43+
impl<'db, C, M, E> LimiterTrait<'db, C> for Select<E>
44+
where
45+
C: ConnectionTrait,
46+
E: EntityTrait<Model = M>,
47+
M: FromQueryResult + Sized + Send + Sync + 'db,
48+
{
49+
type Selector = SelectModel<M>;
50+
51+
fn limiting(self, db: &'db C, offset: u64, limit: u64) -> Limiter<'db, C, Self::Selector> {
52+
let selector = self
53+
.clone()
54+
.limit(NonZeroU64::new(limit).map(|limit| limit.get()))
55+
.offset(NonZeroU64::new(limit).map(|limit| limit.get()))
56+
.into_model();
57+
58+
Limiter {
59+
db,
60+
paginator: self.clone().paginate(db, 1),
61+
selector,
62+
}
63+
}
64+
}

src/executor/mod.rs

+2
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ mod cursor;
22
mod delete;
33
mod execute;
44
mod insert;
5+
mod limiter;
56
mod paginator;
67
mod query;
78
mod select;
@@ -11,6 +12,7 @@ pub use cursor::*;
1112
pub use delete::*;
1213
pub use execute::*;
1314
pub use insert::*;
15+
pub use limiter::*;
1416
pub use paginator::*;
1517
pub use query::*;
1618
pub use select::*;

0 commit comments

Comments
 (0)