diff options
Diffstat (limited to 'src/db/comments.rs')
| -rw-r--r-- | src/db/comments.rs | 42 | 
1 files changed, 42 insertions, 0 deletions
| 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<Postgres>); + +impl Comments { +    pub fn new(pool: Pool<Postgres>) -> Self { +        Self(pool) +    } + +    pub async fn create(&self, comment: Comment) -> Result<i32> { +        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<Vec<Comment>> { +        // TODO: joins to get in_reply_to_ids and mentioned_by_ids +        let comments: Vec<Comment> = sqlx::query_as("select * from comments") +            .fetch_all(&self.0) +            .await?; +        Ok(comments) +    } + +    pub async fn read_thread(&self, artwork_id: i32) -> Result<Vec<Comment>> { +        Ok(sqlx::query_as("select * from comments") +            .fetch_all(&self.0) +            .await?) +    } +} | 
