add checks for if a hash is in use

This commit is contained in:
Charlotte 🦝 Delenk 2024-11-30 09:18:09 +01:00
parent 42b1f82828
commit c9b59ca443
Signed by: darkkirb
GPG key ID: AB2BD8DAF2E37122
4 changed files with 45 additions and 2 deletions

View file

@ -15,7 +15,7 @@ use chir_rs_config::ChirRs;
use chir_rs_misc::{id_generator, lexicographic_base64};
use educe::Educe;
use eyre::{Context as _, Result};
use stretto::{AsyncCache, AsyncCacheBuilder};
use stretto::AsyncCache;
use tokio::{
fs::read_to_string,
io::{AsyncRead, AsyncReadExt},

View file

@ -0,0 +1,22 @@
{
"db_name": "PostgreSQL",
"query": "SELECT COUNT(*) as amount FROM file_map WHERE \"b3hash\" = $1",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "amount",
"type_info": "Int8"
}
],
"parameters": {
"Left": [
"Bytea"
]
},
"nullable": [
null
]
},
"hash": "4eb1d9d2853313df1b2a2050de46d609d719ce7cf906df70d693ffc186468351"
}

View file

@ -0,0 +1,3 @@
-- Add migration script here
create index file_b3hash on file_map(b3hash);

View file

@ -208,7 +208,7 @@ impl File {
/// Updates the file with new information
///
/// # Errors
/// THis function returns an error if updating the entry in the database fails
/// This function returns an error if updating the entry in the database fails
#[instrument(skip(db))]
pub async fn update(&self, db: &Database) -> Result<()> {
let id: i64 = self.id.try_into()?;
@ -231,4 +231,22 @@ impl File {
})?;
Ok(())
}
/// Checks if a particular hash is in use
///
/// # Errors
/// This function returns an error if updating the entry in the database fails
#[instrument(skip(db))]
pub async fn is_used(db: &Database, hash: Hash) -> Result<bool> {
#[expect(clippy::panic, reason = "sqlx silliness")]
let count = query!(
r#"SELECT COUNT(*) as amount FROM file_map WHERE "b3hash" = $1"#,
hash.as_bytes()
)
.fetch_one(&*db.0)
.await
.with_context(|| format!("Checking if {hash:?} is still used."))?;
Ok(count.amount.unwrap_or_default() != 0)
}
}