use sqlx::PgPool;
use uuid::Uuid;
use crate::domain::entity::AttributeValue;
pub const TABLE_NAME: &str = "catalog.attribute_values";
pub struct AttributeValueRepository(
backbone_orm::GenericCrudRepository<AttributeValue, backbone_orm::SoftDelete>,
);
impl std::ops::Deref for AttributeValueRepository {
type Target = backbone_orm::GenericCrudRepository<AttributeValue, backbone_orm::SoftDelete>;
fn deref(&self) -> &Self::Target { &self.0 }
}
impl AttributeValueRepository {
pub fn new(pool: PgPool) -> Self {
Self(backbone_orm::GenericCrudRepository::new(pool, TABLE_NAME))
}
}
pub struct NewAttributeValueRow<'a> {
pub id: Uuid,
pub attribute_id: Uuid,
pub code: &'a str,
pub label: &'a str,
pub label_en: Option<&'a str>,
pub swatch_hex: Option<&'a str>,
pub sort_order: i32,
}
#[derive(Debug, Clone)]
pub struct AttributeValueResolveRow {
pub id: Uuid,
pub label: String,
}
impl AttributeValueRepository {
pub async fn find_value_with_attribute(
&self,
executor: impl sqlx::Executor<'_, Database = sqlx::Postgres>,
attr_code: &str,
val_code: &str,
) -> Result<Option<AttributeValueResolveRow>, sqlx::Error> {
let row: Option<(Uuid, String)> = sqlx::query_as(
r#"SELECT av.id, av.label
FROM catalog.attribute_values av
JOIN catalog.attributes a ON a.id = av.attribute_id
WHERE a.code = $1 AND av.code = $2
AND (a.metadata->>'deleted_at') IS NULL
AND (av.metadata->>'deleted_at') IS NULL"#,
)
.bind(attr_code)
.bind(val_code)
.fetch_optional(executor)
.await?;
Ok(row.map(|(id, label)| AttributeValueResolveRow { id, label }))
}
pub async fn insert_attribute_value(
&self,
executor: impl sqlx::Executor<'_, Database = sqlx::Postgres>,
r: &NewAttributeValueRow<'_>,
) -> Result<(), sqlx::Error> {
sqlx::query(
r#"INSERT INTO catalog.attribute_values
(id, attribute_id, code, label, label_en, swatch_hex, sort_order, status)
VALUES ($1,$2,$3,$4,$5,$6,$7,'active'::catalog_status)"#,
)
.bind(r.id)
.bind(r.attribute_id)
.bind(r.code)
.bind(r.label)
.bind(r.label_en)
.bind(r.swatch_hex)
.bind(r.sort_order)
.execute(executor)
.await?;
Ok(())
}
}
backbone_core::impl_crud_repository!(AttributeValueRepository, AttributeValue, soft_delete);