feat: add comments
This commit is contained in:
parent
fed9c01370
commit
cc69935a88
8 changed files with 56 additions and 4 deletions
|
|
@ -1,6 +1,8 @@
|
|||
use r2d2_sqlite::rusqlite::{self, Row};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::{DbError, DbPool};
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub struct Comment {
|
||||
id: i32,
|
||||
|
|
@ -8,6 +10,12 @@ pub struct Comment {
|
|||
comment: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct NewComment {
|
||||
plant_id: i32,
|
||||
comment: String,
|
||||
}
|
||||
|
||||
impl Comment {
|
||||
pub fn from_row(row: &Row<'_>) -> Result<Self, rusqlite::Error> {
|
||||
Ok(Self {
|
||||
|
|
@ -17,3 +25,13 @@ impl Comment {
|
|||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl NewComment {
|
||||
pub fn insert(self, pool: &DbPool) -> Result<Comment, DbError> {
|
||||
let conn = pool.get()?;
|
||||
|
||||
let mut stmt =
|
||||
conn.prepare("insert into comments (plant_id, comment) values ($1, $2) returning *")?;
|
||||
Ok(stmt.query_row((self.plant_id, self.comment), Comment::from_row)?)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ use r2d2_sqlite::{rusqlite, SqliteConnectionManager};
|
|||
|
||||
use std::{error::Error, fmt};
|
||||
|
||||
pub use comment::Comment;
|
||||
pub use comment::{Comment, NewComment};
|
||||
pub use plant::{NewPlant, Plant};
|
||||
|
||||
pub type DbPool = r2d2::Pool<SqliteConnectionManager>;
|
||||
|
|
|
|||
|
|
@ -43,7 +43,7 @@ impl Plant {
|
|||
|
||||
pub fn comments(&self, pool: &DbPool) -> Result<Vec<Comment>, DbError> {
|
||||
let conn = pool.get()?;
|
||||
let mut stmt = conn.prepare("select * from plant_comments where plant_id = $1")?;
|
||||
let mut stmt = conn.prepare("select * from comments where plant_id = $1")?;
|
||||
|
||||
let comments: Result<Vec<_>, _> = stmt.query_map((self.id,), Comment::from_row)?.collect();
|
||||
Ok(comments?)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue