| 1 |
""" |
| 2 |
Classes and utilities for handling deletions in polymorphic models. |
| 3 |
""" |
| 4 |
|
| 5 |
from __future__ import annotations |
| 6 |
|
| 7 |
from collections.abc import Callable |
| 8 |
from functools import cached_property |
| 9 |
from typing import Any, cast |
| 10 |
|
| 11 |
from django.db import models |
| 12 |
from django.db.migrations.serializer import BaseSerializer, serializer_factory |
| 13 |
from django.db.migrations.writer import MigrationWriter |
| 14 |
from django.db.models.deletion import Collector |
| 15 |
|
| 16 |
from .query import PolymorphicQuerySet |
| 17 |
|
| 18 |
|
| 19 |
def migration_fingerprint(value: Any) -> Any: |
| 20 |
""" |
| 21 |
Produce a stable, hashable fingerprint for a value as Django would represent |
| 22 |
it in migrations, but in a structured form when possible. |
| 23 |
""" |
| 24 |
# Canonical deconstruction path for SET(...), @deconstructible, etc. |
| 25 |
deconstruct = getattr(value, "deconstruct", None) |
| 26 |
if callable(deconstruct): |
| 27 |
path, args, kwargs = value.deconstruct() |
| 28 |
return ( |
| 29 |
path, |
| 30 |
tuple(migration_fingerprint(a) for a in args), |
| 31 |
tuple(sorted((k, migration_fingerprint(v)) for k, v in kwargs.items())), |
| 32 |
) |
| 33 |
|
| 34 |
# Fallback: canonical "code string" Django would emit in a migration. |
| 35 |
# (Works for CASCADE/PROTECT/SET_NULL, primitives, etc.) |
| 36 |
code, _imports = serializer_factory(value).serialize() |
| 37 |
return code |
| 38 |
|
| 39 |
|
| 40 |
class PolymorphicGuard: |
| 41 |
""" |
| 42 |
Wrap an :attr:`django.db.models.ForeignKey.on_delete` callable |
| 43 |
(CASCADE/PROTECT/SET_NULL/SET(...)/custom), but serialize as the underlying |
| 44 |
callable. |
| 45 |
|
| 46 |
:param action: The :attr:`django.db.models.ForeignKey.on_delete` callable to wrap. |
| 47 |
""" |
| 48 |
|
| 49 |
action: Callable[..., Any] |
| 50 |
|
| 51 |
def __init__(self, action: Callable[..., Any]) -> None: |
| 52 |
if not callable(action): |
| 53 |
raise TypeError("action must be callable") |
| 54 |
self.action = action |
| 55 |
|
| 56 |
def __call__( |
| 57 |
self, |
| 58 |
collector: Collector, |
| 59 |
field: models.Field[Any, Any], |
| 60 |
sub_objs: PolymorphicQuerySet[Any, Any], |
| 61 |
using: str, |
| 62 |
) -> None: |
| 63 |
""" |
| 64 |
This guard wraps an on_delete action to ensure that any polymorphic queryset |
| 65 |
passed to it is converted to a non-polymorphic queryset before proceeding. |
| 66 |
This prevents issues with cascading deletes on polymorphic models. |
| 67 |
|
| 68 |
This guard should be automatically applied to reverse relations such that |
| 69 |
|
| 70 |
.. code-block:: python |
| 71 |
|
| 72 |
class MyModel(PolymorphicModel): |
| 73 |
related = models.ForeignKey( |
| 74 |
OtherModel, |
| 75 |
on_delete=models.CASCADE # <- equal to PolymorphicGuard(models.CASCADE) |
| 76 |
) |
| 77 |
|
| 78 |
""" |
| 79 |
if isinstance(sub_objs, PolymorphicQuerySet) and not sub_objs.polymorphic_disabled: |
| 80 |
sub_objs = sub_objs.non_polymorphic() |
| 81 |
self.action(collector, field, sub_objs, using) |
| 82 |
|
| 83 |
@cached_property |
| 84 |
def migration_key(self) -> Any: |
| 85 |
return migration_fingerprint(self.action) |
| 86 |
|
| 87 |
def __eq__(self, other: object) -> bool: |
| 88 |
if ( |
| 89 |
isinstance(other, tuple) |
| 90 |
and len(other) == 3 |
| 91 |
and callable(getattr(self.action, "deconstruct", None)) |
| 92 |
): |
| 93 |
# In some cases the autodetector compares us to a reconstructed, |
| 94 |
# deconstruct() tuple. This has been seen for SET(...) callables. |
| 95 |
# The arguments element may be a list instead of a tuple though, this |
| 96 |
# handles that special case |
| 97 |
result = self.action.deconstruct() == ( # type: ignore[attr-defined] |
| 98 |
other[0], |
| 99 |
tuple(other[1]) if isinstance(other[1], list) else other[1], |
| 100 |
other[2], |
| 101 |
) |
| 102 |
# cast(bool) needed because deconstruct() returns Any |
| 103 |
return cast(bool, result) |
| 104 |
if isinstance(other, PolymorphicGuard): |
| 105 |
result = self.migration_key == other.migration_key |
| 106 |
else: |
| 107 |
try: |
| 108 |
result = self.migration_key == migration_fingerprint(other) |
| 109 |
except Exception: |
| 110 |
return False |
| 111 |
# cast(bool) needed because migration_key and migration_fingerprint return Any |
| 112 |
return cast(bool, result) |
| 113 |
|
| 114 |
def __hash__(self) -> int: |
| 115 |
return hash(self.migration_key) |
| 116 |
|
| 117 |
|
| 118 |
class PolymorphicGuardSerializer(BaseSerializer): |
| 119 |
""" |
| 120 |
A serializer for PolymorphicGuard that serializes the underlying action. |
| 121 |
|
| 122 |
There is no need to serialize the PolymorphicGuard itself, as it is just a wrapper |
| 123 |
that ensures that polymorphic querysets are converted to non-polymorphic but no |
| 124 |
polymorphic managers are present in migrations. This also ensures that new |
| 125 |
migrations will not be generated. |
| 126 |
""" |
| 127 |
|
| 128 |
def serialize(self) -> tuple[str, set[str]]: |
| 129 |
""" |
| 130 |
Serialize the underlying action of the PolymorphicGuard. |
| 131 |
""" |
| 132 |
return serializer_factory(self.value.action).serialize() |
| 133 |
|
| 134 |
|
| 135 |
MigrationWriter.register_serializer(PolymorphicGuard, PolymorphicGuardSerializer) |