Skip to main content

Module prunable

Module prunable 

Source
Expand description

Model pruning — declarative bulk removal of stale rows. See prunable::Prunable + register_prunable!. Model pruning: delete stale rows on a schedule.

Long-lived tables fill up with expired sessions, old soft-deletes, aged audit entries and finished jobs. Write a Prunable impl that returns the queryset of rows to delete, register it with register_prunable!, then run manage prune or call prune_all from cron or a background job.

§Quick start

ⓘ
use rustango::prunable::Prunable;
use rustango::query::QuerySet;
use rustango::Model;

#[derive(Model)]
struct AuditEntry {
    #[rustango(primary_key)] id: rustango::Auto<i64>,
    created: chrono::DateTime<chrono::Utc>,
    // ...
}

impl Prunable for AuditEntry {
    fn prune_queryset() -> QuerySet<Self> {
        // Anything older than 30 days is fair game.
        let cutoff = chrono::Utc::now() - chrono::Duration::days(30);
        QuerySet::<Self>::default().filter("created__lt", cutoff)
    }
}

rustango::register_prunable!(AuditEntry);

Then run from the CLI:

cargo run -- prune                  # delete all registered models
cargo run -- prune --model AuditEntry
cargo run -- prune --except Sessions
cargo run -- prune --pretend        # count matches without deleting

Or programmatically from a background job:

ⓘ
let reports = rustango::prunable::prune_all(
    &pool,
    &rustango::prunable::PruneOptions::default(),
).await?;
for r in reports {
    tracing::info!(table = %r.table, rows = r.rows, "pruned");
}

Structs§

PruneOptions
Picks which models a prune run covers.
PruneReport
One line of a prune report.

Traits§

Prunable
Marks a model as prunable and says which rows to delete. Also call register_prunable! so manage prune can find the impl.

Functions§

prune_all
Delete matching rows for every registered prunable that PruneOptions allows. Returns one PruneReport per model that ran. Use prune_pretend for a dry run.
prune_pretend
Dry run of prune_all: counts the rows instead of deleting them. Use it to preview a prune before you run it for real.
registered_names
Every registered prunable table name. Use it to list them, or to check a --model or --except flag before running.