diff options
author | 2024-11-14 17:59:21 +0000 | |
---|---|---|
committer | 2024-11-14 17:59:21 +0000 | |
commit | 469a3ad33914f7eff6edc9ca7fabb12f2950da84 (patch) | |
tree | 2712ba2e927fb820b6aa58443c9227d1da24a03f /src/db/artworks.rs | |
parent | b7a2265e9b29d8fa09f84f5213ef7f8ed3045ca6 (diff) | |
download | critch-469a3ad33914f7eff6edc9ca7fabb12f2950da84.tar.gz critch-469a3ad33914f7eff6edc9ca7fabb12f2950da84.tar.bz2 critch-469a3ad33914f7eff6edc9ca7fabb12f2950da84.zip |
database work
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?) + } +} |