create_materialized_view_model.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. from django.db.migrations.operations.models import CreateModel
  2. from psqlextra.backend.migrations.state import (
  3. PostgresMaterializedViewModelState,
  4. )
  5. class PostgresCreateMaterializedViewModel(CreateModel):
  6. """Creates the model as a native PostgreSQL 11.x materialzed view."""
  7. serialization_expand_args = [
  8. "fields",
  9. "options",
  10. "managers",
  11. "view_options",
  12. ]
  13. def __init__(
  14. self,
  15. name,
  16. fields,
  17. options=None,
  18. view_options={},
  19. bases=None,
  20. managers=None,
  21. ):
  22. super().__init__(name, fields, options, bases, managers)
  23. self.view_options = view_options or {}
  24. def state_forwards(self, app_label, state):
  25. state.add_model(
  26. PostgresMaterializedViewModelState(
  27. app_label=app_label,
  28. name=self.name,
  29. fields=list(self.fields),
  30. options=dict(self.options),
  31. bases=tuple(self.bases),
  32. managers=list(self.managers),
  33. view_options=dict(self.view_options),
  34. )
  35. )
  36. def database_forwards(self, app_label, schema_editor, from_state, to_state):
  37. """Apply this migration operation forwards."""
  38. model = to_state.apps.get_model(app_label, self.name)
  39. if self.allow_migrate_model(schema_editor.connection.alias, model):
  40. schema_editor.create_materialized_view_model(model)
  41. def database_backwards(
  42. self, app_label, schema_editor, from_state, to_state
  43. ):
  44. """Apply this migration operation backwards."""
  45. model = from_state.apps.get_model(app_label, self.name)
  46. if self.allow_migrate_model(schema_editor.connection.alias, model):
  47. schema_editor.delete_materialized_view_model(model)
  48. def deconstruct(self):
  49. name, args, kwargs = super().deconstruct()
  50. if self.view_options:
  51. kwargs["view_options"] = self.view_options
  52. return name, args, kwargs
  53. def describe(self):
  54. """Gets a human readable text describing this migration."""
  55. description = super().describe()
  56. description = description.replace("model", "materialized view model")
  57. return description