Skip to content
1        10        20        30        40        50        60        70        80        90        100       1101use crate::db::Database;2use crate::models::User;34impl Database {5    /// Creates the account and consumes its invite atomically.6    pub async fn create_user_with_invite(&self, user: &User, invite: &str) -> Result<bool, String> {7        let conn = self.conn().await?;8        conn.execute("BEGIN IMMEDIATE", ())9            .await10            .map_err(|e| e.to_string())?;1112        let result: Result<bool, String> = async {13            let mut rows = conn14                .query("SELECT 1 FROM invites WHERE token = ?1", turso::params![invite])15                .await16                .map_err(|e| e.to_string())?;17            if rows.next().await.map_err(|e| e.to_string())?.is_none() {18                return Ok(false);19            }2021            conn.execute(22                "INSERT INTO users (id, username, email, password_hash, created_at) VALUES (?1, ?2, ?3, ?4, ?5)",23                turso::params![24                    user.id.clone(),25                    user.username.clone(),26                    user.email.clone(),27                    user.password_hash.clone(),28                    user.created_at.clone()29                ],30            )31            .await32            .map_err(|e| e.to_string())?;33            conn.execute(34                "DELETE FROM invites WHERE token = ?1",35                turso::params![invite],36            )37            .await38            .map_err(|e| e.to_string())?;39            Ok(true)40        }41        .await;4243        match result {44            Ok(true) => {45                conn.execute("COMMIT", ())46                    .await47                    .map_err(|e| e.to_string())?;48                Ok(true)49            }50            Ok(false) => {51                conn.execute("ROLLBACK", ())52                    .await53                    .map_err(|e| e.to_string())?;54                Ok(false)55            }56            Err(error) => {57                conn.execute("ROLLBACK", ())58                    .await59                    .map_err(|rollback| format!("{error} (rollback also failed: {rollback})"))?;60                Err(error)61            }62        }63    }6465    pub async fn get_user_by_username(&self, username: &str) -> Result<Option<User>, String> {66        let mut rows = self67            .conn()68            .await?69            .query(70                "SELECT id, username, email, password_hash, created_at FROM users WHERE username = ?1",71                turso::params![username],72            )73            .await74            .map_err(|e| e.to_string())?;7576        Self::row_to_user(rows.next().await.map_err(|e| e.to_string())?)77    }7879    pub async fn get_user_by_id(&self, user_id: &str) -> Result<Option<User>, String> {80        let mut rows = self81            .conn()82            .await?83            .query(84                "SELECT id, username, email, password_hash, created_at FROM users WHERE id = ?1",85                turso::params![user_id],86            )87            .await88            .map_err(|e| e.to_string())?;8990        Self::row_to_user(rows.next().await.map_err(|e| e.to_string())?)91    }9293    fn row_to_user(row: Option<turso::Row>) -> Result<Option<User>, String> {94        match row {95            Some(row) => Ok(Some(User {96                id: row.get(0).map_err(|e| e.to_string())?,97                username: row.get(1).map_err(|e| e.to_string())?,98                email: row.get(2).map_err(|e| e.to_string())?,99                password_hash: row.get(3).map_err(|e| e.to_string())?,100                created_at: row.get(4).map_err(|e| e.to_string())?,101            })),102            None => Ok(None),103        }104    }105}106107#[cfg(test)]108mod tests {109    use super::*;110111    async fn setup_db() -> (Database, String) {112        let db_path = format!("/tmp/test_pear_users_{}.db", uuid::Uuid::new_v4());113        let db = Database::new(&db_path);114        db.init().await.expect("init");115        (db, db_path)116    }117118    fn test_user() -> User {119        User {120            id: uuid::Uuid::new_v4().to_string(),121            username: "testuser".to_string(),122            email: Some("test@example.com".to_string()),123            password_hash: "hash".to_string(),124            created_at: chrono::Utc::now().to_rfc3339(),125        }126    }127128    #[tokio::test]129    async fn test_create_and_get_user() {130        let (db, db_path) = setup_db().await;131        let user = test_user();132        db.create_invite("test-invite")133            .await134            .expect("create invite");135        assert!(136            db.create_user_with_invite(&user, "test-invite")137                .await138                .expect("create user")139        );140141        let by_name = db.get_user_by_username("testuser").await.unwrap();142        assert_eq!(by_name.as_ref().map(|u| &u.id), Some(&user.id));143144        let by_id = db.get_user_by_id(&user.id).await.unwrap();145        assert_eq!(by_id.map(|u| u.username), Some("testuser".to_string()));146147        let _ = std::fs::remove_file(&db_path);148    }149150    #[tokio::test]151    async fn test_get_missing_user_is_none() {152        let (db, db_path) = setup_db().await;153        assert!(db.get_user_by_username("nobody").await.unwrap().is_none());154        let _ = std::fs::remove_file(&db_path);155    }156}