use sqlx::{Pool, Postgres}; use uuid::Uuid; use crate::artist::Artist; use crate::artwork::Artwork; use crate::file::File; use crate::Result; use super::Database; #[derive(Clone)] pub struct Artworks(Pool); impl Artworks { pub fn new(pool: Pool) -> Self { Self(pool) } pub fn downcast(&self) -> Database { Database(self.0.clone()) } pub async fn create(&self, artwork: Artwork) -> Result { let artist_id = if let Some(artist_id) = artwork.artist.id() { artist_id } else { self.downcast().artists().create(artwork.artist).await? }; let artwork_id = sqlx::query!("insert into artworks (title, description, url_source, artist_id) values ($1, $2, $3, $4) returning id", artwork.title, artwork.description, artwork.url_source, artist_id).fetch_one(&self.0).await?.id; for file in artwork.files { sqlx::query!( "insert into artwork_files (id, alt_text, extension, artwork_id) values ($1, $2, $3, $4)", file.id(), file.alt_text, file.extension(), artwork_id ) .execute(&self.0) .await?; } Ok(artwork_id) } pub async fn read_all(&self) -> Result> { // TODO: join comments and files Ok(sqlx::query_as( "select * from artworks left join artists on artworks.artist_id = artists.id left join artwork_files on artworks.id = artwork_files.artwork_id group by artworks.id, artists.id, artwork_files.id", ) .fetch_all(&self.0) .await?) } }