forked from lavina/lavina
89 lines
2.5 KiB
Rust
89 lines
2.5 KiB
Rust
use crate::player::PlayerConnection;
|
|
use anyhow::Result;
|
|
|
|
use crate::repo::Storage;
|
|
|
|
impl Storage {
|
|
#[tracing::instrument(skip(self), name = "Storage::is_room_member")]
|
|
pub async fn is_room_member(&self, room_id: u32, player_id: u32) -> Result<bool> {
|
|
let mut executor = self.conn.lock().await;
|
|
let res: (u32,) = sqlx::query_as(
|
|
"
|
|
select
|
|
count(*)
|
|
from
|
|
memberships
|
|
where
|
|
user_id = ? and room_id = ?;
|
|
",
|
|
)
|
|
.bind(player_id)
|
|
.bind(room_id)
|
|
.fetch_one(&mut *executor)
|
|
.await?;
|
|
Ok(res.0 > 0)
|
|
}
|
|
|
|
#[tracing::instrument(skip(self), name = "Storage::add_room_member")]
|
|
pub async fn add_room_member(&self, room_id: u32, player_id: u32) -> Result<()> {
|
|
let mut executor = self.conn.lock().await;
|
|
sqlx::query(
|
|
"insert into memberships(user_id, room_id, status)
|
|
values (?, ?, 1);",
|
|
)
|
|
.bind(player_id)
|
|
.bind(room_id)
|
|
.execute(&mut *executor)
|
|
.await?;
|
|
|
|
Ok(())
|
|
}
|
|
|
|
#[tracing::instrument(skip(self), name = "Storage::remove_room_member")]
|
|
pub async fn remove_room_member(&self, room_id: u32, player_id: u32) -> Result<()> {
|
|
let mut executor = self.conn.lock().await;
|
|
sqlx::query(
|
|
"delete from memberships
|
|
where user_id = ? and room_id = ?;",
|
|
)
|
|
.bind(player_id)
|
|
.bind(room_id)
|
|
.execute(&mut *executor)
|
|
.await?;
|
|
|
|
Ok(())
|
|
}
|
|
|
|
#[tracing::instrument(skip(self, topic), name = "Storage::set_room_topic")]
|
|
pub async fn set_room_topic(&mut self, id: u32, topic: &str) -> Result<()> {
|
|
let mut executor = self.conn.lock().await;
|
|
sqlx::query(
|
|
"update rooms
|
|
set topic = ?
|
|
where id = ?;",
|
|
)
|
|
.bind(topic)
|
|
.bind(id)
|
|
.fetch_optional(&mut *executor)
|
|
.await?;
|
|
|
|
Ok(())
|
|
}
|
|
|
|
pub async fn create_or_retrieve_room_id_by_name(&self, name: &str) -> Result<u32> {
|
|
// TODO we don't need any info except the name on non-owning nodes, should remove stubs here
|
|
let mut executor = self.conn.lock().await;
|
|
let res: (u32,) = sqlx::query_as(
|
|
"insert into rooms(name, topic)
|
|
values (?, '')
|
|
on conflict(name) do update set name = excluded.name
|
|
returning id;",
|
|
)
|
|
.bind(name)
|
|
.fetch_one(&mut *executor)
|
|
.await?;
|
|
|
|
Ok(res.0)
|
|
}
|
|
}
|