backbone_catalog/infrastructure/persistence/
attribute_repository.rs1use sqlx::PgPool;
16use uuid::Uuid;
17
18use crate::domain::entity::Attribute;
19
20pub const TABLE_NAME: &str = "catalog.attributes";
22
23pub struct AttributeRepository(
28 backbone_orm::GenericCrudRepository<Attribute, backbone_orm::SoftDelete>,
29);
30
31impl std::ops::Deref for AttributeRepository {
32 type Target = backbone_orm::GenericCrudRepository<Attribute, backbone_orm::SoftDelete>;
33 fn deref(&self) -> &Self::Target { &self.0 }
34}
35
36impl AttributeRepository {
37 pub fn new(pool: PgPool) -> Self {
39 Self(backbone_orm::GenericCrudRepository::new(pool, TABLE_NAME))
40 }
41}
42
43pub struct NewAttributeRow<'a> {
45 pub id: Uuid,
46 pub code: &'a str,
47 pub name: &'a str,
48 pub attribute_type: &'a str,
49}
50
51impl AttributeRepository {
53 pub async fn exists_id(&self, executor: impl sqlx::Executor<'_, Database = sqlx::Postgres>, id: Uuid) -> Result<bool, sqlx::Error> {
56 let found: Option<Uuid> = sqlx::query_scalar(
57 "SELECT id FROM catalog.attributes \
58 WHERE id = $1 AND (metadata->>'deleted_at') IS NULL",
59 )
60 .bind(id)
61 .fetch_optional(executor)
62 .await?;
63 Ok(found.is_some())
64 }
65
66 pub async fn find_id_by_code(
69 &self,
70 executor: impl sqlx::Executor<'_, Database = sqlx::Postgres>,
71 code: &str,
72 ) -> Result<Option<Uuid>, sqlx::Error> {
73 let id: Option<Uuid> = sqlx::query_scalar(
74 "SELECT id FROM catalog.attributes \
75 WHERE code=$1 AND (metadata->>'deleted_at') IS NULL",
76 )
77 .bind(code)
78 .fetch_optional(executor)
79 .await?;
80 Ok(id)
81 }
82
83 pub async fn insert_attribute(
86 &self,
87 executor: impl sqlx::Executor<'_, Database = sqlx::Postgres>,
88 r: &NewAttributeRow<'_>,
89 ) -> Result<(), sqlx::Error> {
90 sqlx::query(
91 r#"INSERT INTO catalog.attributes (id, code, name, attribute_type, status)
92 VALUES ($1,$2,$3,$4::attribute_type,'active'::catalog_status)"#,
93 )
94 .bind(r.id)
95 .bind(r.code)
96 .bind(r.name)
97 .bind(r.attribute_type)
98 .execute(executor)
99 .await?;
100 Ok(())
101 }
102}
103
104backbone_core::impl_crud_repository!(AttributeRepository, Attribute, soft_delete);