brass/db/src/models/clothing.rs

68 lines
1.6 KiB
Rust

use sqlx::{query, PgPool};
use super::Result;
#[derive(Debug, Clone)]
pub struct Clothing {
pub id: i32,
pub name: String,
}
impl Clothing {
pub async fn create(pool: &PgPool, name: &str) -> Result<Clothing> {
let r = query!("INSERT INTO clothing (name) VALUES ($1) RETURNING id;", name)
.fetch_one(pool)
.await?;
let created_clothing = Clothing {
id: r.id,
name: name.to_string()
};
Ok(created_clothing)
}
pub async fn read_all(pool: &PgPool) -> Result<Vec<Clothing>> {
let records = query!("SELECT * FROM clothing ORDER by name;").fetch_all(pool).await?;
let clothing_options = records
.into_iter()
.map(|v| Clothing {
id: v.id,
name: v.name,
})
.collect();
Ok(clothing_options)
}
pub async fn read(pool: &PgPool, id: i32) -> Result<Option<Clothing>> {
let record = query!("SELECT * FROM clothing WHERE id = $1;", id)
.fetch_optional(pool)
.await?;
let vehicle = record.map(|v| Clothing {
id: v.id,
name: v.name,
});
Ok(vehicle)
}
pub async fn update(pool: &PgPool, id: i32, name: &str) -> Result<()> {
query!("UPDATE clothing SET name = $1 WHERE id = $2;", name, id)
.execute(pool)
.await?;
Ok(())
}
pub async fn delete(pool: &PgPool, id: i32) -> Result<()> {
query!("DELETE FROM clothing WHERE id = $1;", id)
.execute(pool)
.await?;
Ok(())
}
}