special.py 7.6 KB

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