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 product.id.is_some() {
// update
let form = ProductForm::from(product.clone());
update(products).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,
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,
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(e) => {
if e == Error::NotFound {
Ok(None)
} else {
Err(e)
}
}
}
}
fn find_next_id(conn: &DBConn) -> Result<i32, Error> {
use crate::schema::products::dsl::*;
Ok(products.select(id).order(id.desc()).first::<i32>(conn)? + 1)
}