forked from lavina/lavina
1
0
Fork 0

add author id in messages schema

This commit is contained in:
Nikita Vilunov 2023-10-03 02:00:54 +02:00
parent 1373767d7f
commit 0b98102580
3 changed files with 14 additions and 4 deletions

View File

@ -0,0 +1 @@
alter table messages add author_id integer null references users(id);

View File

@ -3,6 +3,7 @@
use std::str::FromStr; use std::str::FromStr;
use std::sync::Arc; use std::sync::Arc;
use anyhow::anyhow;
use serde::Deserialize; use serde::Deserialize;
use sqlx::sqlite::SqliteConnectOptions; use sqlx::sqlite::SqliteConnectOptions;
use sqlx::{ConnectOptions, Connection, FromRow, Sqlite, SqliteConnection, Transaction}; use sqlx::{ConnectOptions, Connection, FromRow, Sqlite, SqliteConnection, Transaction};
@ -76,16 +77,24 @@ impl Storage {
Ok(id) 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 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( sqlx::query(
"insert into messages(room_id, id, content) "insert into messages(room_id, id, content, author_id)
values (?, ?, ?); values (?, ?, ?, ?);
update rooms set message_count = message_count + 1 where id = ?;", update rooms set message_count = message_count + 1 where id = ?;",
) )
.bind(room_id) .bind(room_id)
.bind(id) .bind(id)
.bind(content) .bind(content)
.bind(author_id)
.bind(room_id) .bind(room_id)
.execute(&mut *executor) .execute(&mut *executor)
.await?; .await?;

View File

@ -181,7 +181,7 @@ impl Room {
async fn send_message(&mut self, author_id: PlayerId, body: Str) -> Result<()> { async fn send_message(&mut self, author_id: PlayerId, body: Str) -> Result<()> {
tracing::info!("Adding a message to room"); tracing::info!("Adding a message to room");
self.storage 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?; .await?;
self.message_count += 1; self.message_count += 1;
let update = Updates::NewMessage { let update = Updates::NewMessage {