db.rs (1838B)
1 use deadpool_sqlite::{Config, Pool, Runtime}; 2 3 pub struct DB { 4 pool: Pool, 5 } 6 7 impl DB { 8 pub async fn get_user(&self, username: String) -> color_eyre::Result<Option<(String, String)>> { 9 let conn = self.pool.get().await?; 10 conn.interact(|conn| { 11 let mut stmt = 12 conn.prepare("SELECT token, device_id FROM users WHERE username = ?1")?; 13 let mut rows = stmt.query((username,))?; 14 if let Some(row) = rows.next()? { 15 color_eyre::Result::<Option<(String, String)>>::Ok(Some((row.get(0)?, row.get(1)?))) 16 } else { 17 color_eyre::Result::<Option<(String, String)>>::Ok(None) 18 } 19 }) 20 .await 21 .unwrap() 22 } 23 24 pub async fn set_user( 25 &self, 26 username: String, 27 access_token: String, 28 device_id: String, 29 ) -> color_eyre::Result<()> { 30 let conn = self.pool.get().await?; 31 conn.interact(|conn| { 32 let mut stmt = 33 conn.prepare("INSERT INTO users (username, token, device_id) VALUES (?1, ?2, ?3)")?; 34 stmt.execute((username, access_token, device_id))?; 35 Ok(()) 36 }) 37 .await 38 .unwrap() 39 } 40 } 41 42 pub async fn setup_db() -> color_eyre::Result<DB> { 43 let cfg = Config::new("./store/sip_bridge.sqlite3"); 44 let pool = cfg.create_pool(Runtime::Tokio1).unwrap(); 45 let conn = pool.get().await?; 46 let _ = conn 47 .interact(|conn| { 48 conn.execute( 49 "CREATE TABLE IF NOT EXISTS users ( 50 username TEXT NOT NULL PRIMARY KEY, 51 token TEXT NOT NULL, 52 device_id TEXT NOT NULL 53 )", 54 (), 55 ) 56 }) 57 .await 58 .expect("Failed to create users table"); 59 Ok(DB { pool }) 60 }