use crate::models::user::User; use crate::db::Database; pub struct UserRepository { db: Database, } impl UserRepository { pub fn new(db: Database) -> Self { UserRepository { db } } pub async fn get_all(&self) -> Result, sqlx::Error> { sqlx::query_as::<_, User>("SELECT * FROM usersss").fetch_all(&self.db.0).await } pub async fn get_by_id(&self, item_id: &str) -> Result { sqlx::query_as::<_, User>("SELECT * FROM usersss WHERE id = $1") .bind(item_id) .fetch_one(&self.db.0) .await } pub async fn get_many_by_id( &self, items_ids: &[&str], ) -> Result, sqlx::Error> { if items_ids.is_empty() { return Ok(vec![]); } let placeholder_params: String = (1..=(items_ids.len())) .map(|i| format!("${}", i)) .collect::>() .join(","); let query_sql = format!( "SELECT * FROM usersss WHERE id IN ({})", placeholder_params ); let mut query = sqlx::query_as::<_, User>(&query_sql); for id in items_ids { query = query.bind(id); } query.fetch_all(&self.db.0).await } pub async fn insert(&self, entity: &User) -> Result<(), sqlx::Error> { sqlx::query( "INSERT INTO usersss (id, handle, full_name, prefered_color, last_login_at, status, groups, avatar_bytes) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)", ) .bind(&entity.id) .bind(&entity.handle) .bind(&entity.full_name) .bind(&entity.prefered_color) .bind(&entity.last_login_at) .bind(&entity.status) .bind(&entity.groups) .bind(&entity.avatar_bytes) .execute(&self.db.0) .await?; Ok(()) } pub async fn insert_many(&self, entities: &Vec) -> Result<(), sqlx::Error> { let values_templates: String = (1..(8usize * entities.len() + 1)) .collect::>() .chunks(8usize) .map(|c| c.to_vec()) .map(|x| { format!( "({})", x.iter().map(| i | format!("${}", i)).collect:: < Vec < String >> ().join(", ") ) }) .collect::>() .join(", "); let query_sql = format!( "INSERT INTO usersss (id, handle, full_name, prefered_color, last_login_at, status, groups, avatar_bytes) VALUES {} ON CONFLICT DO NOTHING", values_templates ); let mut query = sqlx::query(&query_sql); for entity in entities { query = query .bind(&entity.id) .bind(&entity.handle) .bind(&entity.full_name) .bind(&entity.prefered_color) .bind(&entity.last_login_at) .bind(&entity.status) .bind(&entity.groups) .bind(&entity.avatar_bytes); } query.execute(&self.db.0).await?; Ok(()) } pub async fn update_by_id( &self, item_id: &str, entity: &User, ) -> Result<(), sqlx::Error> { sqlx::query( "UPDATE usersss SET id = $2, handle = $3, full_name = $4, prefered_color = $5, last_login_at = $6, status = $7, groups = $8, avatar_bytes = $9 WHERE id = $1", ) .bind(item_id) .bind(&entity.id) .bind(&entity.handle) .bind(&entity.full_name) .bind(&entity.prefered_color) .bind(&entity.last_login_at) .bind(&entity.status) .bind(&entity.groups) .bind(&entity.avatar_bytes) .execute(&self.db.0) .await?; Ok(()) } pub async fn delete_by_id(&self, item_id: &str) -> Result<(), sqlx::Error> { sqlx::query("DELETE FROM usersss WHERE id = $1") .bind(item_id) .execute(&self.db.0) .await?; Ok(()) } }