Add constraint enforcing at most one owner membership per site (#3403)

This commit is contained in:
Adrian Gruntkowski 2023-10-10 11:43:38 +02:00 committed by GitHub
parent 842bbb7995
commit 21297b666f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 28 additions and 0 deletions

View File

@ -0,0 +1,13 @@
defmodule Plausible.Repo.Migrations.AddUniqueIndexOnSiteMembershipsSiteIdWhenOwner do
use Ecto.Migration
@disable_ddl_transaction true
@disable_migration_lock true
def change do
create_if_not_exists unique_index(:site_memberships, [:site_id],
where: "role = 'owner'",
concurrently: true
)
end
end

View File

@ -0,0 +1,15 @@
defmodule Plausible.Site.MembershipTest do
use Plausible.DataCase
test "raises on trying to insert two owner memberships for the same site" do
user1 = insert(:user)
user2 = insert(:user)
site = insert(:site)
insert(:site_membership, site: site, user: user1, role: "owner")
assert_raise Ecto.ConstraintError, ~r/site_memberships_site_id_index/, fn ->
insert(:site_membership, site: site, user: user2, role: "owner")
end
end
end