diff options
Diffstat (limited to 'src/db/artworks.rs')
-rw-r--r-- | src/db/artworks.rs | 51 |
1 files changed, 51 insertions, 0 deletions
diff --git a/src/db/artworks.rs b/src/db/artworks.rs index 8b13789..619f42d 100644 --- a/src/db/artworks.rs +++ b/src/db/artworks.rs @@ -1 +1,52 @@ +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<Postgres>); + +impl Artworks { + pub fn new(pool: Pool<Postgres>) -> Self { + Self(pool) + } + + pub fn downcast(&self) -> Database { + Database(self.0.clone()) + } + + pub async fn create(&self, artwork: Artwork) -> Result<i32> { + 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<Vec<Artwork>> { + // 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?) + } +} |