You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

special.py 7.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  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 (
  21. self.__class__.__qualname__,
  22. [],
  23. kwargs
  24. )
  25. def state_forwards(self, app_label, state):
  26. for state_operation in self.state_operations:
  27. state_operation.state_forwards(app_label, state)
  28. def database_forwards(self, app_label, schema_editor, from_state, to_state):
  29. # We calculate state separately in here since our state functions aren't useful
  30. for database_operation in self.database_operations:
  31. to_state = from_state.clone()
  32. database_operation.state_forwards(app_label, to_state)
  33. database_operation.database_forwards(app_label, schema_editor, from_state, to_state)
  34. from_state = to_state
  35. def database_backwards(self, app_label, schema_editor, from_state, to_state):
  36. # We calculate state separately in here since our state functions aren't useful
  37. to_states = {}
  38. for dbop in self.database_operations:
  39. to_states[dbop] = to_state
  40. to_state = to_state.clone()
  41. dbop.state_forwards(app_label, to_state)
  42. # to_state now has the states of all the database_operations applied
  43. # which is the from_state for the backwards migration of the last
  44. # operation.
  45. for database_operation in reversed(self.database_operations):
  46. from_state = to_state
  47. to_state = to_states[database_operation]
  48. database_operation.database_backwards(app_label, schema_editor, from_state, to_state)
  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__(self, sql, reverse_sql=None, state_operations=None, hints=None, elidable=False):
  59. self.sql = sql
  60. self.reverse_sql = reverse_sql
  61. self.state_operations = state_operations or []
  62. self.hints = hints or {}
  63. self.elidable = elidable
  64. def deconstruct(self):
  65. kwargs = {
  66. 'sql': self.sql,
  67. }
  68. if self.reverse_sql is not None:
  69. kwargs['reverse_sql'] = self.reverse_sql
  70. if self.state_operations:
  71. kwargs['state_operations'] = self.state_operations
  72. if self.hints:
  73. kwargs['hints'] = self.hints
  74. return (
  75. self.__class__.__qualname__,
  76. [],
  77. kwargs
  78. )
  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(schema_editor.connection.alias, app_label, **self.hints):
  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(schema_editor.connection.alias, app_label, **self.hints):
  92. self._run_sql(schema_editor, self.reverse_sql)
  93. def describe(self):
  94. return "Raw SQL operation"
  95. def _run_sql(self, schema_editor, sqls):
  96. if isinstance(sqls, (list, tuple)):
  97. for sql in sqls:
  98. params = None
  99. if isinstance(sql, (list, tuple)):
  100. elements = len(sql)
  101. if elements == 2:
  102. sql, params = sql
  103. else:
  104. raise ValueError("Expected a 2-tuple but got %d" % elements)
  105. schema_editor.execute(sql, params=params)
  106. elif sqls != RunSQL.noop:
  107. statements = schema_editor.connection.ops.prepare_sql_script(sqls)
  108. for statement in statements:
  109. schema_editor.execute(statement, params=None)
  110. class RunPython(Operation):
  111. """
  112. Run Python code in a context suitable for doing versioned ORM operations.
  113. """
  114. reduces_to_sql = False
  115. def __init__(self, code, reverse_code=None, atomic=None, hints=None, elidable=False):
  116. self.atomic = atomic
  117. # Forwards code
  118. if not callable(code):
  119. raise ValueError("RunPython must be supplied with a callable")
  120. self.code = code
  121. # Reverse code
  122. if reverse_code is None:
  123. self.reverse_code = None
  124. else:
  125. if not callable(reverse_code):
  126. raise ValueError("RunPython must be supplied with callable arguments")
  127. self.reverse_code = reverse_code
  128. self.hints = hints or {}
  129. self.elidable = elidable
  130. def deconstruct(self):
  131. kwargs = {
  132. 'code': self.code,
  133. }
  134. if self.reverse_code is not None:
  135. kwargs['reverse_code'] = self.reverse_code
  136. if self.atomic is not None:
  137. kwargs['atomic'] = self.atomic
  138. if self.hints:
  139. kwargs['hints'] = self.hints
  140. return (
  141. self.__class__.__qualname__,
  142. [],
  143. kwargs
  144. )
  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(schema_editor.connection.alias, app_label, **self.hints):
  157. # We now execute the Python code in a context that contains a 'models'
  158. # object, representing the versioned models as an app registry.
  159. # We could try to override the global cache, but then people will still
  160. # use direct imports, so we go with a documentation approach instead.
  161. self.code(from_state.apps, schema_editor)
  162. def database_backwards(self, app_label, schema_editor, from_state, to_state):
  163. if self.reverse_code is None:
  164. raise NotImplementedError("You cannot reverse this operation")
  165. if router.allow_migrate(schema_editor.connection.alias, app_label, **self.hints):
  166. self.reverse_code(from_state.apps, schema_editor)
  167. def describe(self):
  168. return "Raw Python operation"
  169. @staticmethod
  170. def noop(apps, schema_editor):
  171. return None