Skip to content

Commit

Permalink
feat: allow an easier use of limit/offset
Browse files Browse the repository at this point in the history
  • Loading branch information
ctron committed May 2, 2024
1 parent a321f0a commit dc40b69
Show file tree
Hide file tree
Showing 2 changed files with 89 additions and 0 deletions.
87 changes: 87 additions & 0 deletions src/executor/limiter.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
use crate::{
ConnectionTrait, DbErr, EntityTrait, FromQueryResult, Paginator, PaginatorTrait, QuerySelect,
Select, SelectModel, SelectTwo, SelectTwoMany, SelectTwoModel, Selector, SelectorTrait,
};
use std::num::NonZeroU64;

#[derive(Debug)]
pub struct Limiter<'db, C, S>
where
C: ConnectionTrait,
S: SelectorTrait + 'db,
{
db: &'db C,
selector: Selector<S>,
paginator: Paginator<'db, C, S>,
}

impl<'db, C, S> Limiter<'db, C, S>
where
C: ConnectionTrait,
S: SelectorTrait + 'db,
{
pub async fn fetch(self) -> Result<Vec<S::Item>, DbErr> {
self.selector.all(self.db).await
}

pub async fn total(&self) -> Result<u64, DbErr> {
self.paginator.num_items().await
}
}

pub trait LimiterTrait<'db, C>
where
C: ConnectionTrait,
{
type Selector: SelectorTrait + 'db;

fn limiting(self, db: &'db C, offset: u64, limit: u64) -> Limiter<'db, C, Self::Selector>;
}

impl<'db, C, M, E> LimiterTrait<'db, C> for Select<E>
where
C: ConnectionTrait,
E: EntityTrait<Model = M>,
M: FromQueryResult + Sized + Send + Sync + 'db,
{
type Selector = SelectModel<M>;

fn limiting(self, db: &'db C, offset: u64, limit: u64) -> Limiter<'db, C, Self::Selector> {
let selector = self
.clone()
.limit(NonZeroU64::new(limit).map(|limit| limit.get()))
.offset(NonZeroU64::new(offset).map(|offset| offset.get()))
.into_model();

Limiter {
db,
paginator: self.clone().paginate(db, 1),
selector,
}
}
}

impl<'db, C, M1, M2, E1, E2> LimiterTrait<'db, C> for SelectTwo<E1, E2>
where
C: ConnectionTrait,
E1: EntityTrait<Model = M1>,
E2: EntityTrait<Model = M2>,
M1: FromQueryResult + Sized + Send + Sync + 'db,
M2: FromQueryResult + Sized + Send + Sync + 'db,
{
type Selector = SelectTwoModel<M1, M2>;

fn limiting(self, db: &'db C, offset: u64, limit: u64) -> Limiter<'db, C, Self::Selector> {
let selector = self
.clone()
.limit(NonZeroU64::new(limit).map(|limit| limit.get()))
.offset(NonZeroU64::new(offset).map(|offset| offset.get()))
.into_model();

Limiter {
db,
paginator: self.clone().paginate(db, 1),
selector,
}
}
}
2 changes: 2 additions & 0 deletions src/executor/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ mod cursor;
mod delete;
mod execute;
mod insert;
mod limiter;
mod paginator;
mod query;
mod select;
Expand All @@ -11,6 +12,7 @@ pub use cursor::*;
pub use delete::*;
pub use execute::*;
pub use insert::*;
pub use limiter::*;
pub use paginator::*;
pub use query::*;
pub use select::*;
Expand Down

0 comments on commit dc40b69

Please sign in to comment.