//! Units. Rows are created on demand, from the group names Whiskey hands out. use async_trait::async_trait; use sqlx::{query, query_as}; use crate::{ core::{ models::unit::Unit, repositories::{RepositoryError, units_repository::UnitsRepository}, }, services::database::SqlxDatabase, }; #[async_trait] impl UnitsRepository for SqlxDatabase { async fn get_units(&self) -> Result, RepositoryError> { Ok( query_as!(Unit, r#"SELECT id, "name" FROM units ORDER BY "name""#) .fetch_all(&self.pool) .await?, ) } async fn upsert_units(&self, names: &[String]) -> Result, RepositoryError> { let mut tx = self.pool.begin().await?; query!( r#"INSERT INTO units ("name") SELECT DISTINCT UNNEST($1::text[]) ON CONFLICT ("name") DO NOTHING"#, names ) .execute(&mut *tx) .await?; // Read back after the insert: the ones that already existed are in here too let units = query_as!( Unit, r#"SELECT id, "name" FROM units WHERE "name" = ANY($1::text[]) ORDER BY "name""#, names ) .fetch_all(&mut *tx) .await?; tx.commit().await?; Ok(units) } }