From d2d5341a89bc9bdd1f90d0ea2e0ab8d164504c38 Mon Sep 17 00:00:00 2001 From: Joseph Livesey Date: Thu, 4 Jan 2024 18:47:37 -0500 Subject: [PATCH] fix(sqlite): fix code smells around 'get_recipe_models_for_item' query --- crates/persistence/src/models.rs | 2 +- crates/persistence/src/sqlite/mod.rs | 20 ++++++++------------ 2 files changed, 9 insertions(+), 13 deletions(-) diff --git a/crates/persistence/src/models.rs b/crates/persistence/src/models.rs index 1aa9a34..238c048 100644 --- a/crates/persistence/src/models.rs +++ b/crates/persistence/src/models.rs @@ -39,7 +39,7 @@ pub struct NewRecipe<'a> { pub name: &'a str, } -#[derive(Queryable)] +#[derive(Queryable, Selectable)] #[diesel(table_name = recipes)] pub struct RecipeModel { pub id: i32, diff --git a/crates/persistence/src/sqlite/mod.rs b/crates/persistence/src/sqlite/mod.rs index f119102..b8bd876 100644 --- a/crates/persistence/src/sqlite/mod.rs +++ b/crates/persistence/src/sqlite/mod.rs @@ -226,22 +226,18 @@ impl SqliteStore { .optional()?) } - fn get_item_recipes( + fn get_recipe_models_for_item( connection: &mut SqliteConnection, item_id: i32, - ) -> Result, StoreError> { + ) -> Result>, StoreError> { use crate::schema::{items_recipes, recipes}; Ok(items_recipes::table .filter(items_recipes::item_id.eq(item_id)) - .left_join(recipes::table.on(recipes::id.eq(items_recipes::recipe_id))) - .select(recipes::name.nullable()) - .load::>(connection) - .optional()? - .into_iter() - .flatten() - .flatten() - .collect::>()) + .inner_join(recipes::table.on(recipes::id.eq(items_recipes::recipe_id))) + .select(RecipeModel::as_select()) + .load(connection) + .optional()?) } } @@ -505,7 +501,7 @@ impl Storage for SqliteStore { .into_iter() .map(|item| { let section = Self::get_section_model_for_item(connection, item.id)?; - let item_recipes = Self::get_item_recipes(connection, item.id)?; + let item_recipes = Self::get_recipe_models_for_item(connection, item.id)?; let mut item: common::item::Item = item.into(); @@ -513,7 +509,7 @@ impl Storage for SqliteStore { item = item.with_section(section.name()); } - if !item_recipes.is_empty() { + if let Some(item_recipes) = item_recipes { item = item.with_recipes( item_recipes .into_iter()