Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
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.

operations.py 12KB

1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. from django.contrib.postgres.signals import (
  2. get_citext_oids,
  3. get_hstore_oids,
  4. register_type_handlers,
  5. )
  6. from django.db import NotSupportedError, router
  7. from django.db.migrations import AddConstraint, AddIndex, RemoveIndex
  8. from django.db.migrations.operations.base import Operation
  9. from django.db.models.constraints import CheckConstraint
  10. class CreateExtension(Operation):
  11. reversible = True
  12. def __init__(self, name):
  13. self.name = name
  14. def state_forwards(self, app_label, state):
  15. pass
  16. def database_forwards(self, app_label, schema_editor, from_state, to_state):
  17. if schema_editor.connection.vendor != "postgresql" or not router.allow_migrate(
  18. schema_editor.connection.alias, app_label
  19. ):
  20. return
  21. if not self.extension_exists(schema_editor, self.name):
  22. schema_editor.execute(
  23. "CREATE EXTENSION IF NOT EXISTS %s"
  24. % schema_editor.quote_name(self.name)
  25. )
  26. # Clear cached, stale oids.
  27. get_hstore_oids.cache_clear()
  28. get_citext_oids.cache_clear()
  29. # Registering new type handlers cannot be done before the extension is
  30. # installed, otherwise a subsequent data migration would use the same
  31. # connection.
  32. register_type_handlers(schema_editor.connection)
  33. def database_backwards(self, app_label, schema_editor, from_state, to_state):
  34. if not router.allow_migrate(schema_editor.connection.alias, app_label):
  35. return
  36. if self.extension_exists(schema_editor, self.name):
  37. schema_editor.execute(
  38. "DROP EXTENSION IF EXISTS %s" % schema_editor.quote_name(self.name)
  39. )
  40. # Clear cached, stale oids.
  41. get_hstore_oids.cache_clear()
  42. get_citext_oids.cache_clear()
  43. def extension_exists(self, schema_editor, extension):
  44. with schema_editor.connection.cursor() as cursor:
  45. cursor.execute(
  46. "SELECT 1 FROM pg_extension WHERE extname = %s",
  47. [extension],
  48. )
  49. return bool(cursor.fetchone())
  50. def describe(self):
  51. return "Creates extension %s" % self.name
  52. @property
  53. def migration_name_fragment(self):
  54. return "create_extension_%s" % self.name
  55. class BloomExtension(CreateExtension):
  56. def __init__(self):
  57. self.name = "bloom"
  58. class BtreeGinExtension(CreateExtension):
  59. def __init__(self):
  60. self.name = "btree_gin"
  61. class BtreeGistExtension(CreateExtension):
  62. def __init__(self):
  63. self.name = "btree_gist"
  64. class CITextExtension(CreateExtension):
  65. def __init__(self):
  66. self.name = "citext"
  67. class CryptoExtension(CreateExtension):
  68. def __init__(self):
  69. self.name = "pgcrypto"
  70. class HStoreExtension(CreateExtension):
  71. def __init__(self):
  72. self.name = "hstore"
  73. class TrigramExtension(CreateExtension):
  74. def __init__(self):
  75. self.name = "pg_trgm"
  76. class UnaccentExtension(CreateExtension):
  77. def __init__(self):
  78. self.name = "unaccent"
  79. class NotInTransactionMixin:
  80. def _ensure_not_in_transaction(self, schema_editor):
  81. if schema_editor.connection.in_atomic_block:
  82. raise NotSupportedError(
  83. "The %s operation cannot be executed inside a transaction "
  84. "(set atomic = False on the migration)." % self.__class__.__name__
  85. )
  86. class AddIndexConcurrently(NotInTransactionMixin, AddIndex):
  87. """Create an index using PostgreSQL's CREATE INDEX CONCURRENTLY syntax."""
  88. atomic = False
  89. def describe(self):
  90. return "Concurrently create index %s on field(s) %s of model %s" % (
  91. self.index.name,
  92. ", ".join(self.index.fields),
  93. self.model_name,
  94. )
  95. def database_forwards(self, app_label, schema_editor, from_state, to_state):
  96. self._ensure_not_in_transaction(schema_editor)
  97. model = to_state.apps.get_model(app_label, self.model_name)
  98. if self.allow_migrate_model(schema_editor.connection.alias, model):
  99. schema_editor.add_index(model, self.index, concurrently=True)
  100. def database_backwards(self, app_label, schema_editor, from_state, to_state):
  101. self._ensure_not_in_transaction(schema_editor)
  102. model = from_state.apps.get_model(app_label, self.model_name)
  103. if self.allow_migrate_model(schema_editor.connection.alias, model):
  104. schema_editor.remove_index(model, self.index, concurrently=True)
  105. class RemoveIndexConcurrently(NotInTransactionMixin, RemoveIndex):
  106. """Remove an index using PostgreSQL's DROP INDEX CONCURRENTLY syntax."""
  107. atomic = False
  108. def describe(self):
  109. return "Concurrently remove index %s from %s" % (self.name, self.model_name)
  110. def database_forwards(self, app_label, schema_editor, from_state, to_state):
  111. self._ensure_not_in_transaction(schema_editor)
  112. model = from_state.apps.get_model(app_label, self.model_name)
  113. if self.allow_migrate_model(schema_editor.connection.alias, model):
  114. from_model_state = from_state.models[app_label, self.model_name_lower]
  115. index = from_model_state.get_index_by_name(self.name)
  116. schema_editor.remove_index(model, index, concurrently=True)
  117. def database_backwards(self, app_label, schema_editor, from_state, to_state):
  118. self._ensure_not_in_transaction(schema_editor)
  119. model = to_state.apps.get_model(app_label, self.model_name)
  120. if self.allow_migrate_model(schema_editor.connection.alias, model):
  121. to_model_state = to_state.models[app_label, self.model_name_lower]
  122. index = to_model_state.get_index_by_name(self.name)
  123. schema_editor.add_index(model, index, concurrently=True)
  124. class CollationOperation(Operation):
  125. def __init__(self, name, locale, *, provider="libc", deterministic=True):
  126. self.name = name
  127. self.locale = locale
  128. self.provider = provider
  129. self.deterministic = deterministic
  130. def state_forwards(self, app_label, state):
  131. pass
  132. def deconstruct(self):
  133. kwargs = {"name": self.name, "locale": self.locale}
  134. if self.provider and self.provider != "libc":
  135. kwargs["provider"] = self.provider
  136. if self.deterministic is False:
  137. kwargs["deterministic"] = self.deterministic
  138. return (
  139. self.__class__.__qualname__,
  140. [],
  141. kwargs,
  142. )
  143. def create_collation(self, schema_editor):
  144. if self.deterministic is False and not (
  145. schema_editor.connection.features.supports_non_deterministic_collations
  146. ):
  147. raise NotSupportedError(
  148. "Non-deterministic collations require PostgreSQL 12+."
  149. )
  150. args = {"locale": schema_editor.quote_name(self.locale)}
  151. if self.provider != "libc":
  152. args["provider"] = schema_editor.quote_name(self.provider)
  153. if self.deterministic is False:
  154. args["deterministic"] = "false"
  155. schema_editor.execute(
  156. "CREATE COLLATION %(name)s (%(args)s)"
  157. % {
  158. "name": schema_editor.quote_name(self.name),
  159. "args": ", ".join(
  160. f"{option}={value}" for option, value in args.items()
  161. ),
  162. }
  163. )
  164. def remove_collation(self, schema_editor):
  165. schema_editor.execute(
  166. "DROP COLLATION %s" % schema_editor.quote_name(self.name),
  167. )
  168. class CreateCollation(CollationOperation):
  169. """Create a collation."""
  170. def database_forwards(self, app_label, schema_editor, from_state, to_state):
  171. if schema_editor.connection.vendor != "postgresql" or not router.allow_migrate(
  172. schema_editor.connection.alias, app_label
  173. ):
  174. return
  175. self.create_collation(schema_editor)
  176. def database_backwards(self, app_label, schema_editor, from_state, to_state):
  177. if not router.allow_migrate(schema_editor.connection.alias, app_label):
  178. return
  179. self.remove_collation(schema_editor)
  180. def describe(self):
  181. return f"Create collation {self.name}"
  182. @property
  183. def migration_name_fragment(self):
  184. return "create_collation_%s" % self.name.lower()
  185. class RemoveCollation(CollationOperation):
  186. """Remove a collation."""
  187. def database_forwards(self, app_label, schema_editor, from_state, to_state):
  188. if schema_editor.connection.vendor != "postgresql" or not router.allow_migrate(
  189. schema_editor.connection.alias, app_label
  190. ):
  191. return
  192. self.remove_collation(schema_editor)
  193. def database_backwards(self, app_label, schema_editor, from_state, to_state):
  194. if not router.allow_migrate(schema_editor.connection.alias, app_label):
  195. return
  196. self.create_collation(schema_editor)
  197. def describe(self):
  198. return f"Remove collation {self.name}"
  199. @property
  200. def migration_name_fragment(self):
  201. return "remove_collation_%s" % self.name.lower()
  202. class AddConstraintNotValid(AddConstraint):
  203. """
  204. Add a table constraint without enforcing validation, using PostgreSQL's
  205. NOT VALID syntax.
  206. """
  207. def __init__(self, model_name, constraint):
  208. if not isinstance(constraint, CheckConstraint):
  209. raise TypeError(
  210. "AddConstraintNotValid.constraint must be a check constraint."
  211. )
  212. super().__init__(model_name, constraint)
  213. def describe(self):
  214. return "Create not valid constraint %s on model %s" % (
  215. self.constraint.name,
  216. self.model_name,
  217. )
  218. def database_forwards(self, app_label, schema_editor, from_state, to_state):
  219. model = from_state.apps.get_model(app_label, self.model_name)
  220. if self.allow_migrate_model(schema_editor.connection.alias, model):
  221. constraint_sql = self.constraint.create_sql(model, schema_editor)
  222. if constraint_sql:
  223. # Constraint.create_sql returns interpolated SQL which makes
  224. # params=None a necessity to avoid escaping attempts on
  225. # execution.
  226. schema_editor.execute(str(constraint_sql) + " NOT VALID", params=None)
  227. @property
  228. def migration_name_fragment(self):
  229. return super().migration_name_fragment + "_not_valid"
  230. class ValidateConstraint(Operation):
  231. """Validate a table NOT VALID constraint."""
  232. def __init__(self, model_name, name):
  233. self.model_name = model_name
  234. self.name = name
  235. def describe(self):
  236. return "Validate constraint %s on model %s" % (self.name, self.model_name)
  237. def database_forwards(self, app_label, schema_editor, from_state, to_state):
  238. model = from_state.apps.get_model(app_label, self.model_name)
  239. if self.allow_migrate_model(schema_editor.connection.alias, model):
  240. schema_editor.execute(
  241. "ALTER TABLE %s VALIDATE CONSTRAINT %s"
  242. % (
  243. schema_editor.quote_name(model._meta.db_table),
  244. schema_editor.quote_name(self.name),
  245. )
  246. )
  247. def database_backwards(self, app_label, schema_editor, from_state, to_state):
  248. # PostgreSQL does not provide a way to make a constraint invalid.
  249. pass
  250. def state_forwards(self, app_label, state):
  251. pass
  252. @property
  253. def migration_name_fragment(self):
  254. return "%s_validate_%s" % (self.model_name.lower(), self.name.lower())
  255. def deconstruct(self):
  256. return (
  257. self.__class__.__name__,
  258. [],
  259. {
  260. "model_name": self.model_name,
  261. "name": self.name,
  262. },
  263. )