glacier-web 0.4.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
//! Deleting old records on a schedule, as Laravel's `Prunable` does:
//! a model says which of its records are old, and the jobs scheduler
//! deletes them in batches, once an hour.
//!
//! ```ignore
//! impl Prunable for Session {
//!     fn prunable() -> Query<Self> {
//!         Session::all().filter(|s| s.updated_at.lt(glacier::time::now() - 30.days()))
//!     }
//! }
//!
//! Jobs::new().prune_records::<Session>()
//! ```

use crate::db::{Expr, Query, Value};
use crate::error::Result;
use crate::model::Model;

/// How many records each delete takes, so no statement holds locks long.
const BATCH: u64 = 1000;

/// A model whose old records are deleted on a schedule.
pub trait Prunable: Model {
    /// The records to delete. They're deleted without callbacks, a batch
    /// at a time; use `dependent` foreign keys, not callbacks, for what
    /// goes with them.
    fn prunable() -> Query<Self>;
}

/// Deletes `M`'s prunable records in batches; how many it deleted.
pub async fn prune<M: Prunable>() -> Result<u64> {
    let mut deleted = 0;
    loop {
        let ids = M::prunable().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);
        }
    }
}