use std::future::Future;
use std::pin::Pin;
use chrono::TimeDelta;
use super::Delay;
use crate::db::{Expr, Query, Value};
use crate::error::Result;
use crate::model::Model;
const BATCH: u64 = 1000;
pub type HookFuture<'a> = Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>>;
pub type Hook<M> = for<'a> fn(&'a mut M) -> HookFuture<'a>;
pub trait Prunable: Model {
fn prunes() -> Vec<Prune<Self>>;
}
pub struct Prune<M> {
name: &'static str,
every: TimeDelta,
query: fn() -> Query<M>,
hooks: Vec<Hook<M>>,
}
impl<M> Clone for Prune<M> {
fn clone(&self) -> Self {
Self {
name: self.name,
every: self.every,
query: self.query,
hooks: self.hooks.clone(),
}
}
}
impl<M: Model> Prune<M> {
pub fn new(name: &'static str, query: fn() -> Query<M>) -> Self {
Self {
name,
every: TimeDelta::hours(1),
query,
hooks: Vec::new(),
}
}
#[must_use]
pub fn every(mut self, every: impl Delay) -> Self {
self.every = every.delay();
self
}
#[must_use]
pub fn pruning(mut self, hook: Hook<M>) -> Self {
self.hooks.push(hook);
self
}
pub fn full_name(&self) -> String {
if self.name.is_empty() {
M::TABLE.to_owned()
} else {
format!("{}:{}", M::TABLE, self.name)
}
}
pub fn interval(&self) -> TimeDelta {
self.every
}
pub async fn run(&self) -> Result<u64> {
if self.hooks.is_empty() {
return self.delete_in_batches().await;
}
let mut deleted = 0;
loop {
let records = (self.query)().limit(BATCH).all().await?;
let batch = records.len() as u64;
for mut record in records {
for hook in &self.hooks {
hook(&mut record).await?;
}
record.destroy().await?;
deleted += 1;
}
if batch < BATCH {
return Ok(deleted);
}
}
}
async fn delete_in_batches(&self) -> Result<u64> {
let mut deleted = 0;
loop {
let ids = (self.query)().limit(BATCH).ids().await?;
if ids.is_empty() {
return Ok(deleted);
}
let batch = ids.len() as u64;
let values = ids.into_iter().map(Value::Int).collect();
deleted += Query::<M>::new()
.filter(|_| Expr::In {
column: M::PRIMARY_KEY,
values,
})
.delete_all()
.await?;
if batch < BATCH {
return Ok(deleted);
}
}
}
}
pub async fn prune<M: Prunable>() -> Result<u64> {
let mut deleted = 0;
for prune in M::prunes() {
deleted += prune.run().await?;
}
Ok(deleted)
}