OXYGENHUB
◆ v0.9.21 oxygenhub / crates / hub / src / db / attachments.rs
1.4 KiB · Rust · last changed OxygenHub 0.9.19: attachments on issues and comments, over the API and oh --attach; images by their bytes shown in place, everything else a download (closes #350) 3 days ago source blame history raw
1
//! Attachments (oxygenhub#350): files people attach to issues, comments and
2
//! proposals, by content in the assets store.
3
4
use super::{now_ms, Pool};
5
6
#[derive(Clone, Debug, sqlx::FromRow)]
7
pub struct Attachment {
8
    pub id: i64,
9
    pub repo_id: i64,
10
    pub name: String,
11
    pub size: i64,
12
    pub hash: String,
13
    pub content_type: String,
14
    pub uploader_id: Option<i64>,
15
    pub created_ms: i64,
16
}
17
18
pub async fn add(
19
    pool: &Pool,
20
    repo_id: i64,
21
    name: &str,
22
    size: i64,
23
    hash: &str,
24
    content_type: &str,
25
    uploader_id: Option<i64>,
26
) -> sqlx::Result<Attachment> {
27
    sqlx::query_as(
28
        "INSERT INTO attachments (repo_id, name, size, hash, content_type, uploader_id, created_ms) VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING *",
29
    )
30
    .bind(repo_id)
31
    .bind(name)
32
    .bind(size)
33
    .bind(hash)
34
    .bind(content_type)
35
    .bind(uploader_id)
36
    .bind(now_ms())
37
    .fetch_one(pool)
38
    .await
39
}
40
41
/// One of a repository's attachments.
42
pub async fn get(pool: &Pool, repo_id: i64, id: i64) -> sqlx::Result<Option<Attachment>> {
43
    sqlx::query_as("SELECT * FROM attachments WHERE repo_id = $1 AND id = $2").bind(repo_id).bind(id).fetch_optional(pool).await
44
}
45
46
/// Whether any attachment keeps the blob `hash`.
47
pub async fn hash_in_use(pool: &Pool, hash: &str) -> sqlx::Result<bool> {
48
    let n: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM attachments WHERE hash = $1").bind(hash).fetch_one(pool).await?;
49
    Ok(n > 0)
50
}