From 0b9810258062d95c71ba3678602e754b01d5b947 Mon Sep 17 00:00:00 2001 From: Nikita Vilunov Date: Tue, 3 Oct 2023 02:00:54 +0200 Subject: [PATCH] add author id in messages schema --- crates/lavina-core/migrations/1_msg_author.sql | 1 + crates/lavina-core/src/repo/mod.rs | 15 ++++++++++++--- crates/lavina-core/src/room.rs | 2 +- 3 files changed, 14 insertions(+), 4 deletions(-) create mode 100644 crates/lavina-core/migrations/1_msg_author.sql diff --git a/crates/lavina-core/migrations/1_msg_author.sql b/crates/lavina-core/migrations/1_msg_author.sql new file mode 100644 index 0000000..b25146e --- /dev/null +++ b/crates/lavina-core/migrations/1_msg_author.sql @@ -0,0 +1 @@ +alter table messages add author_id integer null references users(id); diff --git a/crates/lavina-core/src/repo/mod.rs b/crates/lavina-core/src/repo/mod.rs index d24e8b5..d81ec0c 100644 --- a/crates/lavina-core/src/repo/mod.rs +++ b/crates/lavina-core/src/repo/mod.rs @@ -3,6 +3,7 @@ use std::str::FromStr; use std::sync::Arc; +use anyhow::anyhow; use serde::Deserialize; use sqlx::sqlite::SqliteConnectOptions; use sqlx::{ConnectOptions, Connection, FromRow, Sqlite, SqliteConnection, Transaction}; @@ -76,16 +77,24 @@ impl Storage { Ok(id) } - pub async fn insert_message(&mut self, room_id: u32, id: u32, content: &str) -> Result<()> { + pub async fn insert_message(&mut self, room_id: u32, id: u32, content: &str, author_id: &str) -> Result<()> { let mut executor = self.conn.lock().await; + let res: Option<(u32,)> = sqlx::query_as("select id from users where name = ?;") + .bind(author_id) + .fetch_optional(&mut *executor) + .await?; + let Some((author_id,)) = res else { + return Err(anyhow!("No such user")); + }; sqlx::query( - "insert into messages(room_id, id, content) - values (?, ?, ?); + "insert into messages(room_id, id, content, author_id) + values (?, ?, ?, ?); update rooms set message_count = message_count + 1 where id = ?;", ) .bind(room_id) .bind(id) .bind(content) + .bind(author_id) .bind(room_id) .execute(&mut *executor) .await?; diff --git a/crates/lavina-core/src/room.rs b/crates/lavina-core/src/room.rs index 5c6dbd9..a61a50e 100644 --- a/crates/lavina-core/src/room.rs +++ b/crates/lavina-core/src/room.rs @@ -181,7 +181,7 @@ impl Room { async fn send_message(&mut self, author_id: PlayerId, body: Str) -> Result<()> { tracing::info!("Adding a message to room"); self.storage - .insert_message(self.storage_id, self.message_count, &body) + .insert_message(self.storage_id, self.message_count, &body, &*author_id.as_inner()) .await?; self.message_count += 1; let update = Updates::NewMessage {