You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

102 lines
2.8 KiB

5 years ago
use std::convert::TryFrom;
use mio::Token;
use rusqlite::params;
use crate::database::Db;
use crate::id::Id;
use crate::player::Player;
use crate::result::RudeResult;
use crate::try_log;
impl Db {
/// Get all connected players in a room
pub fn find_connected_players_by_location(
&self,
location: Id,
) -> RudeResult<Vec<(Token, Player)>> {
let mut statement = try_log!(
self.0.prepare(
"select connected_players.token, players.id, players.name, players.password, players.created, players.location from connected_players, players where players.location = ? and connected_players.player = players.id;"
),
"Unable to prepare sql statement"
);
let mut rows = try_log!(
statement.query(params![location]),
"Unable to perform query"
);
let mut v = Vec::<(Token, Player)>::new();
while let Some(row) = try_log!(rows.next(), "Unable to retrieve row") {
let row_token: i64 = try_log!(row.get("token"), "Unable to get token");
let token: Token = Token(usize::from_le_bytes(row_token.to_le_bytes()));
5 years ago
let player = try_log!(Player::try_from(row), "Unable to get Player from Row");
v.push((token, player));
}
Ok(v)
}
/// Load a player from the database.
pub fn get_connected_player(&self, token: Token) -> RudeResult<Option<Player>> {
let mut statement = try_log!(
self.0.prepare(
"select connected_players.token, players.id, players.name, players.password, players.created, players.location from connected_players, players where connected_players.token = ? and connected_players.player = players.id;"
),
"Unable to prepare sql statement"
);
let mut rows = try_log!(
statement.query(params![i64::from_le_bytes(token.0.to_le_bytes())]),
"Unable to perform query"
);
if let Some(row) = try_log!(rows.next(), "Unable to retrieve row") {
Ok(Some(try_log!(
Player::try_from(row),
"Unable to get Player from Row"
)))
} else {
Ok(None)
}
}
/// Save a connected player to the database.
pub fn save_connected_player(&self, token: Token, player: &Player) -> RudeResult<()> {
let mut statement = try_log!(
self.0.prepare(
"insert into connected_players (token, player) values (?, ?) on conflict(token) do update set player=?;"
),
"Unable to prepare sql statement"
);
let _ = try_log!(
statement.execute(params![
i64::from_le_bytes(token.0.to_le_bytes()),
player.id,
player.id,
]),
"Unable to perform query"
);
Ok(())
}
/// Remove player from connected_players table
pub fn remove_connected_player(&self, token: Token) -> RudeResult<()> {
let mut statement = try_log!(
self.0
.prepare("delete from connected_players where token = ?;"),
"Unable to prepare sql statement"
);
let _ = try_log!(
statement.execute(params![i64::from_le_bytes(token.0.to_le_bytes())]),
"Unable to execute sql statement"
);
Ok(())
}
}