: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(devex): drop django's field indexes without a hand-typed name (#111704)
Julian Beze61a43925fa3
diff --git a/.agents/skills/django-migrations/SKILL.md b/.agents/skills/django-migrations/SKILL.mdindex be829019f473..8fe72a1af0ed 100644--- a/.agents/skills/django-migrations/SKILL.md+++ b/.agents/skills/django-migrations/SKILL.md@@ -100,6 +100,7 @@ Two things a callable does not do for you:- **Add a CHECK constraint** → `AddConstraintNotValid` then `ValidateConstraint` in a later migration (or same migration with `atomic = False`).- **Add a ForeignKey to a [hot table](#hot-table-hazard)** → declare the FK with `db_constraint=False` on the model (so `CreateModel` / `AddField` emit no parent lock), then add the DB constraint back with `AddForeignKeyNotValid` and follow up with `ValidateForeignKey` in a later migration. See [foreign keys to hot tables](#foreign-keys-to-hot-tables).- **Index expressed only as raw SQL** (no Django `Index`) → `CreateIndexConcurrently` / `DropIndexConcurrently` wrapped in `SeparateDatabaseAndState`.+- **Drop an index Django creates for a field** (a `ForeignKey` or other `db_index=True` index, or the `_like` companion of a varchar or text field) → `DropFieldIndexesConcurrently(model_name=..., name=...)`, in place of the generated `AlterField` when `db_index` turns off. It derives Django's names, so the risk analyzer's block on hand-typed hash-suffixed names does not apply. On a foreign key it refuses to leave a key that a parent delete still reads without a btree index that leads with its column.- **Retire a column** → `deprecate_field` on the model, or `untrack_field` in place of the generated `RemoveField`. See [retire a column](#retire-a-column).- **Drop a retired table** → `SafeDropTable("posthog_oldfeature")`. It locks the referenced parents up front under a budget below `deadlock_timeout`, so a lock cycle tends to end with the migration retried rather than a live read killed, and it is idempotent under a retry. It refuses a partitioned or inherited table, because its lock list does not cover the members of a hierarchy.- **Drop the check and unique rules on a retiring column** → `DropColumnConstraints(table, columns=[...])`, before the release that stops writing the column. It finds every check, unique and exclusion constraint and every unique index on those columns in the catalog, including ones an earlier swap left behind that no migration names, and drops them under one bounded lock. Never type a Django-generated name into `DROP CONSTRAINT IF EXISTS`: a wrong name succeeds and drops nothing. The risk analyzer blocks a forward drop of a name with Django's hash suffix.diff --git a/docs/published/handbook/engineering/safe-django-migrations.md b/docs/published/handbook/engineering/safe-django-migrations.mdindex 20afc2929027..b7ac2b574aff 100644--- a/docs/published/handbook/engineering/safe-django-migrations.md+++ b/docs/published/handbook/engineering/safe-django-migrations.md@@ -550,6 +550,14 @@ class Migration(migrations.Migration):Dropping an index uses the mirror helper, `SafeRemoveIndexConcurrently`(`model_name` + index `name`).+Django also creates indexes outside `Meta.indexes`, so `SafeRemoveIndexConcurrently` cannot find them: the index of a field with `db_index=True`, including every `ForeignKey` by default, and the `_like` pattern-ops companion of a varchar or text field with `db_index=True` or `unique=True`.+Drop them with `DropFieldIndexesConcurrently(model_name="mymodel", name="team")`, which derives the names the way Django does, so no hash-suffixed name is typed by hand.++- For a field with `db_index=True`, set `db_index=False` on the model and use the op in place of the `AlterField` that `makemigrations` writes. It drops both indexes.+- For a field with `unique=True`, it drops only the `_like` companion. Model state cannot record that, so a fresh database still creates the companion.++It refuses when the table holds another index on only that column that no `Meta` index or constraint names. It also refuses when no other btree index leads with the column while a parent delete still reads it, including through a foreign key that only the database holds, such as one added with `AddForeignKeyNotValid`. A partial index counts only when its sole condition is `<column> IS NOT NULL`, because a key lookup never matches a null.+### Raw-SQL variant: `CreateIndexConcurrently` / `DropIndexConcurrently`When the index doesn't map cleanly to a Django `Index` (e.g. an expression@@ -614,6 +622,7 @@ helper.- **Never use `AddIndexConcurrently` / `RemoveIndexConcurrently` directly** — they are non-idempotent and the CI policy blocks them- **Prefer `SafeAddIndexConcurrently` / `SafeRemoveIndexConcurrently` from `posthog.migration_helpers`** — they take a `model_name` + Index, track Django state themselves (no `SeparateDatabaseAndState`), disable both timeouts, and recover from invalid leftover indexes- Use the raw-SQL `CreateIndexConcurrently` / `DropIndexConcurrently` (wrapped in `SeparateDatabaseAndState`) only when the index doesn't map to a Django `Index`+- Drop the indexes Django creates for a field, such as a `ForeignKey` index or a `_like` companion, with `DropFieldIndexesConcurrently`, never with `DropIndexConcurrently` and a hand-typed name, which the CI policy blocks- Raw `RunSQL` with `SET lock_timeout = 0; SET statement_timeout = 0; CREATE INDEX CONCURRENTLY IF NOT EXISTS ...` is acceptable as a last-resort fallback but does not recover from invalid leftovers- Set `atomic = False` (required for all `CONCURRENTLY` operations)- If a prior deploy already left an invalid index (the helper would catch this on next run, but the fallback won't), clean it up with `REINDEX INDEX CONCURRENTLY` or `DROP INDEX CONCURRENTLY IF EXISTS` before re-runningdiff --git a/posthog/management/migration_analysis/analyzer.py b/posthog/management/migration_analysis/analyzer.pyindex de11c8b7fbff..45194af2e889 100644--- a/posthog/management/migration_analysis/analyzer.py+++ b/posthog/management/migration_analysis/analyzer.py@@ -17,6 +17,7 @@ from posthog.management.migration_analysis.operations import (CreateModelAnalyzer,DeleteModelAnalyzer,DropColumnConstraintsAnalyzer,+ DropFieldIndexesConcurrentlyAnalyzer,DropForeignKeyAnalyzer,DropIndexConcurrentlyAnalyzer,ExtensionAnalyzer,@@ -104,6 +105,7 @@ class RiskAnalyzer:# PostHog migration helpers (posthog/migration_helpers/concurrent_index.py)"CreateIndexConcurrently": CreateIndexConcurrentlyAnalyzer(),"DropIndexConcurrently": DropIndexConcurrentlyAnalyzer(),+ "DropFieldIndexesConcurrently": DropFieldIndexesConcurrentlyAnalyzer(),"SafeAddIndexConcurrently": SafeAddIndexConcurrentlyAnalyzer(),"SafeRemoveIndexConcurrently": SafeRemoveIndexConcurrentlyAnalyzer(),"AddConstraintNotValid": AddConstraintNotValidAnalyzer(),diff --git a/posthog/management/migration_analysis/operations.py b/posthog/management/migration_analysis/operations.pyindex d1a922c285e2..1190ce34591a 100644--- a/posthog/management/migration_analysis/operations.py+++ b/posthog/management/migration_analysis/operations.py@@ -943,8 +943,9 @@ Use RunSQL wrapped in SeparateDatabaseAndState:class _SafeConcurrentIndexAnalyzer(OperationAnalyzer):"""Base for the PostHog concurrent-index helpers.- All four (the raw-SQL CreateIndexConcurrently / DropIndexConcurrently and- the state-aware SafeAddIndexConcurrently / SafeRemoveIndexConcurrently)+ All of them (the raw-SQL CreateIndexConcurrently / DropIndexConcurrently and+ the state-aware SafeAddIndexConcurrently / SafeRemoveIndexConcurrently /+ DropFieldIndexesConcurrently)encode the guarantees ConcurrentIndexIdempotencyPolicy enforces - timeoutdisabling, invalid-leftover recovery, and skip-if-already-applied - so theyare safe by construction. Scoring them SAFE (vs the default "unknown@@ -977,6 +978,19 @@ class DropIndexConcurrentlyAnalyzer(_SafeConcurrentIndexAnalyzer):operation_type = "DropIndexConcurrently"+class DropFieldIndexesConcurrentlyAnalyzer(_SafeConcurrentIndexAnalyzer):+ operation_type = "DropFieldIndexesConcurrently"++ def analyze(self, op) -> OperationRisk:+ # The op takes a field, and derives the index names from it only when the migration applies.+ return OperationRisk(+ type=self.operation_type,+ score=self.default_score,+ reason=self.safe_reason,+ details={"model": op.model_name, "field": op.name},+ )++class SafeAddIndexConcurrentlyAnalyzer(_SafeConcurrentIndexAnalyzer):operation_type = "SafeAddIndexConcurrently"diff --git a/posthog/management/migration_analysis/policies.py b/posthog/management/migration_analysis/policies.pyindex ef7ebbf8fd48..534df5e1b835 100644--- a/posthog/management/migration_analysis/policies.py+++ b/posthog/management/migration_analysis/policies.py@@ -203,6 +203,7 @@ class AtomicFalsePolicy(MigrationPolicy):"RemoveIndexConcurrently",# PostHog helpers (see posthog/migration_helpers/concurrent_index.py)"CreateIndexConcurrently",+ "DropFieldIndexesConcurrently","DropIndexConcurrently","SafeAddIndexConcurrently","SafeRemoveIndexConcurrently",@@ -386,6 +387,7 @@ class ConcurrentIndexIdempotencyPolicy(MigrationPolicy):# level, so they are explicitly exempt from the static SQL check.POSTHOG_SAFE_HELPER_OPS = {"CreateIndexConcurrently",+ "DropFieldIndexesConcurrently","DropIndexConcurrently","SafeAddIndexConcurrently","SafeRemoveIndexConcurrently",@@ -1073,17 +1075,21 @@ class GeneratedNameDropPolicy(MigrationPolicy):)def check_operation(self, op) -> list[str]:- if op.__class__.__name__ != "RunSQL":+ # Every op that carries SQL, so the RunSQL subclasses in posthog/migration_helpers count too.+ sql = getattr(op, "sql", None)+ if not sql:return []- sql = _without_sql_comments(str(getattr(op, "sql", "")))- names = sorted({name for name in self._DROP.findall(sql) if self._GENERATED.search(name)})+ names = sorted(+ {name for name in self._DROP.findall(_without_sql_comments(str(sql))) if self._GENERATED.search(name)}+ )if not names:return []return [- f"❌ BLOCKED: RunSQL drops {', '.join(names)} by a name Django generated. A long-lived database "+ f"❌ BLOCKED: {op.__class__.__name__} drops {', '.join(names)} by a name Django generated. A long-lived database ""can hold the rule under another name, or hold rules no migration names any more, and IF EXISTS ""hides the miss. Find it in the catalog: DropColumnConstraints(table, columns=[...]) for the check "- "and unique rules on a retiring column, DropForeignKey for a foreign key, or Django's own "+ "and unique rules on a retiring column, DropForeignKey for a foreign key, "+ "DropFieldIndexesConcurrently for the index or `_like` companion Django creates for a field, or Django's own ""AlterUniqueTogether and RemoveIndex, which resolve the name from state or by column."]diff --git a/posthog/management/migration_analysis/test/test_risk_analyzer.py b/posthog/management/migration_analysis/test/test_risk_analyzer.pyindex 88099e49a692..ad641e20d731 100644--- a/posthog/management/migration_analysis/test/test_risk_analyzer.py+++ b/posthog/management/migration_analysis/test/test_risk_analyzer.py@@ -22,7 +22,9 @@ from posthog.migration_helpers import (AddConstraintNotValid,AddForeignKeyNotValid,DropColumnConstraints,+ DropFieldIndexesConcurrently,DropForeignKey,+ DropIndexConcurrently,SafeAddIndexConcurrently,SafeDropTable,SafeRemoveIndexConcurrently,@@ -2199,6 +2201,7 @@ class TestAtomicFalsePolicy:@parameterized.expand(["CreateIndexConcurrently",+ "DropFieldIndexesConcurrently","DropIndexConcurrently","SafeAddIndexConcurrently","SafeRemoveIndexConcurrently",@@ -2440,6 +2443,7 @@ class TestConcurrentIndexIdempotencyPolicy:[(SafeAddIndexConcurrently(model_name="dashboard", index=models.Index(fields=["name"], name="idx")),),(SafeRemoveIndexConcurrently(model_name="dashboard", name="idx"),),+ (DropFieldIndexesConcurrently(model_name="dashboard", name="team"),),])def test_safe_state_aware_helpers_score_safe(self, op):@@ -3140,3 +3144,17 @@ class TestGeneratedNameDropPolicy:assert len(violations) == (1 if expected else 0)for name in expected:assert name in violations[0]++ def test_a_generated_name_is_not_typed_into_a_concurrent_index_drop(self):+ drop = DropIndexConcurrently(+ index_name="posthog_x_owner_id_5a6b7c8d", table_name="posthog_x", columns="(owner_id)"+ )+ migration = MagicMock()+ migration.app_label = "posthog"+ migration.name = "0001_test"+ migration.operations = [migrations.SeparateDatabaseAndState(database_operations=[drop])]++ violations = GeneratedNameDropPolicy().check_migration(migration)++ assert len(violations) == 1+ assert "DropIndexConcurrently drops posthog_x_owner_id_5a6b7c8d" in violations[0]diff --git a/posthog/migration_helpers/__init__.py b/posthog/migration_helpers/__init__.pyindex 9af67b730e4f..267454bb76d6 100644--- a/posthog/migration_helpers/__init__.py+++ b/posthog/migration_helpers/__init__.py@@ -1,5 +1,6 @@from posthog.migration_helpers.concurrent_index import (CreateIndexConcurrently,+ DropFieldIndexesConcurrently,DropIndexConcurrently,SafeAddIndexConcurrently,SafeRemoveIndexConcurrently,@@ -18,6 +19,7 @@ __all__ = ["CreateIndexConcurrently","DropColumnConstraints","DropForeignKey",+ "DropFieldIndexesConcurrently","DropIndexConcurrently","SafeAddIndexConcurrently","SafeDropTable",diff --git a/posthog/migration_helpers/concurrent_index.py b/posthog/migration_helpers/concurrent_index.pyindex 538dfaaeb52a..5d1f347691cc 100644--- a/posthog/migration_helpers/concurrent_index.py+++ b/posthog/migration_helpers/concurrent_index.py@@ -53,15 +53,22 @@ can't model):)],)+`DropFieldIndexesConcurrently` drops the indexes Django creates for a field outside+`Meta.indexes`: the `db_index` index and the `_like` pattern-ops companion.+The Migration class still needs `atomic = False`."""-from django.contrib.postgres.operations import AddIndexConcurrently, RemoveIndexConcurrently+from django.contrib.postgres.operations import AddIndexConcurrently, NotInTransactionMixin, RemoveIndexConcurrentlyfrom django.db import migrations, routerfrom django.db.backends.base.schema import BaseDatabaseSchemaEditor+from django.db.migrations.operations.fields import FieldOperation+from django.db.models import DO_NOTHING, Indeximport structlog+from posthog.dataclasses import frozen+logger = structlog.get_logger(__name__)@@ -400,3 +407,165 @@ class SafeRemoveIndexConcurrently(RemoveIndexConcurrently):to_model_state = to_state.models[app_label, self.model_name_lower]index = to_model_state.get_index_by_name(self.name)schema_editor.add_index(model, index, concurrently=True)+++_LEADING_INDEXES_SQL = """+ SELECT index_class.relname+ FROM pg_index idx+ JOIN pg_class table_class ON table_class.oid = idx.indrelid+ JOIN pg_class index_class ON index_class.oid = idx.indexrelid+ JOIN pg_am am ON am.oid = index_class.relam+ JOIN pg_attribute att ON att.attrelid = idx.indrelid AND att.attnum = idx.indkey[0]+ WHERE table_class.relname = %(table)s+ AND pg_table_is_visible(table_class.oid)+ AND att.attname = %(column)s+ AND am.amname = 'btree'+ AND idx.indisvalid+ -- A key lookup is an equality, which implies IS NOT NULL, so Postgres uses such a partial index for it.+ AND (+ idx.indpred IS NULL+ OR pg_get_expr(idx.indpred, idx.indrelid) = '(' || quote_ident(att.attname) || ' IS NOT NULL)'+ )+"""+++@frozen+class _AutomaticIndex:+ name: str+ columns: str+++class DropFieldIndexesConcurrently(NotInTransactionMixin, FieldOperation):+ """Drop the indexes Django creates for a field outside `Meta.indexes`, without a typed name.++ Django gives a field with `db_index=True` an index of its own, and on Postgres it adds a+ `_like` pattern-ops companion to a varchar or text field with `db_index=True` or+ `unique=True`. Neither is in `Meta.indexes`, so `SafeRemoveIndexConcurrently` cannot+ resolve them. The op derives the names the same way Django did when it created the+ indexes, so no hash-suffixed name is typed at the call site. The Migration class still+ needs `atomic = False`.++ operations = [+ DropFieldIndexesConcurrently(model_name="mymodel", name="team"),+ ]++ - On a field with `db_index=True` and no unique rule, use it in place of the `AlterField`+ that `makemigrations` writes, which runs a plain `DROP INDEX` under ACCESS EXCLUSIVE. It+ drops both indexes and sets `db_index=False` in state.+ - On a field with `unique=True`, it drops only the `_like` companion. The unique rule keeps+ its index, and state does not change, so a fresh database still gets the companion.++ The op raises instead of guessing when another single-column index on the column exists+ that no Meta index or constraint names. It also raises when a parent delete still reads+ the column and no other btree index leads with it. That holds while the database keeps a+ foreign key constraint on the column, which Postgres checks at COMMIT, and on a Django+ relation with any `on_delete` but `DO_NOTHING`. Both would then scan the whole table.+ """++ def state_forwards(self, app_label, state) -> None:+ field = state.models[app_label, self.model_name_lower].fields[self.name]+ if not (field.db_index or field.unique):+ raise ValueError(+ f"{type(self).__name__} needs a field with an index of its own, "+ f"and {self.model_name}.{self.name} has none"+ )+ if field.db_index and not field.unique:+ field = field.clone()+ field.db_index = False+ state.alter_field(app_label, self.model_name_lower, self.name, field, preserve_default=True)++ def _automatic_indexes(self, schema_editor, model, field) -> list[_AutomaticIndex]:+ # The names and columns BaseDatabaseSchemaEditor._field_indexes_sql uses when it creates them.+ table = model._meta.db_table+ indexes = []+ if field.db_index and not field.unique:+ indexes.append(+ _AutomaticIndex(+ name=schema_editor._create_index_name(table, [field.column]),+ columns=f"({schema_editor.quote_name(field.column)})",+ )+ )+ like = schema_editor._create_like_index_sql(model, field)+ if like is not None:+ indexes.append(+ _AutomaticIndex(+ name=schema_editor._create_index_name(table, [field.column], suffix="_like"),+ columns=f"({like.parts['columns']})",+ )+ )+ return indexes++ def database_forwards(self, app_label, schema_editor, from_state, to_state) -> None:+ self._ensure_not_in_transaction(schema_editor)+ model = from_state.apps.get_model(app_label, self.model_name)+ if not self.allow_migrate_model(schema_editor.connection.alias, model):+ return+ table = model._meta.db_table+ field = model._meta.get_field(self.name)+ automatic = {index.name for index in self._automatic_indexes(schema_editor, model, field)}+ if not automatic:+ raise ValueError(+ f"Django creates no index outside the unique rule for {self.model_name}.{self.name}, "+ "so there is nothing to drop."+ )+ # The lookup Django's own AlterField runs to find these indexes when db_index turns off.+ candidates = set(+ schema_editor._constraint_names(+ model,+ [field.column],+ index=True,+ type_=Index.suffix,+ # A conditional UniqueConstraint is a partial unique index, not a pg_constraint row.+ exclude={rule.name for rule in [*model._meta.indexes, *model._meta.constraints]},+ )+ )+ unexpected = sorted(candidates - automatic)+ if unexpected:+ raise ValueError(+ f"{table} holds {', '.join(unexpected)} on only {field.column}. Django did not create it for the "+ f"field ({', '.join(sorted(automatic))}), and no Meta index or constraint names it. "+ "Find out what created it first."+ )+ # Read the key from the database, not from state: AddForeignKeyNotValid adds one under+ # db_constraint=False. Also checked when the indexes are already gone.+ database_key = bool(schema_editor._constraint_names(model, [field.column], foreign_key=True))+ if database_key or (field.is_relation and field.remote_field.on_delete is not DO_NOTHING):+ with schema_editor.connection.cursor() as cursor:+ cursor.execute(_LEADING_INDEXES_SQL, {"table": table, "column": field.column})+ covering = {name for (name,) in cursor.fetchall()} - automatic+ if not covering:+ raise ValueError(+ f"No other btree index on {table} leads with {field.column}. Without one, a delete of the "+ f"parent row scans {table} for child rows. Add a btree index that leads with {field.column} first."+ )+ _disable_timeouts(schema_editor)+ for name in sorted(candidates & automatic):+ schema_editor.execute(_build_drop_sql(name))++ def database_backwards(self, app_label, schema_editor, from_state, to_state) -> None:+ self._ensure_not_in_transaction(schema_editor)+ model = to_state.apps.get_model(app_label, self.model_name)+ if not self.allow_migrate_model(schema_editor.connection.alias, model):+ return+ field = model._meta.get_field(self.name)+ _disable_timeouts(schema_editor)+ for index in self._automatic_indexes(schema_editor, model, field):+ if _index_validity(schema_editor, index.name) == "invalid":+ _log_and_drop_invalid_index(schema_editor, index.name, type(self).__name__)+ schema_editor.execute(+ _build_create_sql(+ index_name=index.name,+ table_name=model._meta.db_table,+ columns=index.columns,+ unique=False,+ using="",+ where="",+ )+ )++ def describe(self) -> str:+ return f"Concurrently drop the indexes Django creates for {self.model_name}.{self.name}"++ @property+ def migration_name_fragment(self) -> str:+ return f"drop_{self.model_name_lower}_{self.name_lower}_indexes"diff --git a/posthog/migration_helpers/test_concurrent_index.py b/posthog/migration_helpers/test_concurrent_index.pyindex d01e232352c1..4f8f21d64bc8 100644--- a/posthog/migration_helpers/test_concurrent_index.py+++ b/posthog/migration_helpers/test_concurrent_index.py@@ -16,6 +16,7 @@ from django.db.migrations.state import ModelState, ProjectStatefrom posthog.migration_helpers import (CreateIndexConcurrently,+ DropFieldIndexesConcurrently,DropIndexConcurrently,SafeAddIndexConcurrently,SafeRemoveIndexConcurrently,@@ -456,3 +457,213 @@ def test_safe_ops_deconstruct_round_trips(op):assert args == []rebuilt = type(op)(**kwargs)assert rebuilt.deconstruct() == op.deconstruct()+++# --- DropFieldIndexesConcurrently ---+++def key_tables():+ """Table names for a parent and a child with a foreign key, dropped on teardown."""+ suffix = uuid.uuid4().hex[:8]+ parent, child = f"test_fkp_{suffix}", f"test_fkc_{suffix}"+ try:+ yield parent, child+ finally:+ with connection.cursor() as cursor:+ cursor.execute(f'DROP TABLE IF EXISTS "{child}", "{parent}"')+++def _create_key_tables(+ parent: str,+ child: str,+ *,+ on_delete=models.CASCADE,+ db_constraint: bool = True,+ to_field: str | None = None,+ indexes: list[models.Index] | None = None,+ constraints: list[models.UniqueConstraint] | None = None,+) -> ProjectState:+ state = ProjectState()+ state.add_model(+ ModelState(+ app_label="posthog",+ name="TempFkParent",+ fields=[+ ("id", models.AutoField(primary_key=True)),+ ("code", models.CharField(max_length=20, unique=True)),+ ],+ options={"db_table": parent},+ )+ )+ state.add_model(+ ModelState(+ app_label="posthog",+ name="TempFkChild",+ fields=[+ ("id", models.AutoField(primary_key=True)),+ (+ "owner",+ models.ForeignKey(+ "posthog.tempfkparent", on_delete=on_delete, db_constraint=db_constraint, to_field=to_field+ ),+ ),+ ("seq", models.IntegerField(default=0)),+ ],+ options={"db_table": child, "indexes": indexes or [], "constraints": constraints or []},+ )+ )+ with connection.schema_editor() as schema_editor:+ schema_editor.create_model(state.apps.get_model("posthog", "TempFkParent"))+ schema_editor.create_model(state.apps.get_model("posthog", "TempFkChild"))+ return state+++def _indexes_on_only(table: str, column: str) -> set[str]:+ with connection.cursor() as cursor:+ constraints = connection.introspection.get_constraints(cursor, table)+ return {name for name, info in constraints.items() if info["index"] and info["columns"] == [column]}++[email protected]_db(transaction=True)+ "on_delete,db_constraint,to_field,index_fields,index_condition,conditional_unique",+ [+ pytest.param(+ models.CASCADE, True, None, ["owner", "seq"], None, False, id="another_index_leads_with_the_column"+ ),+ pytest.param(models.CASCADE, True, None, ["owner"], None, False, id="a_meta_index_on_the_same_column"),+ pytest.param(+ models.CASCADE,+ True,+ None,+ ["owner"],+ models.Q(owner__isnull=False),+ False,+ id="a_partial_index_that_skips_only_nulls",+ ),+ pytest.param(models.DO_NOTHING, False, None, None, None, False, id="no_parent_delete_reads_the_column"),+ pytest.param(models.CASCADE, True, "code", ["owner", "seq"], None, False, id="a_key_to_a_text_column"),+ pytest.param(models.CASCADE, True, None, ["owner", "seq"], None, True, id="a_conditional_unique_on_the_column"),+ ],+)+def test_drop_foreign_key_index_drops_only_the_automatic_indexes(+ key_tables, on_delete, db_constraint, to_field, index_fields, index_condition, conditional_unique+):+ parent, child = key_tables+ indexes = (+ [models.Index(fields=index_fields, condition=index_condition, name=f"{child}_meta")] if index_fields else []+ )+ constraints = (+ [models.UniqueConstraint(fields=["owner"], condition=models.Q(seq__gt=0), name=f"{child}_uniq")]+ if conditional_unique+ else []+ )+ state = _create_key_tables(+ parent,+ child,+ on_delete=on_delete,+ db_constraint=db_constraint,+ to_field=to_field,+ indexes=indexes,+ constraints=constraints,+ )+ single_column_meta = {index.name for index in indexes if index.fields == ["owner"]} | {+ constraint.name for constraint in constraints+ }+ automatic = _indexes_on_only(child, "owner_id") - single_column_meta+ op = DropFieldIndexesConcurrently(model_name="TempFkChild", name="owner")++ _apply_forwards(op, state)+ assert _indexes_on_only(child, "owner_id") == single_column_meta++ _apply_forwards(op, state) # a bin/migrate retry finds nothing left to drop+ assert _indexes_on_only(child, "owner_id") == single_column_meta++ after = state.clone()+ op.state_forwards("posthog", after)+ assert after.models["posthog", "tempfkchild"].fields["owner"].db_index is False++ _apply_backwards(op, state)+ assert all(_index_is_valid(name) for name in automatic)+ assert _indexes_on_only(child, "owner_id") == automatic | single_column_meta++[email protected]_db(transaction=True)+def test_drop_field_indexes_drops_only_the_like_companion_of_a_unique_field(key_tables):+ parent, child = key_tables+ state = _create_key_tables(parent, child)+ (like,) = _indexes_on_only(parent, "code")+ op = DropFieldIndexesConcurrently(model_name="TempFkParent", name="code")+ before = state.models["posthog", "tempfkparent"].fields["code"].deconstruct()++ _apply_forwards(op, state)+ assert _indexes_on_only(parent, "code") == set()+ with connection.cursor() as cursor:+ constraints = connection.introspection.get_constraints(cursor, parent)+ assert any(info["unique"] and info["columns"] == ["code"] for info in constraints.values())++ after = state.clone()+ op.state_forwards("posthog", after)+ assert after.models["posthog", "tempfkparent"].fields["code"].deconstruct() == before++ _apply_backwards(op, state)+ assert _indexes_on_only(parent, "code") == {like}+ assert _index_is_valid(like)++[email protected]_db(transaction=True)+ "on_delete,db_constraint,setup_sql,error",+ [+ pytest.param(+ models.CASCADE,+ True,+ 'CREATE INDEX "{child}_stray" ON "{child}" (owner_id)',+ "Find out what created it",+ id="an_unexpected_index_on_the_column",+ ),+ pytest.param(models.CASCADE, True, None, "No other btree index", id="no_other_index_leads_with_the_column"),+ pytest.param(+ models.DO_NOTHING, True, None, "No other btree index", id="only_the_commit_check_reads_the_column"+ ),+ pytest.param(+ models.CASCADE, False, None, "No other btree index", id="only_the_delete_collector_reads_the_column"+ ),+ pytest.param(+ models.CASCADE,+ True,+ 'DROP INDEX "{automatic}"',+ "No other btree index",+ id="the_automatic_index_is_already_gone",+ ),+ pytest.param(+ models.CASCADE,+ True,+ 'CREATE INDEX "{child}_partial" ON "{child}" (owner_id, seq) WHERE owner_id IS NOT NULL AND seq > 0',+ "No other btree index",+ id="a_partial_index_that_skips_more_than_nulls",+ ),+ pytest.param(+ models.DO_NOTHING,+ False,+ 'ALTER TABLE "{child}" ADD CONSTRAINT "{child}_fk" FOREIGN KEY (owner_id) REFERENCES "{parent}" (id) NOT VALID',+ "No other btree index",+ id="a_database_key_that_state_does_not_track",+ ),+ ],+)+def test_drop_foreign_key_index_refuses_and_keeps_the_indexes(key_tables, on_delete, db_constraint, setup_sql, error):+ parent, child = key_tables+ state = _create_key_tables(parent, child, on_delete=on_delete, db_constraint=db_constraint)+ (automatic,) = _indexes_on_only(child, "owner_id")+ if setup_sql:+ with connection.cursor() as cursor:+ cursor.execute(setup_sql.format(parent=parent, child=child, automatic=automatic))+ before = _indexes_on_only(child, "owner_id")+ op = DropFieldIndexesConcurrently(model_name="TempFkChild", name="owner")++ with pytest.raises(ValueError, match=error):+ _apply_forwards(op, state)++ assert _indexes_on_only(child, "owner_id") == before