summaryrefslogtreecommitdiffstats
path: root/src/db/models/endpoint.rs
blob: 3909b2b7fa99c8742ff39e39492071596ce135b1 (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
//
// 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 anyhow::Error;
use anyhow::Result;
use diesel::prelude::*;
use diesel::PgConnection;

use crate::config::EndpointName;
use crate::schema::endpoints;
use crate::schema::endpoints::*;

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

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

impl Endpoint {
    pub fn create_or_fetch(database_connection: &PgConnection, ep_name: &EndpointName) -> Result<Endpoint> {
        let new_ep = NewEndpoint { name: ep_name.as_ref() };

        diesel::insert_into(endpoints::table)
            .values(&new_ep)
            .on_conflict_do_nothing()
            .execute(database_connection)?;

        dsl::endpoints
            .filter(name.eq(ep_name.as_ref()))
            .first::<Endpoint>(database_connection)
            .map_err(Error::from)
    }

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

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