summaryrefslogtreecommitdiffstats
path: root/src/db/models/artifact.rs
blob: 4faf7c45eae90108f4e83415c09949c5582496f5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
use std::path::PathBuf;
use crate::filestore::path::ArtifactPath;

use anyhow::anyhow;
use anyhow::Error;
use anyhow::Context;
use anyhow::Result;
use diesel::PgConnection;
use diesel::prelude::*;

use crate::db::models::Job;
use crate::schema::artifacts::*;
use crate::schema::artifacts;

#[derive(Debug, Identifiable, Queryable, Associations)]
#[belongs_to(Job)]
pub struct Artifact {
    pub id: i32,
    pub path: String,
    pub released: bool,
    pub job_id: i32,
}

#[derive(Insertable)]
#[table_name="artifacts"]
struct NewArtifact<'a> {
    pub path: &'a str,
    pub released: bool,
    pub job_id: i32,
}

impl Artifact {
    pub fn path_buf(&self) -> PathBuf {
        PathBuf::from(&self.path)
    }

    pub fn create(database_connection: &PgConnection, art_path: &ArtifactPath, art_released: bool, job: &Job) -> Result<Artifact> {
        let path_str = art_path.to_str()
                .ok_or_else(|| anyhow!("Path is not valid UTF-8: {}",  art_path.display()))
                .context("Writing artifact to database")?;
        let new_art = NewArtifact {
            path: path_str,
            released: art_released,
            job_id: job.id,
        };

        diesel::insert_into(artifacts::table)
            .values(&new_art)
            .execute(database_connection)?;

        dsl::artifacts
            .filter(path.eq(path_str).and(job_id.eq(job.id)))
            .first::<Artifact>(database_connection)
            .map_err(Error::from)
    }
}