From 4668ce7d0fd84feea164132e080b2d4f6aa0893f Mon Sep 17 00:00:00 2001 From: shockrah Date: Sat, 7 Nov 2020 18:26:19 -0800 Subject: [PATCH] Channel add behavior now also returns the same new channel that was just added ! We do this because in order to `get` the channel later we need its id. Some clients will be updating channel data periodically so this helps to make smaller queries possible --- server-api/db/src/channels.rs | 37 ++++++++++++++++++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/server-api/db/src/channels.rs b/server-api/db/src/channels.rs index 76bbba5..fe17f8c 100644 --- a/server-api/db/src/channels.rs +++ b/server-api/db/src/channels.rs @@ -154,5 +154,40 @@ impl FromDB for Channel { } impl Channel { - pub async fn add() {} + pub async fn add(p: &Pool, name: &str, desc: &str, kind: Integer) -> Response { + //! @returns on success -> Response::Row + //! @returns on partial success -> Response::Empty + //! @returns on failure -> Response::Other + if let Ok(conn) = p.get_conn().await { + let q = "INSERT INTO channels (name, description, kind) VALUES (:n, :d, :k)"; + let insert_result = conn.drop_exec(q, params!{ + "n" => name, + "d" => desc, + "k" => kind + }).await; + if let Ok(conn) = insert_result { + // This is only kosher because names are enforced as unique by sql + let q = "SELECT id FROM channels WHERE name = :name"; + let fetch_result : Result<(Conn, Option), SqlError> = + conn.first_exec(q, params!{"name" => name}).await; + + return match fetch_result { + Ok((_, id_opt)) => { + if let Some(id) = id_opt { + Response::Row(Channel { + id: id, + name: name.into(), + description: Some(desc.into()), + kind: kind + }) + } + else { Response::Empty } + }, + Err(_) => Response::Empty + }; + } + return Response::Other("Could fetch new channel".into()); + } + return Response::Other(no_conn!("db::channels::add")) + } }