summaryrefslogtreecommitdiffstats
path: root/src/db/models/package.rs
blob: 88839b6a0f169606f36d3338c95040cddfa58cb0 (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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
//
// Copyright (c) 2020-2021 science+computing ag and other contributors
//
// This program and the accompanying materials are made
// available under the terms of the Eclipse Public License 2.0
// which is available at https://www.eclipse.org/legal/epl-2.0/
//
// SPDX-License-Identifier: EPL-2.0
//

use std::ops::Deref;

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

use crate::schema::packages;
use crate::schema::packages::*;

#[derive(Debug, Identifiable, Queryable, Eq, PartialEq)]
pub struct Package {
    pub id: i32,
    pub name: String,
    pub version: String,
}

#[derive(Insertable)]
#[table_name = "packages"]
struct NewPackage<'a> {
    pub name: &'a str,
    pub version: &'a str,
}

impl Package {
    pub fn create_or_fetch(
        database_connection: &PgConnection,
        p: &crate::package::Package,
    ) -> Result<Package> {
        let new_package = NewPackage {
            name: p.name().deref(),
            version: p.version().deref(),
        };

        diesel::insert_into(packages::table)
            .values(&new_package)
            .on_conflict_do_nothing()
            .execute(database_connection)?;

        dsl::packages
            .filter({
                let p_name = p.name().deref();
                let p_vers = p.version().deref();

                name.eq(p_name).and(version.eq(p_vers))
            })
            .first::<Package>(database_connection)
            .map_err(Error::from)
    }

    pub fn fetch_for_job(database_connection: &PgConnection, j: &crate::db::models::Job) -> Result<Option<Package>> {
        Self::fetch_by_id(database_connection, j.package_id)
    }

    pub fn fetch_by_id(database_connection: &PgConnection, pid: i32) -> Result<Option<Package>> {
        match dsl::packages.filter(id.eq(pid)).first::<Package>(database_connection) {
            Err(diesel::result::Error::NotFound) => Ok(None),
            Err(e) => Err(Error::from(e)),
            Ok(p) => Ok(Some(p)),
        }
    }
}