From 2642fdb8b303bafd7d319ef8d698210db2a76d7d Mon Sep 17 00:00:00 2001 From: shockrah Date: Thu, 17 Sep 2020 21:51:23 -0700 Subject: [PATCH] adding wrapper for messages --- server-api/db/src/lib.rs | 1 + server-api/db/src/messages.rs | 67 +++++++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+) create mode 100644 server-api/db/src/messages.rs diff --git a/server-api/db/src/lib.rs b/server-api/db/src/lib.rs index f1c61d1..6f9cdc2 100644 --- a/server-api/db/src/lib.rs +++ b/server-api/db/src/lib.rs @@ -2,6 +2,7 @@ mod member; mod common; mod invites; mod channels; +mod messages; use std::vec::Vec; diff --git a/server-api/db/src/messages.rs b/server-api/db/src/messages.rs new file mode 100644 index 0000000..4f23bd5 --- /dev/null +++ b/server-api/db/src/messages.rs @@ -0,0 +1,67 @@ +use mysql_async::{params, Pool, Conn}; +use mysql_async::prelude::Queryable; +use mysql_async::error::Error as SqlError; + +use async_trait::async_trait; + +use crate::{Response, no_conn, sql_err}; +use crate::{UBigInt, BigInt, Integer, VarChar}; + +use crate::common::{FromDB}; + +#[allow(dead_code)] +pub struct Message { + pub id: UBigInt, + pub time: BigInt, + pub content: VarChar, + pub author_id: UBigInt, + pub channel_name: VarChar +} + +#[async_trait] +impl FromDB for Message { + type Row = Option<(UBigInt, BigInt, VarChar, UBigInt, VarChar)>; + + async fn get(p: &Pool, id: UBigInt) -> Response { + if let Ok(conn) = p.get_conn().await { + let q = "SELECT id, time, content, author_id, channel_name WHERE id = :id"; + let result: Result<(Conn, Self::Row), SqlError> = + conn.first_exec(q, params!{"id" => id}).await; + if let Ok((_, row)) = result { + return match row { + Some(row) => Response::Row(Self { + id: id, + time: row.1, + content: row.2, + author_id: row.3, + channel_name: row.4 + }), + None => Response::Empty + } + } + return Response::Other(sql_err!("Message::FromDB::get")); + } + return Response::Other(no_conn!("Message")); + } + + async fn update(p: &Pool, row: Self) -> Response { + // NOTE: we only allow the changing of content in this since + // no other column has good reason to be modified + if let Ok(conn) = p.get_conn().await { + let q = "UPDATE messages + SET content = :content + WHERE id = :id"; + let result: Result = + conn.drop_exec(q, params!{"id" => row.id, "content" => row.content}).await; + return match result { + Ok(_) => Response::Success, + Err(_) => Response::Other(sql_err!("Message::FromDB::update")) + } + } + return Response::Other(no_conn!("Message::FromDB::update")) + } + + async fn delete(p: &Pool, id: UBigInt) -> Response { + unimplemented!() + } +}