use std::num::NonZeroUsize;
use miden_node_db::sqlite::ReadTx;
use miden_protocol::account::AccountId;
use crate::db::queries::VALID_FOREVER;
use crate::errors::DatabaseError;
const SQL_FIRST_PAGE: &str = include_str!("select_public_account_ids_page.sql");
const SQL_AFTER_CURSOR: &str = include_str!("select_public_account_ids_page_after.sql");
#[derive(Debug)]
pub struct PublicAccountIdsPage {
pub account_ids: Vec<AccountId>,
pub next_cursor: Option<AccountId>,
}
pub(crate) fn select_public_account_ids_paged(
tx: &ReadTx<'_>,
page_size: NonZeroUsize,
after_account_id: Option<AccountId>,
) -> Result<PublicAccountIdsPage, DatabaseError> {
let limit = i64::try_from(page_size.get() + 1).expect("page size fits within i64");
let mut account_ids = match after_account_id {
Some(cursor) => tx.query(SQL_AFTER_CURSOR, &[&limit, &VALID_FOREVER, &cursor], |row| {
row.get::<AccountId>(0)
})?,
None => {
tx.query(SQL_FIRST_PAGE, &[&limit, &VALID_FOREVER], |row| row.get::<AccountId>(0))?
},
};
let next_cursor = if account_ids.len() > page_size.get() {
account_ids.pop(); account_ids.last().copied()
} else {
None
};
Ok(PublicAccountIdsPage { account_ids, next_cursor })
}