From 13064b2cbdfa455e58d10aa7802064dafcf6c47d Mon Sep 17 00:00:00 2001 From: "Christoph J. Scherr" Date: Thu, 27 Jun 2024 12:29:08 +0200 Subject: [PATCH] publish post --- members/diesel-demo/src/main.rs | 37 +++++++++++++++++++++++++++++-- members/diesel-demo/src/models.rs | 15 ++++++++++++- 2 files changed, 49 insertions(+), 3 deletions(-) diff --git a/members/diesel-demo/src/main.rs b/members/diesel-demo/src/main.rs index 69c0c96..86519b8 100644 --- a/members/diesel-demo/src/main.rs +++ b/members/diesel-demo/src/main.rs @@ -1,5 +1,5 @@ use diesel::SqliteConnection; -use diesel_demo::models::PostDraft; +use diesel_demo::models::{Post, PostDraft}; use libpt::log::{self, debug, error, trace}; use diesel_demo as lib; @@ -33,10 +33,23 @@ fn repl(conn: &mut SqliteConnection) -> anyhow::Result<()> { help - show this menu\n\ exit - exit the application\n\ list - list all posts\n\ + publish [id] - delete the post with the id [id]\n\ + delete [id] - delete the post with the id [id]\n\ new - create a new post" ) } else if buf.starts_with("EXIT") { break; + } else if buf.starts_with("PUBLISH") { + let id: i32 = match get_id(&buf) { + Some(i) => i, + None => continue, + }; + Post::publish(conn, id)?; + } else if buf.starts_with("DELETE") { + let id: i32 = match get_id(&buf) { + Some(i) => i, + None => continue, + }; } else if buf.starts_with("LIST") { let posts = lib::load_all_posts(conn)?; trace!("loaded posts for display: {posts:#?}"); @@ -47,9 +60,29 @@ fn repl(conn: &mut SqliteConnection) -> anyhow::Result<()> { error!("Could not submit the post: {e:?}"); }); } else { - println!("Bad input: try 'help'"); + usage() } } Ok(()) } + +fn usage() { + println!("Bad input: try 'help'"); +} + +fn get_id(buf: &str) -> Option { + match buf.split(' ').nth(1) { + Some(s) => match s.parse() { + Ok(i) => Some(i), + Err(e) => { + error!("could not parse the id: {e:?}"); + None + } + }, + None => { + usage(); + None + } + } +} diff --git a/members/diesel-demo/src/models.rs b/members/diesel-demo/src/models.rs index 981a64b..0ef2dd2 100644 --- a/members/diesel-demo/src/models.rs +++ b/members/diesel-demo/src/models.rs @@ -1,7 +1,7 @@ use std::io::{self, Read, Write}; use diesel::prelude::*; -use libpt::log::trace; +use libpt::log::{info, trace}; use crate::schema::posts; @@ -21,6 +21,19 @@ pub struct Post { pub published: bool, } +impl Post { + pub fn publish(conn: &mut SqliteConnection, id: i32) -> anyhow::Result<()> { + use crate::schema::posts::dsl::{posts, published}; + + let post = diesel::update(posts.find(id)) + .set(published.eq(true)) + .returning(Post::as_returning()) + .get_result(conn)?; + info!("updated post {}", post.id); + Ok(()) + } +} + #[derive(Insertable, Debug)] #[diesel(table_name = crate::schema::posts)] #[diesel(check_for_backend(diesel::sqlite::Sqlite))] // optional but improves generated compiler errors