Skip to content

Commit

Permalink
fix: Recipe upsert doesn't trigger stack foreign key (#1140)
Browse files Browse the repository at this point in the history
  • Loading branch information
michaeljguarino authored Jul 4, 2023
1 parent 00c69db commit 59c11af
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 10 deletions.
4 changes: 4 additions & 0 deletions apps/core/lib/core/schema/recipe_section.ex
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ defmodule Core.Schema.RecipeSection do
timestamps()
end

def for_recipe(query \\ __MODULE__, recipe_id) do
from(r in query, where: r.recipe_id == ^recipe_id)
end

@valid ~w(index repository_id recipe_id)a

def changeset(model, attrs \\ %{}) do
Expand Down
29 changes: 19 additions & 10 deletions apps/core/lib/core/services/recipes.ex
Original file line number Diff line number Diff line change
Expand Up @@ -214,19 +214,28 @@ defmodule Core.Services.Recipes do
recreates it.
"""
@spec upsert(map, binary, User.t) :: recipe_resp
def upsert(%{name: name} = attrs, repo_id, user) do
def upsert(%{name: name, sections: sections} = attrs, repo_id, user) do
start_transaction()
|> add_operation(:wipe, fn _ ->
case get_by_name(name, repo_id) do
%Recipe{} = recipe -> Core.Repo.delete(recipe)
_ -> {:ok, %{id: nil}}
end
|> add_operation(:get, fn _ -> {:ok, get_by_name(name, repo_id)} end)
|> add_operation(:wipe, fn
%{get: %{id: id}} ->
RecipeSection.for_recipe(id)
|> Core.Repo.delete_all()
|> ok()
_ -> {:ok, nil}
end)
|> add_operation(:create, fn %{wipe: %{id: id}} ->
Map.put(attrs, :id, id)
|> create(repo_id, user)
|> add_operation(:recipe, fn %{get: get} ->
case get do
%Recipe{} = r -> r
nil -> %Recipe{repository_id: repo_id}
end
|> Recipe.changeset(build_dependencies(attrs))
|> allow(user, :edit)
|> when_ok(&Core.Repo.insert_or_update/1)
end)
|> execute(extract: :create)
|> build_sections(sections)
|> execute(extract: :recipe)
|> when_ok(&hydrate/1)
end

@doc """
Expand Down
5 changes: 5 additions & 0 deletions apps/core/test/services/recipes_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,11 @@ defmodule Core.Services.RecipesTest do
other_repo_section = Enum.find(recipe.recipe_sections, & &1.repository_id == other_repo.id)
assert length(other_repo_section.configuration) == 1

# verify stack membership has no effect
stack = insert(:stack)
collection = insert(:stack_collection, provider: :aws, stack: stack)
insert(:stack_recipe, collection: collection, recipe: recipe)

{:ok, new} = Recipes.upsert(%{
name: "recipe",
sections: [
Expand Down

0 comments on commit 59c11af

Please sign in to comment.