summaryrefslogtreecommitdiff
path: root/dichroism/src/repo/photo_set_repo.rs
blob: 339ea910ca26621650b128f31bf826711be0ce81 (plain) (blame)
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
use super::entities::*;
use super::DBConn;
use crate::models;
use diesel::{insert_into, prelude::*, result::Error, update};

pub fn store(conn: &DBConn, mut photo_set: models::PhotoSet) -> Result<models::PhotoSet, Error> {
    use crate::schema::photo_sets::dsl::*;
    if photo_set.id.is_some() {
        // update
        let form = PhotoSetForm::from(photo_set.clone());
        update(photo_sets).set(&form).execute(conn)?;
    } else {
        // insert
        photo_set.id = Some(find_next_id(conn)?);
        let form = PhotoSetForm::from(photo_set.clone());
        insert_into(photo_sets).values(&form).execute(conn)?;
    }
    Ok(photo_set)
}

pub fn find(conn: &DBConn, dbid: i32) -> Result<Option<models::PhotoSet>, Error> {
    use crate::schema::photo_sets::dsl::*;
    let query = photo_sets
        .filter(id.eq(dbid))
        .select((id, original, fullsize, base, thumbnail));
    let photo_set = query.first::<PhotoSet>(conn).map(|p| p.into());
    match photo_set {
        Ok(p) => Ok(Some(p)),
        Err(e) => {
            if e == Error::NotFound {
                Ok(None)
            } else {
                Err(e)
            }
        }
    }
}

fn find_next_id(conn: &DBConn) -> Result<i32, Error> {
    use crate::schema::photo_sets::dsl::*;
    Ok(photo_sets.select(id).order(id.desc()).first::<i32>(conn)? + 1)
}