Skip to content
Snippets Groups Projects
Select Git revision
1 result Searching

groups.rs

Blame
  • groups.rs 4.15 KiB
    use crate::models::Group;
    use pyo3::prelude::*;
    use pyo3::exceptions::PyRuntimeError;
    use postgres::{Client, NoTls};
    use crate::models::User;
    
    fn pg_err(e: postgres::Error) -> PyErr {
        PyRuntimeError::new_err(e.to_string())
    }
    
    /// Create a group
    #[pyfunction]
    pub fn create_group(db_url: &str, name: &str) -> PyResult<()> {
        let mut client = Client::connect(db_url, NoTls).map_err(pg_err)?;
        client.execute(
            "INSERT INTO groups (name, member_count) VALUES ($1, $2)", 
            &[&name, &0]  
        ).map_err(pg_err)?;
        Ok(())
    }
    
    /// Retrieve a group by ID.
    #[pyfunction]
    pub fn get_group(db_url: &str, group_id: i32) -> PyResult<Option<Group>> {
        let mut client = Client::connect(db_url, NoTls).map_err(pg_err)?;
        let row_opt = client.query_opt(
            "SELECT id, name, member_count FROM groups WHERE id = $1",
            &[&group_id]
        ).map_err(pg_err)?;
        
        if let Some(row) = row_opt {
            let group = Group {
                id: row.get(0),
                name: row.get(1),
                member_count: row.get(2),
            };
            Ok(Some(group))
        } else {
            Ok(None)
        }
    }
    
    /// Retrieve all groups.
    #[pyfunction]
    pub fn get_all_groups(db_url: &str) -> PyResult<Vec<Group>> {
        let mut client = Client::connect(db_url, NoTls).map_err(pg_err)?;
        let rows = client.query("SELECT id, name, member_count FROM groups", &[])
            .map_err(pg_err)?;
        
        let groups = rows.into_iter().map(|row| Group {
            id: row.get(0),
            name: row.get(1),
            member_count: row.get(2),
        }).collect();
        
        Ok(groups)
    }
    
    /// Add a user to a group.
    #[pyfunction]
    pub fn add_user_to_group(db_url: &str, group_id: i32, user_id: i32) -> PyResult<()> {
        let mut client = Client::connect(db_url, NoTls).map_err(pg_err)?;
        
        // Insert a row to show membership
        client.execute(
            "INSERT INTO group_members (group_id, user_id)
             VALUES ($1, $2)
             ON CONFLICT DO NOTHING",
            &[&group_id, &user_id],
        ).map_err(pg_err)?;