image.rs 1.67 KB
use std::sync::Arc;

use crate::error::*;
use crate::{schema::*, Pool};
use diesel::{Connection, insert_into};
use diesel::prelude::*;
use serde::{Deserialize, Serialize};

#[derive(Clone, Debug, Serialize, Deserialize, Queryable, Identifiable)]
pub struct Image {
    pub id           :i32,
    pub upload_uuid  :Option<Vec<u8>>,
    pub uuid         :Option<Vec<u8>>,
    pub size         :i32,
    pub dim_x        :Option<i32>,
    pub dim_y        :Option<i32>,
    pub mime_type    :String,
    pub date_created :String,
    pub date_updated :String
}

#[derive(Debug, Insertable)]
#[table_name = "images"]
pub struct ImageNew<'a> {
    pub upload_uuid  :Option<&'a [u8]>,
    pub size         :i32,
    pub mime_type    :&'a str,
    pub date_created :&'a str,
    pub date_updated :&'a str
}

#[derive(Clone, Debug, Serialize, Deserialize, AsChangeset)]
#[table_name = "images"]
pub struct Upload {
    pub upload_uuid  :Option<Vec<u8>>,
    pub size         :i32,
    pub mime_type    :String,
}

pub(crate) fn upload( pool: Arc<Pool>
                    , item: Upload ) -> Result<Image> {
    use crate::schema::images::dsl::*;
    let db_connection = pool.get()?;

    let now = chrono::Local::now().naive_local();
    let new_image = ImageNew {
        upload_uuid  : item.upload_uuid.as_deref(),
        size         : item.size,
        mime_type    : &item.mime_type,
        date_created : &format!("{}", now),
        date_updated : &format!("{}", now)
    };

    Ok(db_connection.transaction(|| {
        insert_into(images) . values(&new_image)
                            . execute(&db_connection)?;
        images . order(id.desc())
               . first::<Image>(&db_connection)
    })?)
}