Skip to content

Open source, privacy-first web analytics. Lightweight, cookie-free Google Analytics alternative. Self-hosted or cloud.

[migration] Data fix: rewrite goals for which `event_name` and `page_path` both exist (#3357)

hq1a5bac43981da
diff --git a/lib/plausible/goal/schema.ex b/lib/plausible/goal/schema.ex
index 17ad1123ba..547bc8a7fd 100644
--- a/lib/plausible/goal/schema.ex
+++ b/lib/plausible/goal/schema.ex
@@ -43,6 +43,10 @@ defmodule Plausible.Goal do
|> update_change(:event_name, &String.trim/1)
|> update_change(:page_path, &String.trim/1)
|> validate_length(:event_name, max: 120)
+ |> check_constraint(:event_name,
+ name: :check_event_name_or_page_path,
+ message: "cannot co-exist with page_path"
+ )
|> maybe_drop_currency()
end
diff --git a/priv/repo/migrations/20230918084301_fix_broken_goals.exs b/priv/repo/migrations/20230918084301_fix_broken_goals.exs
new file mode 100644
index 0000000000..4586b64d33
--- /dev/null
+++ b/priv/repo/migrations/20230918084301_fix_broken_goals.exs
@@ -0,0 +1,29 @@
+defmodule Plausible.Repo.Migrations.FixBrokenGoals do
+ use Ecto.Migration
+
+ @disable_ddl_transaction true
+ @disable_migration_lock true
+
+ def up do
+ execute("""
+ UPDATE goals SET page_path = NULL WHERE page_path IS NOT NULL AND event_name IS NOT NULL
+ """)
+
+ execute("""
+ ALTER TABLE goals
+ ADD CONSTRAINT check_event_name_or_page_path
+ CHECK (
+ (event_name IS NOT NULL AND page_path IS NULL) OR
+ (event_name IS NULL AND page_path IS NOT NULL)
+ )
+ NOT VALID;
+ """)
+ end
+
+ def down do
+ execute("""
+ ALTER TABLE goals
+ DROP CONSTRAINT check_event_name_or_page_path;
+ """)
+ end
+end
diff --git a/test/plausible/goals_test.exs b/test/plausible/goals_test.exs
index 7cf9d27234..daeebff4af 100644
--- a/test/plausible/goals_test.exs
+++ b/test/plausible/goals_test.exs
@@ -174,4 +174,13 @@ defmodule Plausible.GoalsTest do
assert [^g3, ^g2] = Goals.for_site(site)
end
+
+ test "must be either page_path or event_name" do
+ site = insert(:site)
+
+ assert {:error, changeset} =
+ Goals.create(site, %{"page_path" => "/foo", "event_name" => "/foo"})
+
+ assert {"cannot co-exist with page_path", _} = changeset.errors[:event_name]
+ end
end