use miden_node_db::sqlite::WriteTx;
use miden_node_tracing::miden_instrument;
use miden_protocol::block::BlockNumber;
use crate::COMPONENT;
use crate::db::queries::VALID_FOREVER;
use crate::errors::DatabaseError;
const SQL_VAULT_ASSETS: &str = include_str!("prune_account_vault_assets.sql");
const SQL_STORAGE_MAP_VALUES: &str = include_str!("prune_account_storage_map_values.sql");
const SQL_ACCOUNT_CODES_FULL: &str = include_str!("prune_account_codes_full.sql");
const SQL_ACCOUNT_CODES_WINDOWED: &str = include_str!("prune_account_codes_windowed.sql");
const SQL_SELECT_PRUNE_PROGRESS: &str = include_str!("select_prune_progress.sql");
const SQL_UPSERT_PRUNE_PROGRESS: &str = include_str!("upsert_prune_progress.sql");
const _: () = assert!(
VALID_FOREVER == 9_223_372_036_854_775_807,
"the `valid_until != <sentinel>` literal in the pruning statements is out of date"
);
pub const HISTORICAL_BLOCK_RETENTION: u32 = 50;
#[miden_instrument(
target = COMPONENT,
err,
fields(
cutoff_block,
),
)]
pub(crate) fn prune_history(
tx: &WriteTx<'_>,
prune_tip: BlockNumber,
) -> Result<(usize, usize, usize), DatabaseError> {
let cutoff_block = i64::from(prune_tip.as_u32().saturating_sub(HISTORICAL_BLOCK_RETENTION));
miden_node_tracing::Span::current().record("cutoff_block", cutoff_block);
let vault_deleted = tx.execute(SQL_VAULT_ASSETS, &[&cutoff_block])?;
let storage_deleted = tx.execute(SQL_STORAGE_MAP_VALUES, &[&cutoff_block])?;
let codes_deleted = prune_account_codes(tx, cutoff_block)?;
Ok((vault_deleted, storage_deleted, codes_deleted))
}
#[miden_instrument(
target = COMPONENT,
err,
fields(
cutoff_block,
),
)]
fn prune_account_codes(tx: &WriteTx<'_>, cutoff_block: i64) -> Result<usize, DatabaseError> {
let prev_cutoff = tx
.query(SQL_SELECT_PRUNE_PROGRESS, &[], |row| row.get::<i64>(0))?
.into_iter()
.next();
let deleted = match prev_cutoff {
Some(prev_cutoff) if prev_cutoff >= cutoff_block => return Ok(0),
Some(prev_cutoff) => {
tx.execute(SQL_ACCOUNT_CODES_WINDOWED, &[&prev_cutoff, &cutoff_block])?
},
None => tx.execute(SQL_ACCOUNT_CODES_FULL, &[&cutoff_block])?,
};
tx.execute(SQL_UPSERT_PRUNE_PROGRESS, &[&cutoff_block])?;
Ok(deleted)
}