cargagep-v2/src/services/database/units.rs
Antoine Pelletier 7e958b89c6 feat: add oidc
2026-08-23 22:20:27 +02:00

48 lines
1.3 KiB
Rust

//! 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<Vec<Unit>, 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<Vec<Unit>, 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)
}
}