Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(email): index messaging record campaign lookups (#91723)

Reece Jonesac8ee1236994
diff --git a/posthog/migrations/1331_messagingrecord_campaign_key_idx.py b/posthog/migrations/1331_messagingrecord_campaign_key_idx.py
new file mode 100644
index 000000000000..45b9cb34fdfb
--- /dev/null
+++ b/posthog/migrations/1331_messagingrecord_campaign_key_idx.py
@@ -0,0 +1,18 @@
+from django.db import migrations, models
+
+from posthog.migration_helpers import SafeAddIndexConcurrently
+
+
+class Migration(migrations.Migration):
+ atomic = False
+
+ dependencies = [
+ ("posthog", "1330_alter_team_test_account_filters"),
+ ]
+
+ operations = [
+ SafeAddIndexConcurrently(
+ model_name="messagingrecord",
+ index=models.Index(fields=["campaign_key"], name="messagingrecord_campaign_idx"),
+ ),
+ ]
diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txt
index a87a559fc415..15b63524b349 100644
--- a/posthog/migrations/max_migration.txt
+++ b/posthog/migrations/max_migration.txt
@@ -1 +1 @@
-1330_alter_team_test_account_filters
+1331_messagingrecord_campaign_key_idx
diff --git a/posthog/models/messaging.py b/posthog/models/messaging.py
index 1127f3aed670..9e8d4b4de375 100644
--- a/posthog/models/messaging.py
+++ b/posthog/models/messaging.py
@@ -82,3 +82,4 @@ class MessagingRecord(UUIDTModel):
"email_hash",
"campaign_key",
) # can only send campaign once to each email
+ indexes = [models.Index(fields=["campaign_key"], name="messagingrecord_campaign_idx")]
diff --git a/posthog/test/test_migration_1324.py b/posthog/test/test_migration_1324.py
index 31c0d58d78b4..04459219246a 100644
--- a/posthog/test/test_migration_1324.py
+++ b/posthog/test/test_migration_1324.py
@@ -1,13 +1,14 @@
from typing import Any
-from posthog.test.base import TestMigrations
+from posthog.test.base import NonAtomicTestMigrations
LEGACY_URL = "https://legacy.example.com/.well-known/oauth-client-metadata"
MOVED_URL = "https://moved.example.com/.well-known/oauth-client-metadata"
STRAY_URL = "https://stray.example.com/.well-known/oauth-client-metadata"
-class BackfillCimdClientIdMigrationTest(TestMigrations):
+# The latest migration creates an index concurrently, so teardown must not run inside a transaction.
+class BackfillCimdClientIdMigrationTest(NonAtomicTestMigrations):
migrate_from = "1323_proxyrecord_root_redirect_url"
migrate_to = "1324_backfill_cimd_client_id"