1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
use async_trait::async_trait; use eyre::{eyre, Result}; use sqlx::postgres::PgPoolOptions; use crate::settings::HISTORY_PAGE_SIZE; use super::models::{History, NewHistory, NewSession, NewUser, Session, User}; #[async_trait] pub trait Database { async fn get_session(&self, token: &str) -> Result<Session>; async fn get_session_user(&self, token: &str) -> Result<User>; async fn add_session(&self, session: &NewSession) -> Result<()>; async fn get_user(&self, username: &str) -> Result<User>; async fn get_user_session(&self, u: &User) -> Result<Session>; async fn add_user(&self, user: &NewUser) -> Result<i64>; async fn count_history(&self, user: &User) -> Result<i64>; async fn list_history( &self, user: &User, created_since: chrono::NaiveDateTime, since: chrono::NaiveDateTime, host: &str, ) -> Result<Vec<History>>; async fn add_history(&self, history: &[NewHistory]) -> Result<()>; } #[derive(Clone)] pub struct Postgres { pool: sqlx::Pool<sqlx::postgres::Postgres>, } impl Postgres { pub async fn new(uri: &str) -> Result<Self, sqlx::Error> { let pool = PgPoolOptions::new() .max_connections(100) .connect(uri) .await?; sqlx::migrate!("./migrations").run(&pool).await?; Ok(Self { pool }) } } #[async_trait] impl Database for Postgres { async fn get_session(&self, token: &str) -> Result<Session> { let res: Option<Session> = sqlx::query_as::<_, Session>("select * from sessions where token = $1") .bind(token) .fetch_optional(&self.pool) .await?; if let Some(s) = res { Ok(s) } else { Err(eyre!("could not find session")) } } async fn get_user(&self, username: &str) -> Result<User> { let res: Option<User> = sqlx::query_as::<_, User>("select * from users where username = $1") .bind(username) .fetch_optional(&self.pool) .await?; if let Some(u) = res { Ok(u) } else { Err(eyre!("could not find user")) } } async fn get_session_user(&self, token: &str) -> Result<User> { let res: Option<User> = sqlx::query_as::<_, User>( "select * from users inner join sessions on users.id = sessions.user_id and sessions.token = $1", ) .bind(token) .fetch_optional(&self.pool) .await?; if let Some(u) = res { Ok(u) } else { Err(eyre!("could not find user")) } } async fn count_history(&self, user: &User) -> Result<i64> { let res: (i64,) = sqlx::query_as( "select count(1) from history where user_id = $1", ) .bind(user.id) .fetch_one(&self.pool) .await?; Ok(res.0) } async fn list_history( &self, user: &User, created_since: chrono::NaiveDateTime, since: chrono::NaiveDateTime, host: &str, ) -> Result<Vec<History>> { let res = sqlx::query_as::<_, History>( "select * from history where user_id = $1 and hostname != $2 and created_at >= $3 and timestamp >= $4 order by timestamp asc limit $5", ) .bind(user.id) .bind(host) .bind(created_since) .bind(since) .bind(HISTORY_PAGE_SIZE) .fetch_all(&self.pool) .await?; Ok(res) } async fn add_history(&self, history: &[NewHistory]) -> Result<()> { let mut tx = self.pool.begin().await?; for i in history { let client_id: &str = &i.client_id; let hostname: &str = &i.hostname; let data: &str = &i.data; sqlx::query( "insert into history (client_id, user_id, hostname, timestamp, data) values ($1, $2, $3, $4, $5) on conflict do nothing ", ) .bind(client_id) .bind(i.user_id) .bind(hostname) .bind(i.timestamp) .bind(data) .execute(&mut tx) .await?; } tx.commit().await?; Ok(()) } async fn add_user(&self, user: &NewUser) -> Result<i64> { let email: &str = &user.email; let username: &str = &user.username; let password: &str = &user.password; let res: (i64,) = sqlx::query_as( "insert into users (username, email, password) values($1, $2, $3) returning id", ) .bind(username) .bind(email) .bind(password) .fetch_one(&self.pool) .await?; Ok(res.0) } async fn add_session(&self, session: &NewSession) -> Result<()> { let token: &str = &session.token; sqlx::query( "insert into sessions (user_id, token) values($1, $2)", ) .bind(session.user_id) .bind(token) .execute(&self.pool) .await?; Ok(()) } async fn get_user_session(&self, u: &User) -> Result<Session> { let res: Option<Session> = sqlx::query_as::<_, Session>("select * from sessions where user_id = $1") .bind(u.id) .fetch_optional(&self.pool) .await?; if let Some(s) = res { Ok(s) } else { Err(eyre!("could not find session")) } } }