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.2 KiB

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