special.py 7.8 KB

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