From: Karen Konou Date: Sat, 9 Feb 2019 19:52:11 +0000 (+0100) Subject: Add unique index and unique constraint check, uniqueness test fails X-Git-Url: https://git.squeep.com/?a=commitdiff_plain;h=6a150de3bd416cfe0b4870deee2e6557791345f8;p=akkoma Add unique index and unique constraint check, uniqueness test fails --- diff --git a/lib/pleroma/web/thread_mute.ex b/lib/pleroma/web/thread_mute.ex index 146de0d80..b5bff86be 100644 --- a/lib/pleroma/web/thread_mute.ex +++ b/lib/pleroma/web/thread_mute.ex @@ -13,12 +13,22 @@ defmodule Pleroma.Web.ThreadMute do field(:context, :string) end + def changeset(mute, params \\ %{}) do + mute + |> Ecto.Changeset.cast(params, [:user_id, :context]) + |> Ecto.Changeset.foreign_key_constraint(:user_id) + |> Ecto.Changeset.unique_constraint(:user_id, name: :unique_index) + end + def add_mute(user, id) do activity = Activity.get_by_id(id) context = activity.data["context"] - mute = %Pleroma.Web.ThreadMute{user_id: user.id, context: context} - Repo.insert(mute) - {:ok, activity} + changeset = changeset(%Pleroma.Web.ThreadMute{}, %{user_id: user.id, context: context}) + + case Repo.insert(changeset) do + {:ok, _} -> {:ok, activity} + {:error, _} -> {:error, "conversation is already muted"} + end end def remove_mute(user, id) do diff --git a/priv/repo/migrations/20190205114625_create_thread_mutes.exs b/priv/repo/migrations/20190205114625_create_thread_mutes.exs index b16f557f0..8e9eccbae 100644 --- a/priv/repo/migrations/20190205114625_create_thread_mutes.exs +++ b/priv/repo/migrations/20190205114625_create_thread_mutes.exs @@ -7,6 +7,6 @@ defmodule Pleroma.Repo.Migrations.CreateThreadMutes do add :context, :string end - create index(:thread_mutes, [:user_id]) + create unique_index(:thread_mutes, [:user_id, :context], name: :unique_index) end end diff --git a/test/web/thread_mute_test.exs b/test/web/thread_mute_test.exs index 119a06f52..f3a24613c 100644 --- a/test/web/thread_mute_test.exs +++ b/test/web/thread_mute_test.exs @@ -18,17 +18,20 @@ defmodule Pleroma.Web.ThreadMuteTest do end test "add mute", %{user: user, activity: activity} do - id = activity.id - {:ok, _activity} = add_mute(user, id) + {:ok, _activity} = add_mute(user, activity.id) assert muted?(user, activity) end test "remove mute", %{user: user, activity: activity} do - id = activity.id - - add_mute(user, id) - {:ok, _activity} = remove_mute(user, id) + add_mute(user, activity.id) + {:ok, _activity} = remove_mute(user, activity.id) refute muted?(user, activity) end + + test "check that mutes can't be duplicate", %{user: user, activity: activity} do + add_mute(user, activity.id) + assert muted?(user, activity) + {:error, _} = add_mute(user, activity.id) + end end end