summaryrefslogtreecommitdiff
path: root/dichroism/src/repo/product_repo.rs
blob: 487f96ec7795c0c9acbee98892c121a8d35b6371 (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
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
73
74
75
76
77
78
79
80
81
82
use super::entities::*;
use super::DBConn;
use crate::models;
use diesel::{insert_into, prelude::*, result::Error, update};

pub fn store(conn: &DBConn, mut product: models::Product) -> Result<models::Product, Error> {
    use crate::schema::products::dsl::*;
    if let Some(product_id) = product.id {
        // update
        let form = ProductForm::from(product.clone());
        update(products.filter(id.eq(product_id)))
            .set(&form)
            .execute(conn)?;
    } else {
        // insert
        product.id = Some(find_next_id(conn));
        let form = ProductForm::from(product.clone());
        insert_into(products).values(&form).execute(conn)?;
    }

    Ok(product)
}

pub fn find_all(conn: &DBConn) -> Result<Vec<models::Product>, Error> {
    use crate::schema::*;
    let query = products::table.inner_join(photo_sets::table).select((
        products::id,
        products::name,
        products::description,
        products::quantity,
        products::cents,
        products::featured,
        products::category,
        photo_sets::id,
        photo_sets::original,
        photo_sets::fullsize,
        photo_sets::base,
        photo_sets::thumbnail,
    ));
    Ok(query
        .load::<Product>(conn)?
        .into_iter()
        .map(|p| p.into())
        .collect::<Vec<models::Product>>())
}

pub fn find(conn: &DBConn, dbid: i32) -> Result<Option<models::Product>, Error> {
    use crate::schema::*;
    let query = products::table
        .inner_join(photo_sets::table)
        .filter(products::id.eq(dbid))
        .select((
            products::id,
            products::name,
            products::description,
            products::quantity,
            products::cents,
            products::featured,
            products::category,
            photo_sets::id,
            photo_sets::original,
            photo_sets::fullsize,
            photo_sets::base,
            photo_sets::thumbnail,
        ));
    let product = query.first::<Product>(conn).map(|p| p.into());
    match product {
        Ok(p) => Ok(Some(p)),
        Err(Error::NotFound) => Ok(None),
        Err(e) => Err(e),
    }
}

fn find_next_id(conn: &DBConn) -> i32 {
    use crate::schema::products::dsl::*;
    let last_id = products
        .select(id)
        .order(id.desc())
        .first::<i32>(conn)
        .unwrap_or(0);
    last_id + 1
}