nil_server_database/database/
user.rs1use super::BlockingDatabase;
5use crate::error::{Error, Result};
6use crate::model::user::{NewUser, User};
7use crate::sql_types::id::UserId;
8use crate::sql_types::player_id::db_PlayerId;
9use diesel::prelude::*;
10use diesel::result::{DatabaseErrorKind, Error as DieselError};
11use either::Either;
12
13impl BlockingDatabase {
14 pub fn count_games_by_user(&self, id: db_PlayerId) -> Result<i64> {
15 self.count_games_by_user_id(self.get_user_id(id)?)
16 }
17
18 pub fn count_games_by_user_id(&self, id: UserId) -> Result<i64> {
19 use crate::schema::game;
20
21 game::table
22 .filter(game::created_by.eq(id))
23 .count()
24 .get_result(&mut *self.conn())
25 .map_err(Into::into)
26 }
27
28 pub fn create_user(&self, new: &NewUser) -> Result<usize> {
29 use crate::schema::user;
30
31 let result = diesel::insert_into(user::table)
32 .values(new)
33 .execute(&mut *self.conn());
34
35 if let Err(DieselError::DatabaseError(kind, _)) = &result
36 && let DatabaseErrorKind::UniqueViolation = kind
37 {
38 Err(Error::UserAlreadyExists(new.player_id()))
39 } else {
40 Ok(result?)
41 }
42 }
43
44 pub fn get_user(&self, id: db_PlayerId) -> Result<User> {
45 use crate::schema::user;
46
47 let result = user::table
48 .filter(user::player_id.eq(&id))
49 .select(User::as_select())
50 .first(&mut *self.conn());
51
52 if let Err(DieselError::NotFound) = &result {
53 Err(Error::UserNotFound(Either::Left(id)))
54 } else {
55 Ok(result?)
56 }
57 }
58
59 pub fn get_user_by_id(&self, id: UserId) -> Result<User> {
60 use crate::schema::user;
61
62 let result = user::table
63 .find(id)
64 .select(User::as_select())
65 .first(&mut *self.conn());
66
67 if let Err(DieselError::NotFound) = &result {
68 Err(Error::UserNotFound(Either::Right(id)))
69 } else {
70 Ok(result?)
71 }
72 }
73
74 pub fn get_user_id(&self, id: db_PlayerId) -> Result<UserId> {
75 use crate::schema::user;
76
77 let result = user::table
78 .filter(user::player_id.eq(&id))
79 .select(user::id)
80 .first(&mut *self.conn());
81
82 if let Err(DieselError::NotFound) = &result {
83 Err(Error::UserNotFound(Either::Left(id)))
84 } else {
85 Ok(result?)
86 }
87 }
88
89 pub fn get_user_player_id(&self, id: UserId) -> Result<db_PlayerId> {
90 use crate::schema::user;
91
92 let result = user::table
93 .find(id)
94 .select(user::player_id)
95 .first::<db_PlayerId>(&mut *self.conn());
96
97 if let Err(DieselError::NotFound) = &result {
98 Err(Error::UserNotFound(Either::Right(id)))
99 } else {
100 Ok(result?)
101 }
102 }
103
104 pub fn user_exists(&self, id: &db_PlayerId) -> Result<bool> {
105 use crate::schema::user;
106 use diesel::dsl::{exists, select};
107
108 select(exists(user::table.filter(user::player_id.eq(id))))
109 .get_result(&mut *self.conn())
110 .map_err(Into::into)
111 }
112}