use sqlx::PgPool;
use uuid::Uuid;
use crate::domain::entity::Attribute;
pub const TABLE_NAME: &str = "catalog.attributes";
pub struct AttributeRepository(
backbone_orm::GenericCrudRepository<Attribute, backbone_orm::SoftDelete>,
);
impl std::ops::Deref for AttributeRepository {
type Target = backbone_orm::GenericCrudRepository<Attribute, backbone_orm::SoftDelete>;
fn deref(&self) -> &Self::Target { &self.0 }
}
impl AttributeRepository {
pub fn new(pool: PgPool) -> Self {
Self(backbone_orm::GenericCrudRepository::new(pool, TABLE_NAME))
}
}
pub struct NewAttributeRow<'a> {
pub id: Uuid,
pub code: &'a str,
pub name: &'a str,
pub attribute_type: &'a str,
}
impl AttributeRepository {
pub async fn exists_id(&self, executor: impl sqlx::Executor<'_, Database = sqlx::Postgres>, id: Uuid) -> Result<bool, sqlx::Error> {
let found: Option<Uuid> = sqlx::query_scalar(
"SELECT id FROM catalog.attributes \
WHERE id = $1 AND (metadata->>'deleted_at') IS NULL",
)
.bind(id)
.fetch_optional(executor)
.await?;
Ok(found.is_some())
}
pub async fn find_id_by_code(
&self,
executor: impl sqlx::Executor<'_, Database = sqlx::Postgres>,
code: &str,
) -> Result<Option<Uuid>, sqlx::Error> {
let id: Option<Uuid> = sqlx::query_scalar(
"SELECT id FROM catalog.attributes \
WHERE code=$1 AND (metadata->>'deleted_at') IS NULL",
)
.bind(code)
.fetch_optional(executor)
.await?;
Ok(id)
}
pub async fn insert_attribute(
&self,
executor: impl sqlx::Executor<'_, Database = sqlx::Postgres>,
r: &NewAttributeRow<'_>,
) -> Result<(), sqlx::Error> {
sqlx::query(
r#"INSERT INTO catalog.attributes (id, code, name, attribute_type, status)
VALUES ($1,$2,$3,$4::attribute_type,'active'::catalog_status)"#,
)
.bind(r.id)
.bind(r.code)
.bind(r.name)
.bind(r.attribute_type)
.execute(executor)
.await?;
Ok(())
}
}
backbone_core::impl_crud_repository!(AttributeRepository, Attribute, soft_delete);