Debian Codegraph @

django/db/migrations/operations/special.py

raw
1 from django.db import router
2
3 from .base import Operation, OperationCategory
4
5
6 class SeparateDatabaseAndState(Operation):
7 """
8 Take two lists of operations - ones that will be used for the database,
9 and ones that will be used for the state change. This allows operations
10 that don't support state change to have it applied, or have operations
11 that affect the state or not the database, or so on.
12 """
13
14 category = OperationCategory.MIXED
15 serialization_expand_args = ["database_operations", "state_operations"]
16
17 def __init__(self, database_operations=None, state_operations=None):
18 self.database_operations = database_operations or []
19 self.state_operations = state_operations or []
20
21 def deconstruct(self):
22 kwargs = {}
23 if self.database_operations:
24 kwargs["database_operations"] = self.database_operations
25 if self.state_operations:
26 kwargs["state_operations"] = self.state_operations
27 return (self.__class__.__qualname__, [], kwargs)
28
29 def state_forwards(self, app_label, state):
30 for state_operation in self.state_operations:
31 state_operation.state_forwards(app_label, state)
32
33 def database_forwards(self, app_label, schema_editor, from_state, to_state):
34 # We calculate state separately in here since our state functions aren't useful
35 for database_operation in self.database_operations:
36 to_state = from_state.clone()
37 database_operation.state_forwards(app_label, to_state)
38 database_operation.database_forwards(
39 app_label, schema_editor, from_state, to_state
40 )
41 from_state = to_state
42
43 def database_backwards(self, app_label, schema_editor, from_state, to_state):
44 # We calculate state separately in here since our state functions aren't useful
45 to_states = {}
46 for dbop in self.database_operations:
47 to_states[dbop] = to_state
48 to_state = to_state.clone()
49 dbop.state_forwards(app_label, to_state)
50 # to_state now has the states of all the database_operations applied
51 # which is the from_state for the backwards migration of the last
52 # operation.
53 for database_operation in reversed(self.database_operations):
54 from_state = to_state
55 to_state = to_states[database_operation]
56 database_operation.database_backwards(
57 app_label, schema_editor, from_state, to_state
58 )
59
60 def describe(self):
61 return "Custom state/database change combination"
62
63
64 class RunSQL(Operation):
65 """
66 Run some raw SQL. A reverse SQL statement may be provided.
67
68 Also accept a list of operations that represent the state change effected
69 by this SQL change, in case it's custom column/table creation/deletion.
70 """
71
72 category = OperationCategory.SQL
73 noop = ""
74
75 def __init__(
76 self, sql, reverse_sql=None, state_operations=None, hints=None, elidable=False
77 ):
78 self.sql = sql
79 self.reverse_sql = reverse_sql
80 self.state_operations = state_operations or []
81 self.hints = hints or {}
82 self.elidable = elidable
83
84 def deconstruct(self):
85 kwargs = {
86 "sql": self.sql,
87 }
88 if self.reverse_sql is not None:
89 kwargs["reverse_sql"] = self.reverse_sql
90 if self.state_operations:
91 kwargs["state_operations"] = self.state_operations
92 if self.hints:
93 kwargs["hints"] = self.hints
94 return (self.__class__.__qualname__, [], kwargs)
95
96 @property
97 def reversible(self):
98 return self.reverse_sql is not None
99
100 def state_forwards(self, app_label, state):
101 for state_operation in self.state_operations:
102 state_operation.state_forwards(app_label, state)
103
104 def database_forwards(self, app_label, schema_editor, from_state, to_state):
105 if router.allow_migrate(
106 schema_editor.connection.alias, app_label, **self.hints
107 ):
108 self._run_sql(schema_editor, self.sql)
109
110 def database_backwards(self, app_label, schema_editor, from_state, to_state):
111 if self.reverse_sql is None:
112 raise NotImplementedError("You cannot reverse this operation")
113 if router.allow_migrate(
114 schema_editor.connection.alias, app_label, **self.hints
115 ):
116 self._run_sql(schema_editor, self.reverse_sql)
117
118 def describe(self):
119 return "Raw SQL operation"
120
121 def _run_sql(self, schema_editor, sqls):
122 if isinstance(sqls, (list, tuple)):
123 for sql in sqls:
124 params = None
125 if isinstance(sql, (list, tuple)):
126 elements = len(sql)
127 if elements == 2:
128 sql, params = sql
129 else:
130 raise ValueError("Expected a 2-tuple but got %d" % elements)
131 schema_editor.execute(sql, params=params)
132 elif sqls != RunSQL.noop:
133 statements = schema_editor.connection.ops.prepare_sql_script(sqls)
134 for statement in statements:
135 schema_editor.execute(statement, params=None)
136
137
138 class RunPython(Operation):
139 """
140 Run Python code in a context suitable for doing versioned ORM operations.
141 """
142
143 category = OperationCategory.PYTHON
144 reduces_to_sql = False
145
146 def __init__(
147 self, code, reverse_code=None, atomic=None, hints=None, elidable=False
148 ):
149 self.atomic = atomic
150 # Forwards code
151 if not callable(code):
152 raise ValueError("RunPython must be supplied with a callable")
153 self.code = code
154 # Reverse code
155 if reverse_code is None:
156 self.reverse_code = None
157 else:
158 if not callable(reverse_code):
159 raise ValueError("RunPython must be supplied with callable arguments")
160 self.reverse_code = reverse_code
161 self.hints = hints or {}
162 self.elidable = elidable
163
164 def deconstruct(self):
165 kwargs = {
166 "code": self.code,
167 }
168 if self.reverse_code is not None:
169 kwargs["reverse_code"] = self.reverse_code
170 if self.atomic is not None:
171 kwargs["atomic"] = self.atomic
172 if self.hints:
173 kwargs["hints"] = self.hints
174 return (self.__class__.__qualname__, [], kwargs)
175
176 @property
177 def reversible(self):
178 return self.reverse_code is not None
179
180 def state_forwards(self, app_label, state):
181 # RunPython objects have no state effect. To add some, combine this
182 # with SeparateDatabaseAndState.
183 pass
184
185 def database_forwards(self, app_label, schema_editor, from_state, to_state):
186 # RunPython has access to all models. Ensure that all models are
187 # reloaded in case any are delayed.
188 from_state.clear_delayed_apps_cache()
189 if router.allow_migrate(
190 schema_editor.connection.alias, app_label, **self.hints
191 ):
192 # We now execute the Python code in a context that contains a 'models'
193 # object, representing the versioned models as an app registry.
194 # We could try to override the global cache, but then people will still
195 # use direct imports, so we go with a documentation approach instead.
196 self.code(from_state.apps, schema_editor)
197
198 def database_backwards(self, app_label, schema_editor, from_state, to_state):
199 if self.reverse_code is None:
200 raise NotImplementedError("You cannot reverse this operation")
201 if router.allow_migrate(
202 schema_editor.connection.alias, app_label, **self.hints
203 ):
204 self.reverse_code(from_state.apps, schema_editor)
205
206 def describe(self):
207 return "Raw Python operation"
208
209 @staticmethod
210 def noop(apps, schema_editor):
211 return None