use crate::models::dht::SliceHashIndexedRow;
use sqlx::{Executor, Sqlite};
pub(crate) async fn insert_slice_hash<'e, E>(
executor: E,
arc_start: u32,
arc_end: u32,
slice_index: u64,
hash: &[u8],
) -> sqlx::Result<()>
where
E: Executor<'e, Database = Sqlite>,
{
sqlx::query(
"INSERT INTO SliceHash (arc_start, arc_end, slice_index, hash)
VALUES (?, ?, ?, ?)",
)
.bind(arc_start as i64)
.bind(arc_end as i64)
.bind(slice_index as i64)
.bind(hash)
.execute(executor)
.await?;
Ok(())
}
pub(crate) async fn slice_hash_count<'e, E>(
executor: E,
arc_start: u32,
arc_end: u32,
) -> sqlx::Result<u64>
where
E: Executor<'e, Database = Sqlite>,
{
let (max_index,): (Option<i64>,) = sqlx::query_as(
"SELECT MAX(slice_index) FROM SliceHash
WHERE arc_start = ? AND arc_end = ?",
)
.bind(arc_start as i64)
.bind(arc_end as i64)
.fetch_one(executor)
.await?;
Ok(max_index.map_or(0, |m| m.max(0) as u64 + 1))
}
pub(crate) async fn get_slice_hash<'e, E>(
executor: E,
arc_start: u32,
arc_end: u32,
slice_index: u64,
) -> sqlx::Result<Option<Vec<u8>>>
where
E: Executor<'e, Database = Sqlite>,
{
let row: Option<(Vec<u8>,)> = sqlx::query_as(
"SELECT hash FROM SliceHash
WHERE arc_start = ? AND arc_end = ? AND slice_index = ?",
)
.bind(arc_start as i64)
.bind(arc_end as i64)
.bind(slice_index as i64)
.fetch_optional(executor)
.await?;
Ok(row.map(|(h,)| h))
}
pub(crate) async fn get_slice_hashes<'e, E>(
executor: E,
arc_start: u32,
arc_end: u32,
) -> sqlx::Result<Vec<SliceHashIndexedRow>>
where
E: Executor<'e, Database = Sqlite>,
{
sqlx::query_as::<_, SliceHashIndexedRow>(
"SELECT slice_index, hash FROM SliceHash
WHERE arc_start = ? AND arc_end = ?",
)
.bind(arc_start as i64)
.bind(arc_end as i64)
.fetch_all(executor)
.await
}