add_list_partition.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. from psqlextra.backend.migrations.state import PostgresListPartitionState
  2. from .partition import PostgresPartitionOperation
  3. class PostgresAddListPartition(PostgresPartitionOperation):
  4. """Adds a new list partition to a :see:PartitionedPostgresModel."""
  5. def __init__(self, model_name, name, values):
  6. """Initializes new instance of :see:AddListPartition.
  7. Arguments:
  8. model_name:
  9. The name of the :see:PartitionedPostgresModel.
  10. name:
  11. The name to give to the new partition table.
  12. values:
  13. Partition key values that should be
  14. stored in this partition.
  15. """
  16. super().__init__(model_name, name)
  17. self.values = values
  18. def state_forwards(self, app_label, state):
  19. model = state.models[(app_label, self.model_name_lower)]
  20. model.add_partition(
  21. PostgresListPartitionState(
  22. app_label=app_label,
  23. model_name=self.model_name,
  24. name=self.name,
  25. values=self.values,
  26. )
  27. )
  28. state.reload_model(app_label, self.model_name_lower)
  29. def database_forwards(self, app_label, schema_editor, from_state, to_state):
  30. model = to_state.apps.get_model(app_label, self.model_name)
  31. if self.allow_migrate_model(schema_editor.connection.alias, model):
  32. schema_editor.add_list_partition(model, self.name, self.values)
  33. def database_backwards(
  34. self, app_label, schema_editor, from_state, to_state
  35. ):
  36. model = from_state.apps.get_model(app_label, self.model_name)
  37. if self.allow_migrate_model(schema_editor.connection.alias, model):
  38. schema_editor.delete_partition(model, self.name)
  39. def deconstruct(self):
  40. name, args, kwargs = super().deconstruct()
  41. kwargs["values"] = self.values
  42. return name, args, kwargs
  43. def describe(self) -> str:
  44. return "Creates list partition %s on %s" % (self.name, self.model_name)