From 1fe54c5c389a272f9f8e7b58173bb36991108f1e Mon Sep 17 00:00:00 2001 From: Aravinth Manivannan Date: Mon, 15 Jul 2024 17:54:08 +0530 Subject: [PATCH] feat: impl product name exists for category DB port --- .../product_name_exists_for_category.rs | 78 +++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 src/inventory/adapters/output/db/postgres/product_name_exists_for_category.rs diff --git a/src/inventory/adapters/output/db/postgres/product_name_exists_for_category.rs b/src/inventory/adapters/output/db/postgres/product_name_exists_for_category.rs new file mode 100644 index 0000000..c2f1f45 --- /dev/null +++ b/src/inventory/adapters/output/db/postgres/product_name_exists_for_category.rs @@ -0,0 +1,78 @@ +// SPDX-FileCopyrightText: 2024 Aravinth Manivannan +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +use super::InventoryDBPostgresAdapter; +use crate::inventory::application::port::output::db::{ + errors::*, product_name_exists_for_category::*, +}; +use crate::inventory::domain::product_aggregate::*; + +#[async_trait::async_trait] +impl ProductNameExistsForCategoryDBPort for InventoryDBPostgresAdapter { + async fn product_name_exists_for_category(&self, s: &Product) -> InventoryDBResult { + let res = sqlx::query!( + "SELECT EXISTS ( + SELECT 1 + FROM cqrs_inventory_product_query + WHERE + name = $1 + AND + category_id = $2 + );", + s.name(), + s.category_id(), + ) + .fetch_one(&self.pool) + .await?; + if let Some(x) = res.exists { + Ok(x) + } else { + Ok(false) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::inventory::adapters::output::db::postgres::product_id_exists::tests::create_dummy_product_record; + use crate::inventory::domain::add_product_command::tests::get_command; + use crate::utils::uuid::tests::UUID; + + #[actix_rt::test] + async fn test_postgres_product_exists() { + let product_name = "foo_product"; + + let settings = crate::settings::tests::get_settings().await; + settings.create_db().await; + let db = super::InventoryDBPostgresAdapter::new( + sqlx::postgres::PgPool::connect(&settings.database.url) + .await + .unwrap(), + ); + + let cmd = get_command(); + + let product = ProductBuilder::default() + .name(product_name.into()) + .description(cmd.description().as_ref().map(|s| s.to_string())) + .image(cmd.image().as_ref().map(|s| s.to_string())) + .sku_able(cmd.sku_able().clone()) + .category_id(cmd.category_id().clone()) + .product_id(UUID.clone()) + .price(cmd.price().clone()) + .build() + .unwrap(); + + // state doesn't exist + assert!(!db.product_name_exists_for_category(&product).await.unwrap()); + + create_dummy_product_record(&product, &db).await; + + // state exists + assert!(db.product_name_exists_for_category(&product).await.unwrap()); + + settings.drop_db().await; + } +}