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/comments.rs | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 src/db/comments.rs (limited to 'src/db/comments.rs') diff --git a/src/db/comments.rs b/src/db/comments.rs new file mode 100644 index 0000000..ec07aa0 --- /dev/null +++ b/src/db/comments.rs @@ -0,0 +1,42 @@ +use sqlx::{Pool, Postgres}; + +use crate::comment::Comment; +use crate::Result; + +#[derive(Clone)] +pub struct Comments(Pool); + +impl Comments { + pub fn new(pool: Pool) -> Self { + Self(pool) + } + + pub async fn create(&self, comment: Comment) -> Result { + let comment_id = sqlx::query!( + r#"insert into comments (text, artwork_id) values ($1, $2) returning id"#, + comment.text, + comment.artwork_id + ) + .fetch_one(&self.0) + .await? + .id; + for in_reply_to_id in comment.in_reply_to_ids { + sqlx::query!("insert into comment_relations (artwork_id, in_reply_to_id, comment_id) values ($1, $2, $3)", comment.artwork_id, in_reply_to_id, comment_id).execute(&self.0).await?; + } + Ok(comment_id) + } + + pub async fn read_all(&self) -> Result> { + // TODO: joins to get in_reply_to_ids and mentioned_by_ids + let comments: Vec = sqlx::query_as("select * from comments") + .fetch_all(&self.0) + .await?; + Ok(comments) + } + + pub async fn read_thread(&self, artwork_id: i32) -> Result> { + Ok(sqlx::query_as("select * from comments") + .fetch_all(&self.0) + .await?) + } +} -- cgit