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(persons): honor -- no-transaction in the persons migration runner (#101441)

posthog[bot]5140e653ac36
diff --git a/posthog/management/commands/apply_persons_migrations.py b/posthog/management/commands/apply_persons_migrations.py
index b276912948ac..a9466fd1e4aa 100644
--- a/posthog/management/commands/apply_persons_migrations.py
+++ b/posthog/management/commands/apply_persons_migrations.py
@@ -9,16 +9,21 @@ Tracks applied migrations in a _persons_migrations_applied table so each
migration is only executed once. Also bridges the sqlx _sqlx_migrations
tracking table so that environments transitioning from sqlx don't re-apply
already-applied migrations.
+
+Each file runs inside a transaction, unless it opens with the -- no-transaction
+marker that CONCURRENTLY index builds need.
"""
from __future__ import annotations
+import re
from pathlib import Path
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
import psycopg
+import sqlparse
from psycopg import sql
from psycopg.conninfo import conninfo_to_dict
@@ -35,6 +40,22 @@ HOBBY_SKIP_MIGRATIONS = {
TRACKING_TABLE = "_persons_migrations_applied"
+# Marker a migration file opens with when it must not run inside a transaction, because
+# Postgres rejects CREATE/DROP INDEX CONCURRENTLY there. Same convention as the sqlx
+# runners that read these files in Rust.
+NO_TRANSACTION_MARKER = "-- no-transaction"
+
+# The index a concurrent build names, so the invalid-index guard below can look at that index
+# alone. Postgres does not accept a schema-qualified name here: the index lands in the table's
+# schema. Inside a quoted name it writes an embedded quote as two quotes, so the name branch
+# accepts a doubled quote to keep such a name parseable.
+CONCURRENT_INDEX_CREATE = re.compile(
+ r"""^\s*CREATE\s+(?:UNIQUE\s+)?INDEX\s+CONCURRENTLY\s+
+ (?:IF\s+NOT\s+EXISTS\s+)?
+ (?P<name>"(?:[^"]|"")+"|[A-Za-z_][A-Za-z0-9_$]*)\s+ON\b""",
+ re.IGNORECASE | re.VERBOSE,
+)
+
def _ensure_tracking_table(cursor) -> None:
cursor.execute(f"""
@@ -74,6 +95,111 @@ def _record_migration(cursor, filename: str) -> None:
cursor.execute(f"INSERT INTO {TRACKING_TABLE} (filename) VALUES (%s)", [filename])
+def _runs_outside_transaction(sql_content: str) -> bool:
+ """Report whether a migration opens with the marker.
+
+ sqlx tests the raw file content with starts_with, so a marker below a header comment or
+ a blank line is transactional under the Rust runners. Match that test exactly: a file
+ this runner accepts must behave the same way in the sqlx job that applies it.
+ """
+ return sql_content.startswith(NO_TRANSACTION_MARKER)
+
+
+def _holds_multiple_statements(sql_content: str) -> bool:
+ """Report whether a migration holds more than one statement.
+
+ A semicolon split miscounts a predicate such as ``WHERE value = ';'``, so leave the
+ parsing to sqlparse. Drop a fragment that is only a comment: the trailing note these
+ files carry is not a statement.
+ """
+ statements = [
+ statement
+ for statement in sqlparse.split(sql_content)
+ if sqlparse.format(statement, strip_comments=True).strip(" \t\r\n;")
+ ]
+ return len(statements) > 1
+
+
+def _concurrent_index_target(sql_content: str) -> str | None:
+ """Return the index name a concurrent build creates, or None for any other statement.
+
+ A concurrent drop returns None on purpose. Its target is often the invalid index itself,
+ so the guard below must let it run.
+ """
+ match = CONCURRENT_INDEX_CREATE.match(sqlparse.format(sql_content, strip_comments=True).strip())
+ if not match:
+ return None
+ name = match.group("name")
+ if not name.startswith('"'):
+ return name.lower()
+ # pg_class holds the name unescaped, so collapse each doubled quote back to one.
+ return name[1:-1].replace('""', '"')
+
+
+def _invalid_indexes_named(cursor, index_name: str) -> list[str]:
+ """Return the qualified names of invalid indexes that carry ``index_name``.
+
+ The connected database can hold indexes this runner does not own: hobby deploys keep the
+ persons tables in the main PostHog database. Match the one name the migration is about to
+ build, so an unrelated interrupted build does not stop the queue.
+ """
+ cursor.execute(
+ """
+ SELECT n.nspname, c.relname
+ FROM pg_index i
+ JOIN pg_class c ON c.oid = i.indexrelid
+ JOIN pg_namespace n ON n.oid = c.relnamespace
+ WHERE NOT i.indisvalid
+ AND c.relkind = 'i'
+ AND c.relname = %s
+ AND n.nspname NOT IN ('pg_catalog', 'information_schema')
+ ORDER BY n.nspname, c.relname
+ """,
+ [index_name],
+ )
+ return [f"{schema}.{name}" for schema, name in cursor.fetchall()]
+
+
+def _apply_without_transaction(cursor, filename: str, sql_content: str) -> None:
+ """Apply a migration with no transaction around it, on the autocommit connection.
+
+ The tracking insert is no longer atomic with the migration body, so an interrupted run
+ can leave the statement applied and unrecorded. A rerun of a CONCURRENTLY build is
+ harmless, except when the interruption left the index INVALID: IF NOT EXISTS then skips
+ the rebuild and the migration is recorded over a broken index. Refuse the run instead,
+ and name the index to drop. Only the index this file builds is checked.
+ """
+ if _holds_multiple_statements(sql_content):
+ raise CommandError(
+ f"{filename} is marked '{NO_TRANSACTION_MARKER}' but holds more than one statement. "
+ "Postgres runs a multi-statement batch in one implicit transaction, which "
+ "CONCURRENTLY rejects. Give each statement its own migration file."
+ )
+
+ target = _concurrent_index_target(sql_content)
+ invalid_indexes = _invalid_indexes_named(cursor, target) if target else []
+ if invalid_indexes:
+ drops = "\n".join(f" DROP INDEX CONCURRENTLY {index};" for index in invalid_indexes)
+ raise CommandError(
+ f"Cannot apply {filename}: the index it builds is INVALID, left by an interrupted "
+ f"CONCURRENTLY build. Drop it, then re-run the migrations:\n{drops}"
+ )
+
+ cursor.execute(sql_content)
+ _record_migration(cursor, filename)
+
+
+def _apply_migration(conn, cursor, sql_file: Path) -> None:
+ sql_content = sql_file.read_text()
+ if _runs_outside_transaction(sql_content):
+ _apply_without_transaction(cursor, sql_file.name, sql_content)
+ return
+
+ with conn.transaction():
+ cursor.execute(sql_content)
+ _record_migration(cursor, sql_file.name)
+
+
def _ensure_database_exists(persons_url: str) -> None:
"""Create the persons database named in ``persons_url`` if it doesn't already exist.
@@ -188,11 +314,8 @@ class Command(BaseCommand):
applied_count += 1
continue
- sql_content = sql_file.read_text()
self.stdout.write(f" Applying {sql_file.name}...")
- with conn.transaction():
- cursor.execute(sql_content)
- _record_migration(cursor, sql_file.name)
+ _apply_migration(conn, cursor, sql_file)
applied_count += 1
action = "Would apply" if dry_run else "Applied"
diff --git a/posthog/management/commands/test/test_apply_persons_migrations.py b/posthog/management/commands/test/test_apply_persons_migrations.py
new file mode 100644
index 000000000000..0ef4b4e04ad7
--- /dev/null
+++ b/posthog/management/commands/test/test_apply_persons_migrations.py
@@ -0,0 +1,206 @@
+from pathlib import Path
+from tempfile import TemporaryDirectory
+from uuid import uuid4
+
+import pytest
+
+from django.core.management import call_command
+from django.core.management.base import CommandError
+from django.test import SimpleTestCase, TestCase
+
+import psycopg
+from parameterized import parameterized
+
+from posthog.management.commands.apply_persons_migrations import (
+ TRACKING_TABLE,
+ _concurrent_index_target,
+ _holds_multiple_statements,
+ _runs_outside_transaction,
+)
+from posthog.persons_db import persons_db_connection
+
+
+def _persons_fetchall(query: str, params: list | None = None) -> list[tuple]:
+ with persons_db_connection(writer=True, autocommit=True) as conn, conn.cursor() as cursor:
+ cursor.execute(query, params)
+ return cursor.fetchall()
+
+
+def _persons_execute(statements: list[str]) -> None:
+ with persons_db_connection(writer=True, autocommit=True) as conn, conn.cursor() as cursor:
+ for statement in statements:
+ cursor.execute(statement)
+
+
+class TestNoTransactionMarker(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("first_line", "-- no-transaction\nCREATE INDEX CONCURRENTLY a ON t (c);", True),
+ ("first_line_with_suffix", "-- no-transaction (concurrent)\nCREATE INDEX CONCURRENTLY a ON t (c);", True),
+ ("after_other_comments", "-- why\n\n-- no-transaction\nCREATE INDEX CONCURRENTLY a ON t (c);", False),
+ ("after_a_blank_line", "\n-- no-transaction\nCREATE INDEX CONCURRENTLY a ON t (c);", False),
+ ("absent", "-- why\nCREATE INDEX a ON t (c);", False),
+ ("only_after_a_statement", "CREATE INDEX a ON t (c);\n-- no-transaction\n", False),
+ ]
+ )
+ def test_marker_detection(self, _name: str, sql_content: str, expected: bool) -> None:
+ assert _runs_outside_transaction(sql_content) is expected
+
+
+class TestMultipleStatementDetection(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("single_statement", "CREATE INDEX CONCURRENTLY i ON t (c);", False),
+ ("semicolon_in_a_string_literal", "CREATE INDEX CONCURRENTLY i ON t (c) WHERE v = ';';", False),
+ ("trailing_comment", "CREATE INDEX CONCURRENTLY i ON t (c);\n-- recovery note\n", False),
+ (
+ "comment_marker_in_a_string_literal",
+ "CREATE INDEX CONCURRENTLY i ON t (c) WHERE v = '--x'; CREATE INDEX j ON t (d);",
+ True,
+ ),
+ ("two_statements", "CREATE TABLE t (id INT);\nCREATE INDEX CONCURRENTLY i ON t (id);", True),
+ ]
+ )
+ def test_statement_counting(self, _name: str, sql_content: str, expected: bool) -> None:
+ assert _holds_multiple_statements(sql_content) is expected
+
+
+class TestConcurrentIndexTarget(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("create", "CREATE INDEX CONCURRENTLY IF NOT EXISTS i ON t (c);", "i"),
+ ("create_below_a_comment_block", "-- no-transaction\n-- why\nCREATE INDEX CONCURRENTLY i ON t (c);", "i"),
+ ("create_unique_over_two_lines", "CREATE UNIQUE INDEX CONCURRENTLY Mixed\n ON t (c);", "mixed"),
+ ("create_with_a_quoted_name", 'CREATE INDEX CONCURRENTLY "Mixed" ON t (c);', "Mixed"),
+ (
+ "create_with_a_doubled_quote_in_the_quoted_name",
+ 'CREATE UNIQUE INDEX CONCURRENTLY "Mixed""unique" ON t (c);',
+ 'Mixed"unique',
+ ),
+ ("create_without_a_name", "CREATE INDEX CONCURRENTLY ON t (c);", None),
+ ("drop", "DROP INDEX CONCURRENTLY IF EXISTS i;", None),
+ ]
+ )
+ def test_target_parsing(self, _name: str, sql_content: str, expected: str | None) -> None:
+ assert _concurrent_index_target(sql_content) == expected
+
+
+class TestApplyPersonsMigrations(TestCase):
+ def setUp(self) -> None:
+ super().setUp()
+ self.suffix = uuid4().hex[:8]
+ self.table = f"no_tx_test_{self.suffix}"
+ self.index = f"no_tx_test_{self.suffix}_idx"
+ self.other_table = f"no_tx_test_{self.suffix}_other"
+ self.other_index = f"no_tx_test_{self.suffix}_other_idx"
+ self._migrations_tmp = TemporaryDirectory()
+ self.migrations_dir = Path(self._migrations_tmp.name)
+
+ def tearDown(self) -> None:
+ _persons_execute(
+ [
+ f"DROP INDEX CONCURRENTLY IF EXISTS {self.index}",
+ f"DROP INDEX CONCURRENTLY IF EXISTS {self.other_index}",
+ f"DROP TABLE IF EXISTS {self.table}",
+ f"DROP TABLE IF EXISTS {self.other_table}",
+ f"DELETE FROM {TRACKING_TABLE} WHERE filename LIKE '%{self.suffix}%'",
+ ]
+ )
+ self._migrations_tmp.cleanup()
+ super().tearDown()
+
+ def _write_migration(self, version: str, name: str, body: str) -> None:
+ (self.migrations_dir / f"{version}_{self.suffix}_{name}.sql").write_text(body)
+
+ def _apply(self) -> None:
+ call_command("apply_persons_migrations", "--migrations-dir", str(self.migrations_dir))
+
+ def _leave_an_invalid_index(self, table: str, index: str) -> None:
+ _persons_execute([f"CREATE TABLE {table} (id INT)", f"INSERT INTO {table} (id) VALUES (1), (1)"])
+ with pytest.raises(psycopg.Error):
+ _persons_execute([f"CREATE UNIQUE INDEX CONCURRENTLY {index} ON {table} (id)"])
+
+ def _recorded_migrations(self) -> list[str]:
+ rows = _persons_fetchall(
+ f"SELECT filename FROM {TRACKING_TABLE} WHERE filename LIKE %s ORDER BY filename",
+ [f"%{self.suffix}%"],
+ )
+ return [row[0] for row in rows]
+
+ def test_applies_a_concurrent_index_build_marked_no_transaction(self) -> None:
+ self._write_migration("20990101000001", "create_table", f"CREATE TABLE {self.table} (id INT);")
+ self._write_migration(
+ "20990101000002",
+ "add_index",
+ f"-- no-transaction\nCREATE INDEX CONCURRENTLY IF NOT EXISTS {self.index} ON {self.table} (id);",
+ )
+
+ self._apply()
+
+ assert _persons_fetchall("SELECT indisvalid FROM pg_index WHERE indexrelid = %s::regclass", [self.index]) == [
+ (True,)
+ ]
+ assert len(self._recorded_migrations()) == 2
+
+ def test_rejects_a_no_transaction_file_holding_more_than_one_statement(self) -> None:
+ self._write_migration(
+ "20990101000001",
+ "two_statements",
+ f"-- no-transaction\nCREATE TABLE {self.table} (id INT);\n"
+ f"CREATE INDEX CONCURRENTLY {self.index} ON {self.table} (id);",
+ )
+
+ with pytest.raises(CommandError, match="more than one statement"):
+ self._apply()
+
+ assert self._recorded_migrations() == []
+
+ def test_applies_a_marked_migration_while_an_unrelated_index_is_invalid(self) -> None:
+ self._leave_an_invalid_index(self.other_table, self.other_index)
+ self._write_migration("20990101000001", "create_table", f"CREATE TABLE {self.table} (id INT);")
+ self._write_migration(
+ "20990101000002",
+ "add_index",
+ f"-- no-transaction\nCREATE INDEX CONCURRENTLY IF NOT EXISTS {self.index} ON {self.table} (id);",
+ )
+
+ self._apply()
+
+ assert _persons_fetchall("SELECT indisvalid FROM pg_index WHERE indexrelid = %s::regclass", [self.index]) == [
+ (True,)
+ ]
+ assert len(self._recorded_migrations()) == 2
+
+ def test_applies_a_concurrent_drop_of_an_invalid_index(self) -> None:
+ self._leave_an_invalid_index(self.table, self.index)
+ self._write_migration(
+ "20990101000001",
+ "drop_index",
+ f"-- no-transaction\nDROP INDEX CONCURRENTLY IF EXISTS {self.index};",
+ )
+
+ self._apply()
+
+ assert _persons_fetchall("SELECT to_regclass(%s) IS NULL", [self.index]) == [(True,)]
+ assert self._recorded_migrations() == [f"20990101000001_{self.suffix}_drop_index.sql"]
+
+ def test_refuses_to_continue_when_a_failed_build_left_an_invalid_index(self) -> None:
+ self._write_migration(
+ "20990101000001",
+ "create_table",
+ f"CREATE TABLE {self.table} (id INT); INSERT INTO {self.table} (id) VALUES (1), (1);",
+ )
+ self._write_migration(
+ "20990101000002",
+ "add_unique_index",
+ f"-- no-transaction\nCREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS {self.index} ON {self.table} (id);",
+ )
+
+ with pytest.raises(psycopg.Error):
+ self._apply()
+
+ with pytest.raises(CommandError, match=f"DROP INDEX CONCURRENTLY public.{self.index}") as error:
+ self._apply()
+
+ assert "INVALID" in str(error.value)
+ assert len(self._recorded_migrations()) == 1