view.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. from typing import Type
  2. from psqlextra.models import PostgresViewModel
  3. from .model import PostgresModelState
  4. class PostgresViewModelState(PostgresModelState):
  5. """Represents the state of a :see:PostgresViewModel in the migrations."""
  6. def __init__(self, *args, view_options={}, **kwargs):
  7. """Initializes a new instance of :see:PostgresViewModelState.
  8. Arguments:
  9. view_options:
  10. Dictionary of options for views.
  11. See: PostgresViewModelMeta for a list.
  12. """
  13. super().__init__(*args, **kwargs)
  14. self.view_options = dict(view_options)
  15. @classmethod
  16. def _pre_new( # type: ignore[override]
  17. cls,
  18. model: Type[PostgresViewModel],
  19. model_state: "PostgresViewModelState",
  20. ) -> "PostgresViewModelState":
  21. """Called when a new model state is created from the specified
  22. model."""
  23. model_state.view_options = dict(model._view_meta.original_attrs)
  24. return model_state
  25. def _pre_clone( # type: ignore[override]
  26. self, model_state: "PostgresViewModelState"
  27. ) -> "PostgresViewModelState":
  28. """Called when this model state is cloned."""
  29. model_state.view_options = dict(self.view_options)
  30. return model_state
  31. def _pre_render(self, name: str, bases, attributes):
  32. """Called when this model state is rendered into a model."""
  33. view_meta = type("ViewMeta", (), dict(self.view_options))
  34. return name, bases, {**attributes, "ViewMeta": view_meta}
  35. @classmethod
  36. def _get_base_model_class(self) -> Type[PostgresViewModel]:
  37. """Gets the class to use as a base class for rendered models."""
  38. return PostgresViewModel