add_range_partition.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. from psqlextra.backend.migrations.state import PostgresRangePartitionState
  2. from .partition import PostgresPartitionOperation
  3. class PostgresAddRangePartition(PostgresPartitionOperation):
  4. """Adds a new range partition to a :see:PartitionedPostgresModel."""
  5. def __init__(self, model_name: str, name: str, from_values, to_values):
  6. """Initializes new instance of :see:AddRangePartition.
  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. from_values:
  13. Start of the partitioning key range of
  14. values that need to be stored in this
  15. partition.
  16. to_values:
  17. End of the partitioning key range of
  18. values that need to be stored in this
  19. partition.
  20. """
  21. super().__init__(model_name, name)
  22. self.from_values = from_values
  23. self.to_values = to_values
  24. def state_forwards(self, app_label, state):
  25. model = state.models[(app_label, self.model_name_lower)]
  26. model.add_partition(
  27. PostgresRangePartitionState(
  28. app_label=app_label,
  29. model_name=self.model_name,
  30. name=self.name,
  31. from_values=self.from_values,
  32. to_values=self.to_values,
  33. )
  34. )
  35. state.reload_model(app_label, self.model_name_lower)
  36. def database_forwards(self, app_label, schema_editor, from_state, to_state):
  37. model = to_state.apps.get_model(app_label, self.model_name)
  38. if self.allow_migrate_model(schema_editor.connection.alias, model):
  39. schema_editor.add_range_partition(
  40. model, self.name, self.from_values, self.to_values
  41. )
  42. def database_backwards(
  43. self, app_label, schema_editor, from_state, to_state
  44. ):
  45. model = from_state.apps.get_model(app_label, self.model_name)
  46. if self.allow_migrate_model(schema_editor.connection.alias, model):
  47. schema_editor.delete_partition(model, self.name)
  48. def deconstruct(self):
  49. name, args, kwargs = super().deconstruct()
  50. kwargs["from_values"] = self.from_values
  51. kwargs["to_values"] = self.to_values
  52. return name, args, kwargs
  53. def describe(self) -> str:
  54. return "Creates range partition %s on %s" % (self.name, self.model_name)