Debian Codegraph @

django/db/migrations/operations/base.py

raw
1 import enum
2
3 from django.db import router
4
5
6 class OperationCategory(str, enum.Enum):
7 ADDITION = "+"
8 REMOVAL = "-"
9 ALTERATION = "~"
10 PYTHON = "p"
11 SQL = "s"
12 MIXED = "?"
13
14
15 class Operation:
16 """
17 Base class for migration operations.
18
19 It's responsible for both mutating the in-memory model state
20 (see db/migrations/state.py) to represent what it performs, as well
21 as actually performing it against a live database.
22
23 Note that some operations won't modify memory state at all (e.g. data
24 copying operations), and some will need their modifications to be
25 optionally specified by the user (e.g. custom Python code snippets)
26
27 Due to the way this class deals with deconstruction, it should be
28 considered immutable.
29 """
30
31 # If this migration can be run in reverse.
32 # Some operations are impossible to reverse, like deleting data.
33 reversible = True
34
35 # Can this migration be represented as SQL? (things like RunPython cannot)
36 reduces_to_sql = True
37
38 # Should this operation be forced as atomic even on backends with no
39 # DDL transaction support (i.e., does it have no DDL, like RunPython)
40 atomic = False
41
42 # Should this operation be considered safe to elide and optimize across?
43 elidable = False
44
45 serialization_expand_args = []
46
47 category = None
48
49 def __new__(cls, *args, **kwargs):
50 # We capture the arguments to make returning them trivial
51 self = object.__new__(cls)
52 self._constructor_args = (args, kwargs)
53 return self
54
55 def deconstruct(self):
56 """
57 Return a 3-tuple of class import path (or just name if it lives
58 under django.db.migrations), positional arguments, and keyword
59 arguments.
60 """
61 return (
62 self.__class__.__name__,
63 self._constructor_args[0],
64 self._constructor_args[1],
65 )
66
67 def state_forwards(self, app_label, state):
68 """
69 Take the state from the previous migration, and mutate it
70 so that it matches what this migration would perform.
71 """
72 raise NotImplementedError(
73 "subclasses of Operation must provide a state_forwards() method"
74 )
75
76 def database_forwards(self, app_label, schema_editor, from_state, to_state):
77 """
78 Perform the mutation on the database schema in the normal
79 (forwards) direction.
80 """
81 raise NotImplementedError(
82 "subclasses of Operation must provide a database_forwards() method"
83 )
84
85 def database_backwards(self, app_label, schema_editor, from_state, to_state):
86 """
87 Perform the mutation on the database schema in the reverse
88 direction - e.g. if this were CreateModel, it would in fact
89 drop the model's table.
90 """
91 raise NotImplementedError(
92 "subclasses of Operation must provide a database_backwards() method"
93 )
94
95 def describe(self):
96 """
97 Output a brief summary of what the action does.
98 """
99 return "%s: %s" % (self.__class__.__name__, self._constructor_args)
100
101 def formatted_description(self):
102 """Output a description prefixed by a category symbol."""
103 description = self.describe()
104 if self.category is None:
105 return f"{OperationCategory.MIXED.value} {description}"
106 return f"{self.category.value} {description}"
107
108 @property
109 def migration_name_fragment(self):
110 """
111 A filename part suitable for automatically naming a migration
112 containing this operation, or None if not applicable.
113 """
114 return None
115
116 def references_model(self, name, app_label):
117 """
118 Return True if there is a chance this operation references the given
119 model name (as a string), with an app label for accuracy.
120
121 Used for optimization. If in doubt, return True;
122 returning a false positive will merely make the optimizer a little
123 less efficient, while returning a false negative may result in an
124 unusable optimized migration.
125 """
126 return True
127
128 def references_field(self, model_name, name, app_label):
129 """
130 Return True if there is a chance this operation references the given
131 field name, with an app label for accuracy.
132
133 Used for optimization. If in doubt, return True.
134 """
135 return self.references_model(model_name, app_label)
136
137 def allow_migrate_model(self, connection_alias, model):
138 """
139 Return whether or not a model may be migrated.
140
141 This is a thin wrapper around router.allow_migrate_model() that
142 preemptively rejects any proxy, swapped out, or unmanaged model.
143 """
144 if not model._meta.can_migrate(connection_alias):
145 return False
146
147 return router.allow_migrate_model(connection_alias, model)
148
149 def reduce(self, operation, app_label):
150 """
151 Return either a list of operations the actual operation should be
152 replaced with or a boolean that indicates whether or not the specified
153 operation can be optimized across.
154 """
155 if self.elidable:
156 return [operation]
157 elif operation.elidable:
158 return [self]
159 return False
160
161 def __repr__(self):
162 return "<%s %s%s>" % (
163 self.__class__.__name__,
164 ", ".join(map(repr, self._constructor_args[0])),
165 ",".join(" %s=%r" % x for x in self._constructor_args[1].items()),
166 )