From 469a3ad33914f7eff6edc9ca7fabb12f2950da84 Mon Sep 17 00:00:00 2001 From: cel 🌸 Date: Thu, 14 Nov 2024 17:59:21 +0000 Subject: database work --- src/db/artworks.rs | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) (limited to 'src/db/artworks.rs') 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); + +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?) + } +} -- cgit