From 7199b2cf210b5b04300304420676e83e3ea7466b Mon Sep 17 00:00:00 2001 From: Artur Pata Date: Tue, 12 Nov 2024 13:09:33 +0200 Subject: [PATCH] WIP: Clean up personal and site segments on user leaving a team/sites --- .../20241112100000_cleanup_segments.exs | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 priv/repo/migrations/20241112100000_cleanup_segments.exs diff --git a/priv/repo/migrations/20241112100000_cleanup_segments.exs b/priv/repo/migrations/20241112100000_cleanup_segments.exs new file mode 100644 index 000000000..2a1210b1b --- /dev/null +++ b/priv/repo/migrations/20241112100000_cleanup_segments.exs @@ -0,0 +1,32 @@ +defmodule Plausible.Repo.Migrations.SegmentsCleanup do + use Ecto.Migration + + def up do + execute """ + CREATE OR REPLACE FUNCTION clean_segments() RETURNS trigger AS $$ + BEGIN + UPDATE segments + SET owner_id = null + WHERE site_id in (SELECT id FROM sites WHERE sites.team_id = OLD.team_id) AND owner_id = OLD.user_id AND type = 'site'; + + DELETE FROM segments + WHERE site_id in (SELECT id FROM sites WHERE sites.team_id = OLD.team_id) AND owner_id = OLD.user_id AND type = 'personal'; + + RETURN OLD; + END; + $$ LANGUAGE plpgsql; + """ + + execute """ + CREATE TRIGGER user_deassociated_from_team + AFTER DELETE ON team_memberships + FOR EACH ROW + EXECUTE FUNCTION clean_segments(); + """ + end + + def down do + execute "DROP TRIGGER IF EXISTS user_deassociated_from_team ON team_memberships;" + execute "DROP FUNCTION IF EXISTS clean_segments();" + end +end